I have a python script with sys.exit(0) or sys.exit(-1) in the end (0 or 1 depending on whether an error has occurred). How do I store this 0 or 1 in a variable? For example, in an environment variable or in a variable used by a perl script
2 Answers
If you run your python code in a normal shell you have the $? variable:
$ python yourscript.py
$ echo $? # this will echo the sys.exit value
This is also valid inside your perl script:
system("python yourscript.py");
if ($? == -1) {
print "failed to execute: $!\n";
}
elsif ($? & 127) {
printf "child died with signal %d, %s coredump\n",
($? & 127), ($? & 128) ? 'with' : 'without';
}
else {
printf "child exited with value %d\n", $? >> 8;
}
Comments
If you are in windows use %ERRORLEVEL%:
CMDPROMPT>python
Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win 32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.exit(-1)
CMDPROMPT>echo %ERRORLEVEL%
-1
CMDPROMPT>python
Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win 32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.exit(0)
CMDPROMPT>echo %ERRORLEVEL%
0
CMDPROMPT>