由蟒蛇在shell脚本返回处理退出代码(Handling exit code returned by

2019-07-18 01:57发布

我从一个shell脚本中调用一个python脚本。 该Python脚本返回失败的情况下,错误代码。

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

Answer 1:

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

使用下面的伪代码:

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


Answer 2:

你的意思是在$? 变量 ?

$ 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


Answer 3:

请使用以下流程脚本执行结果的逻辑:

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


文章来源: Handling exit code returned by python in shell script