Python – Using embedded python script in Makefile

makepython

I'm trying to run a Python snippet inside a Make target, but I'm having trouble trying to figure out how these things work in Make.

Here is my attempt so far:

define BROWSER_PYSCRIPT
import os, webbrowser, sys
try:
    from urllib import pathname2url
except:
    from urllib.request import pathname2url

webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1])))
endef
BROWSER := $(shell python -c '$(BROWSER_PYSCRIPT)')

I wanted to use $(BROWSER) in a target like:

docs:
    #.. compile docs
    $(BROWSER) docs/index.html

Is this really a bad idea?

Best Answer

Related: https://stackoverflow.com/q/649246/4937930

You cannot recall a multi-line variable as is in a single recipe, it rather gets expanded to multiple recipes and causes syntax error.

A possible workaround would be:

export BROWSER_PYSCRIPT
BROWSER := python -c "$$BROWSER_PYSCRIPT"

docs:
        #.. compile docs
        $(BROWSER) docs/index.html
Related Question