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:
sys.exit(myString)
In my bash script, I did the following:
outputString=`python myPythonScript arg1 arg2 arg3 `
But then when I check the value of outputString
with echo $outputString
I get everything that the Python script had printed to screen, but not the return value myString
!
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
In addition to what Tichodroma said, you might end up using this syntax:
Do not use
sys.exit
like this. When called with a string argument, the exit code of your process will be 1, signaling an error condition. The string is printed to standard error to indicate what the error might be.sys.exit
is not to be used to provide a "return value" for your script.Instead, you should simply print the "return value" to standard output using a
print
statement, then callsys.exit(0)
, and capture the output in the shell.sys.exit()
should return an integer, not a string:The value
1
is in$?
.Edit:
If you want to write to stderr, use
sys.stderr
.Python documentation for sys.exit([arg])says:
Moreover to retrieve the return value of the last executed program you could use the $? bash predefined variable.
Anyway if you put a string as arg in sys.exit() it should be printed at the end of your program output in a separate line, so that you can retrieve it just with a little bit of parsing. As an example consider this:
read it in the docs. If you return anything but an
int
orNone
it will be printed tostderr
.To get just stderr while discarding stdout do:
sys.exit(myString)
doesn't mean "return this string". If you pass a string tosys.exit
,sys.exit
will consider that string to be an error message, and it will write that string tostderr
. 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
You could do something like that in your bash script
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.example:
test.py
t.sh
bash t.sh
edit
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.