16

我正在从 shell 脚本中调用 python 脚本。如果发生故障,python 脚本会返回错误代码。

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

4

3 回答 3

30

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

使用下面的伪代码:

python myPythonScript.py
ret=$?
if [ $ret -ne 0 ]; then
     #Handle failure
     #exit if required
fi
于 2013-01-10T14:04:54.133 回答
3

你的意思$?变量

$ 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
于 2013-01-10T14:04:56.937 回答
2

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

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
于 2018-08-17T14:52:18.657 回答