3

Can somebody help me to find a way to capture the return value from a python script in Makefile.I have a scenario where the source code is getting build through the Makefile and it should throw a build error when python script reruns a failure.

myMakefile.mak

python mySample.py <arg1> <arg2> // Invoking python script here, How to get script's return value?

mySample.py

SUCCESS 0
FAIL 1

if(true)
  exit(SUCCESS)
else:
  exit(FAIL)

Thanks in advance.

Joe
  • 63
  • 1
  • 6
  • I am not sure but I think that if the Python script fails then the error level will raise as for any other application and therefore make will fail too. Now that's not an error you can manage in the Makefile so if you want more options to manage this error or to catch a result from your python script into your Makefile, I'm out. – Tim Jun 14 '16 at 20:35

2 Answers2

2

If your python script exits with a non-zero code, make will detect this and tell you that an error occurred. So you don't need to do anything more.

Example, if I have a program foo.py that does this:

print 'running foo'
exit(1)

And a Makefile like this:

foo:
    python foo.py

And I run make foo, I get the output:

python foo.py

running foo

make: *** [foo] Error 1

So it detected the error.


If on the other hand, what you want to do is record the return value of a command in a Makefile, you can use the $? variable, which stores the last return value of a command.

A couple things to note:

  • the dollar sign has to be escaped in a Makefile, so it becomes $$? in the command
  • since each command in a Makefile is run in a separate shell, you must capture the output in the same subshell as the command you're running (i.e. make the output capture part of the same line as the command you care about)

Example:

build:
    python mySample.py ; echo $$? > output

After running make, you will have a file named output that contains the return value of mySample.py.

Community
  • 1
  • 1
xgord
  • 4,606
  • 6
  • 30
  • 51
  • 1
    Though unless you specifically want `make` to ignore failures, you will need to capture and relay the exit status somehow; perhaps `python mySample.py; rc=$$?; echo "$$rc" >output; exit $$rc` – tripleee Jun 15 '16 at 08:36
0

One way to do it would be to have your python script write the value you want to use in the makefile to an output file. Then your makefile could read in the value from that intermediary file.

Example:

with open("intermediary.tmp", "wb") as h:
    h.write(SUCCESS)