I am calling a python script from within a shell script. The python script returns error codes in case of failures.
How do I handle these error codes in shell script and exit it when necessary?
If your shell prompt is ... you have an unclosed environment inside python . To interrupt the environment type CTRL-C . If your shell prompt is In [123]: you are in ipython . To exit from ipython type exit() , or CTRL-D then press y .
This can be achieved by calling the sys. exit() function and passing the exit code as an argument. The sys. exit() function will raise a SystemExit exception in the current process, which will terminate the process.
Exit codes are a number between 0 and 255, which is returned by any Unix command when it returns control to its parent process. Other numbers can be used, but these are treated modulo 256, so exit -10 is equivalent to exit 246 , and exit 257 is equivalent to exit 1 .
If the program is the current process in your shell, typing Ctrl-C will stop the Python program.
The exit code of last command is contained in $?
.
Use below pseudo code:
python myPythonScript.py
ret=$?
if [ $ret -ne 0 ]; then
#Handle failure
#exit if required
fi
You mean the $?
variable?
$ python -c 'import foobar' > /dev/null
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named foobar
$ echo $?
1
$ python -c 'import this' > /dev/null
$ echo $?
0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With