Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling exit code returned by python in shell script

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?

like image 873
SpikETidE Avatar asked Jan 10 '13 14:01

SpikETidE


People also ask

How do you exit a shell script in Python?

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 .

How does Python handle exit codes?

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.

What is exit code in shell script?

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 .

How do you exit a Python script in Linux?

If the program is the current process in your shell, typing Ctrl-C will stop the Python program.


2 Answers

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
like image 154
anishsane Avatar answered Oct 15 '22 17:10

anishsane


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
like image 35
Lev Levitsky Avatar answered Oct 15 '22 18:10

Lev Levitsky