在Shell中使用日志重定向时,如何获取函数的返回代码?

2024-04-19 23:46:20 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的shell脚本中,它是有效的:

测试1.sh

python main.py
if [[ $? -ne 0 ]]
then
exit
fi

测试2.sh

python main.py 2>&1 | tee log.txt 
if [[ $? -ne 0 ]]
then
exit
fi

脚本2失败。如何在test2.sh中获得python调用main的返回代码


Tags: 代码pytxt脚本logifmainsh
3条回答

您可以在if之外执行重定向,也可以避免使用反模式。你知道吗

if ! python main.py; then
   exit
fi 2>&1 | tee log.txt

(见Why is testing "$?" to see if a command succeeded or not, an anti-pattern?

您为posixshell添加了问题标签,而且AFIK,在posixshell中无法实现这一点。但是,许多其他shell都有一个特性,允许这样做。你知道吗

例如,如果可以使用bash,就可以使用PIPESTATUS,正如这里已经建议的那样。如果选择Zsh,则有一个类似的数组,名为pipestatus。你知道吗

如果您想使用ksh,您没有一个等价的特性,但是here讨论了如何在kornshell中处理这个问题。你知道吗

如果在一行中使用多个命令,则需要使用PIPESTATUS为每个命令获取正确的返回代码。你知道吗

例如:

Python代码:

import sys


def exit_with_code():
    sys.exit(5)


exit_with_code()

Shell脚本:

python3 test.py  2>&1 | tee log.txt
echo "${PIPESTATUS[0]} ${PIPESTATUS[1]}"

输出:

5 0

这意味着Python脚本的返回码是5,tee脚本的返回码是0。你知道吗

相关问题 更多 >