How to use Python in a Makefile

A little tutorial: How to embed python into a makefile. There are two ways.
1. Using a predefined multiline string:
# Define a multiline string variable for your python script: define MULTILINE_EXAMPLE # A comment in the script. import sys print(sys.argv) endef # It is now available as $(MULTILINE_EXAMPLE) as a makefile variable. export MULTILINE_EXAMPLE # It is now also available as "$$MULTILINE_EXAMPLE" as a shell variable. # Use the predefined multiline string: python-multiline-embed: @python -c "$$MULTILINE_EXAMPLE" foo bar ;
You must be very careful when using multiline strings. Dollar signs can be misinterpreted as either makefile vars or shell vars depending on the context. Only the multiline version allows comments in the script.
2. Direct embed:
python-direct-embed: @# You can put comments outside of the script. @echo 'if 1: ~\ import sys ~\ print(sys.argv) ~\ ' | sed 's/~/\n/' | python - foo bar ;
The direct embed is more complicated, but it allows indentation.
Start the python script with "if 1:" so that you can choose the indentation level.
Be sure to use a single quoted string for the python script. Pass in any variables as command line args.The first command line arg must be a dash "-". This makes the python interpreter read the script from stdin. In the script, you will have to choose a char sequence that will be replaced by a newline char. I have used a single tilde here. Edit the sed portion if you change this.
Each line needs to end in a line-continuation char sequence: a backslash followed immediately by a newline.
Choose a specific version of python for your app and ship it. Python code is not portable even though it seems to be.
I did this and it changed my life.