I have a python script a.py
which is run by a shell script b.sh
. I wish to return the result (which is int) of a.py
to b.sh
.
I know I can use sys.exit(result)
in a.py
. But as I wrote set -ex
in b.sh
, the shell script stops after running a.py
. I don't wish to use print(result)
eather because I wish to print other information in a.py
.
Is there any other way to return result from a.py
to b.sh
?
CodePudding user response:
You can return the exit code from the python script and look it up (and reassign to another variable if necessary) in the shell script via $?
:
foo.py:
import sys
sys.exit(35)
foo.sh:
python foo.py
echo $?
Run the scripts:
> sh foo.sh
35
CodePudding user response:
You can do something like this:
{ a.py; result=$?; } || true
# the result of a.py is in $result
|| true
temporarily disables set -e
, and the $?
special variable gets stored to $result
before it gets overwritten by the next command.
The downside is that, if your script actually fails (e.g. by raising an exception), you won't notice that. A more robust solution would be to print the needed result and catch it as output, and print the other output to the standard error.