简体   繁体   English

在 shell 脚本中运行 Python 脚本 - 检查状态

[英]Running a Python script within shell script - Check status

Within my shell script I run this command:在我的 shell 脚本中,我运行以下命令:

python script.py

I was wondering, as a two part question:我想知道,作为一个两部分的问题:

  1. 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.我如何编写我的 python 脚本以将状态传递回运行它的 shell 脚本,具体取决于 python 脚本中发生的情况。 For example if something goes wrong in the python script have it exit with a code of 1 which is sent back to shell.例如,如果 python 脚本中出现问题,让它退出,代码为 1,该代码被发送回 shell。

  2. How can I get my shell script to read the exit code of python and exit for an error?如何让我的 shell 脚本读取 python 的退出代码并退出错误? For example, a status code of anything but 0 then exit.例如,状态码不是 0,然后退出。

First, you can pass the desired exit code as an argument to sys.exit in your python script.首先,您可以将所需的退出代码作为参数sys.exit给 Python 脚本中的sys.exit

Second, the exit code of the most recently exited process can be found in the bash parameter $?其次,最近退出的进程的退出代码可以在bash参数$? . . However, you may not need to check it explicitly:但是,您可能不需要明确检查它:

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 if statement:要显式检查退出代码,您需要为if语句提供条件表达式:

python script.py
if [[ $? = 0 ]]; then
    echo "success"
else
    echo "failure: $?"
fi

Hate to resurrect a dinosaur but while this selected answer worked as written I wanted to add a variation where one can check against multiple exit codes.讨厌复活一只恐龙,但是虽然这个选定的答案按书面方式工作,但我想添加一个变体,可以检查多个退出代码。 $? only seems to retrieve the exit code of the last executed program one time.似乎只检索上一次执行的程序的退出代码一次。 So if you need to check the exit code against multiple cases, it is necessary to assign $?所以如果需要针对多种情况检查退出码,就需要赋值$? to a variable and then check the variable, a la (using @chepner 's example):到一个变量,然后检查变量,一个 la(使用 @chepner 的例子):

python script.py
exit_code=$?
if [[ $exit_code = 0 ]]; then
    echo "success"
elif [[ $exit_code = 1 ]]; then
    echo "a different form of success, maybe"
else
    echo "failure: $exit_code"
fi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM