Skip to content
Advertisement

How to add the module path used by the python script in the Makefile?

I want to add command to run python script inside Makefile.

THIS_DIR := $(dir $(abspath $(lastword $(MAKEFILE_LIST))))
.PHONY: default analyse
analyse: 
    export PYTHONPATH=${PYTHONPATH}:${THIS_DIR}/tools
    python  ${THIS_DIR}/runScripts/attack_spectre/analyse_log.py

Below is the directory structure. Among them, analyze_log.py uses the classes in tools/fileOp.py.

runScripts/attack_spectre/
├── analyse_log.py
└── trace.out
tools/
├── fileOp.py
├── GeneralOp.py
├── plotFig.py
├── __pycache__
│   ├── fileOp.cpython-39.pyc
│   ├── GeneralOp.cpython-39.pyc
│   └── structureOp.cpython-39.pyc
├── settingOp.py
└── structureOp.py
Makefile

I used the method below at first, but when I execute python analyse_log.py in the directory where analyse_log.py is, it is correct. But when I use the above Makefile to execute, then it doesn’t work. Of course I can also use absolute paths. But since I sometimes mount it in the docker image to execute, and sometimes execute it outside the image, the absolute path is not very convenient (it doesn’t seem reasonable to add it directly to the system path).

How can I temporarily add the python library to the system path in the Makefile?

And I found that with the following method, I can’t jump to the function definition? Is there any way to solve this?

sys.path.append(os.path.dirname(__file__)+"/../../tools")
print(os.path.dirname(__file__))
from fileOp import FileOp

Advertisement

Answer

Every individual logical line in a makefile is run in a different shell. This rule:

analyse: 
        export PYTHONPATH=${PYTHONPATH}:${THIS_DIR}/tools
        python  ${THIS_DIR}/runScripts/attack_spectre/analyse_log.py

is run in a way equivalent to this:

/bin/sh -c 'export PYTHONPATH=${PYTHONPATH}:${THIS_DIR}/tools'
/bin/sh -c 'python  ${THIS_DIR}/runScripts/attack_spectre/analyse_log.py'

So, any variables you set in the first line have no effect on the second line, because they’re run in a separate shell that then exits.

You need to combine both physical lines in the recipe into one logical line so they are run in the same shell. You can combine lines with backslash. So write your rule like this:

analyse: 
        export PYTHONPATH=${PYTHONPATH}:${THIS_DIR}/tools ; 
        python  ${THIS_DIR}/runScripts/attack_spectre/analyse_log.py

(note the extra ; ) and then make will run it like this:

/bin/sh -c 'export PYTHONPATH=${PYTHONPATH}:${THIS_DIR}/tools; 
            python  ${THIS_DIR}/runScripts/attack_spectre/analyse_log.py'
3 People found this is helpful
Advertisement