strboul blog

Embed Python code into Makefile


I love the standard UNIX tools. They are ubiquitous yet the commands can be very arcane. bash and make are the programs that are available on almost every systems, but they can become very tedious to work with once you need to do something a bit complex, like when dealing with array or string operations.

Anything I feel that it gets too complex with bash, I just want to switch to vanilla Python1. Python is great. Simple, readable, and has fun syntax (for me!).

On the other hand, make, which is almost 50 years old, is my go-to task runner. There are many alternatives to make today, with modernized versions, but make, as part of the GNU project, it's still very common. It's syntax is one of the funkiest one I've ever seen and it made me my hair pulled out at least a dozen times in the past, I still rely on make as it's also everywhere.

Unlike bash to Python alternative, I don't see really an alternative to make, so I'd rather tame make with Python instead of replacing make with something else.

When make frustrates you for some reason, you can just embed Python into it.

Example code that opens an html file with a browser from Python.

define BROWSER_PYSCRIPT
import os
import sys
import webbrowser
from urllib.request import pathname2url

webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1])))
endef
export BROWSER_PYSCRIPT

BROWSER := python -c "$$BROWSER_PYSCRIPT"

render-and-open:
    echo "<p>Hello world!</p>" > /tmp/index.html
    $(BROWSER) index.html

Then start the command in make.

make render-and-open
echo "<p>Hello world!</p>" > /tmp/index.html
python -c "$BROWSER_PYSCRIPT" /tmp/index.html

  1. Vanilla Python: I mean, is the Python without any external dependencies, just using the standard library. That's quite extensive and has much more than a what I need from a script for the most of times.