bash 在shell脚本中处理python返回的退出代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14259660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Handling exit code returned by python in shell script
提问by SpikETidE
I am calling a python script from within a shell script. The python script returns error codes in case of failures.
我正在从 shell 脚本中调用 python 脚本。如果出现故障,python 脚本会返回错误代码。
How do I handle these error codes in shell script and exit it when necessary?
如何在 shell 脚本中处理这些错误代码并在必要时退出它?
回答by anishsane
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
回答by Lev Levitsky
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
回答by Andriy Ivaneyko
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