I want to execute a python script from a bash script, and I want to store the output of the python script in a variable.
In my python script, I print some stuff to screen and at the end I return a string with:
In my bash script, I did the following:
outputString=`python myPythonScript arg1 arg2 arg3 `
But then when I check the value of
echo $outputString I get everything that the Python script had printed to screen, but not the return value
How should I do this?
EDIT: I need the string because that tells me where a file created by the Python script is located. I want to do something like:
fileLocation=`python myPythonScript1 arg1 arg2 arg1` python myPythonScript2 $fileLocation
This question is tagged with
~ Asked on 2012-08-10 11:35:36
sys.exit(myString) doesn't mean "return this string". If you pass a string to
sys.exit will consider that string to be an error message, and it will write that string to
stderr. The closest concept to a return value for an entire program is its exit status, which must be an integer.
If you want to capture output written to stderr, you can do something like
python yourscript 2> return_file
You could do something like that in your bash script
output=$((your command here) 2> &1)
This is not guaranteed to capture only the value passed to
sys.exit, though. Anything else written to stderr will also be captured, which might include logging output or stack traces.
print "something" exit('ohoh')
va=$(python test.py 2>&1) mkdir $va
Not sure why but in that case, I would write a main script and two other scripts... Mixing python and bash is pointless unless you really need to.
import script1 import script2 if __name__ == '__main__': filename = script1.run(sys.args) script2.run(filename)
~ Answered on 2012-08-10 11:41:02
sys.exit() should return an integer, not a string:
1 is in
$ cat e.py import sys sys.exit(1) $ python e.py $ echo $? 1
If you want to write to stderr, use
~ Answered on 2012-08-10 11:37:37