首页 > 解决方案 > 在 Shell 中使用日志重定向时如何获取函数的重调代码?

问题描述

在我的 shell scripts1 中,它可以工作。:</p>

测试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 失败。main在 test2.sh 中如何获取 python-call 的返回码?</p>

标签: pythonshellreturn-code

解决方案


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

例如:

Python代码:

import sys


def exit_with_code():
    sys.exit(5)


exit_with_code()

外壳脚本:

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

输出:

5 0

表示脚本的返回码Python为5,脚本的返回码tee为0。


推荐阅读