store return value of a Python script in a bash script store return value of a Python script in a bash script python python

store return value of a Python script in a bash script


sys.exit(myString) doesn't mean "return this string". If you pass a string to sys.exit, 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.

example:

test.py

print "something"exit('ohoh') 

t.sh

va=$(python test.py 2>&1)                                                                                                                    mkdir $va

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.

import script1import script2if __name__ == '__main__':    filename = script1.run(sys.args)    script2.run(filename)


sys.exit() should return an integer, not a string:

sys.exit(1)

The value 1 is in $?.

$ cat e.pyimport syssys.exit(1)$ python e.py$ echo $?1

Edit:

If you want to write to stderr, use sys.stderr.


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 call sys.exit(0), and capture the output in the shell.