获取 python 退出状态并在 bash 命令中使用它

Take python exit status and use it in bash command

我有一个 Python 脚本,当它完成时 return 是一个状态(但不是通过输出)。

sys.exit(status)

而且我必须 运行 一个使用该状态的 bash 命令,执行类似于:

command --host=xxx --service="xxx" --message="`myscript.py`" -s "ip" -u "user" -p "pass" " --returncode=0

有没有办法直接从“sys.exit(状态)”中获取return代码?

我尝试将 --returncode=0 更改为 --returncode=$? 但它不起作用。

脚本退出后,bash在变量$?中有退出代码。但是调用另一个命令会更改该退出代码。所以你应该在脚本 returns.

之后将它保存到一个变量中

你可以这样写:

python3 script.py
status=$?
command --returncode=$status

嗯,你可以用templating or hardcode the status in there if you want to be sure that it returns the status you want, but that basically removes the use case of having an exit code/status. ()

除此之外,退出代码可通过 POSIX shell 在 $? 变量中获得,但您也可以 return 您想要的输出并检查它例如return STDOUT 中的常见输出和 return 错误,或者对于您的情况,STDERR like this.

中的自定义“退出代码”字符串

您可以尝试类似的方法:

sys_exit_code.py

import sys
status = 12
sys.exit(status)

sys_exit_code.sh

python sys_exit_code.py
RC=$?
echo "Exit code $RC"

运行 你 bash 脚本

sh sys_exit_code.sh