处理shell脚本中python返回的退出代码

时间:2013-01-10 14:01:37

标签: bash shell python-2.7 error-handling

我在shell脚本中调用python脚本。如果失败,python脚本将返回错误代码。

如何在shell脚本中处理这些错误代码并在必要时退出?

3 个答案:

答案 0 :(得分:13)

最后一个命令的退出代码包含在$?

使用以下伪代码:

python myPythonScript.py
ret=$?
if [ $ret -ne 0 ]; then
     #Handle failure
     #exit if required
fi

答案 1 :(得分:3)

你的意思是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

答案 2 :(得分:1)

请使用以下逻辑来处理脚本执行结果:

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