bash 在 shell 脚本中运行 Python 脚本 - 检查状态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14447997/
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
Running a Python script within shell script - Check status
提问by Jimmy
Within my shell script I run this command:
在我的 shell 脚本中,我运行以下命令:
python script.py
I was wondering, as a two part question:
我想知道,作为一个两部分的问题:
How can I program my python script to pass a status back to the shell script that ran it depending on what happens in the python script. For example if something goes wrong in the python script have it exit with a code of 1 which is sent back to shell.
How can I get my shell script to read the exit code of python and exit for an error? For example, a status code of anything but 0 then exit.
我如何编写我的 python 脚本以将状态传递回运行它的 shell 脚本,具体取决于 python 脚本中发生的情况。例如,如果 python 脚本出现问题,让它退出,代码为 1,该代码被发送回 shell。
如何让我的 shell 脚本读取 python 的退出代码并退出错误?例如,状态码不是 0,然后退出。
回答by chepner
First, you can pass the desired exit code as an argument to sys.exitin your python script.
首先,您可以将所需的退出代码作为参数传递给sys.exit您的 Python 脚本。
Second, the exit code of the most recently exited process can be found in the bashparameter $?. However, you may not need to check it explicitly:
其次,最近退出的进程的退出代码可以在bash参数中找到$?。但是,您可能不需要明确检查它:
if python script.py; then
echo "Exit code of 0, success"
else
echo "Exit code of $?, failure"
fi
To check the exit code explicitly, you need to supply a conditional expression to the ifstatement:
要显式检查退出代码,您需要为if语句提供条件表达式:
python script.py
if [[ $? = 0 ]]; then
echo "success"
else
echo "failure: $?"
fi

