Take python exit status and use it in bash command

807 Views Asked by At

I have a Python script that returns a status when it finishes (but not through an output).

sys.exit(status)

And I have to run a bash command that uses that status, the execution is something like:

command --host=xxx --service="xxx" --message="`myscript.py`" -s "ip" -u "user" -p "pass" " --returncode=0

Is there any way to take the return code directly from the "sys.exit(status)"?

I tried changing --returncode=0 to --returncode=$? but it does not work.

3

There are 3 best solutions below

0
Hellmar Becker On BEST ANSWER

After the script exits, bash has the exit code in variable $?. But invoking another command would change that exit code. So you should save it to a variable right after the script returns.

You could write something like:

python3 script.py
status=$?
command --returncode=$status
0
Peter Badida On

Well, you can use templating or hardcode the status in there if you want to be sure that it returns the status you want, but that basically removes the use case of having an exit code/status. (ref)

Other than that, the exit code is available by POSIX shell in $? variable, but you can also return an output you want and check for that e.g. return common output in STDOUT and return errors, or for your case a custom "exit code" string in STDERR like this.

0
Anil Kumar Gupta On

You could try something like:

sys_exit_code.py

import sys
status = 12
sys.exit(status)

sys_exit_code.sh

python sys_exit_code.py
RC=$?
echo "Exit code $RC"

run you bash script

sh sys_exit_code.sh