Handling exit code returned by python in shell scr

2019-01-19 16:33发布

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?

3条回答
forever°为你锁心
2楼-- · 2019-01-19 16:57

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
查看更多
小情绪 Triste *
3楼-- · 2019-01-19 17:01

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
查看更多
迷人小祖宗
4楼-- · 2019-01-19 17:04

Please use logic below to process script execution result:

python myPythonScript.py
# $? =  is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. 
if [ $? -eq 0 ]
then
  echo "Successfully executed script"
else
  # Redirect stdout from echo command to stderr.
  echo "Script exited with error." >&2
fi
查看更多
登录 后发表回答