带有tee命令的Python 3.6子过程模块返回代码

问题描述 投票:0回答:1

我正在使用Python 3.6.9调用以下bash脚本:

run_cmds.sh

ls dir_doesnt_exist | tee log

这里是Python代码:

import subprocess 
from subprocess import PIPE

cmd = subprocess.run(['bash','run_cmds.sh'], stdout=PIPE, stderr=PIPE)

print(cmd.stderr.decode())
print("The returned code is:", cmd.returncode)

运行Python代码,得到以下内容:

ls: cannot access 'dir_doesnt_exist': No such file or directory

The returned code is: 0

您可以看到,子流程捕获了标准错误输出,但returncode0

我的Python脚本怎么了?

感谢您的帮助。

python bash subprocess tee
1个回答
0
投票

返回码是0。您可以在命令行上自己看到它:

$ ls dir_doesnt_exist | tee log
ls: dir_doesnt_exist: No such file or directory

$ echo $?
0

但是,如果删除管道|,将获得非零的退出代码

$ ls dir_doesnt_exist
ls: dir_doesnt_exist: No such file or directory

$ echo $?
1

因此,当使用tee时,您必须检查$ PIPETSTATUS变量而不是常规退出代码

$ ls dir_doesnt_exist | tee log
ls: dir_doesnt_exist: No such file or directory

$ echo ${PIPESTATUS[0]}
1

尝试像这样制作您的python代码

import subprocess 
from subprocess import PIPE

cmd = subprocess.run(['bash','run_cmds.sh; exit ${PIPESTATUS[0]}'], stdout=PIPE, stderr=PIPE)

print(cmd.stderr.decode())
print("The returned code is:", cmd.returncode)
© www.soinside.com 2019 - 2024. All rights reserved.