Python 3.6 subprocess 模块 returncode with tee 命令
Python 3.6 subprocess module returncode with tee command
我正在使用 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
如您所见,子进程捕获标准错误输出,但 returncode
是 0
。
我的 Python 脚本有什么问题?
感谢任何帮助。
return 代码为 0。return 代码是最后一个命令的 return 代码,即使在使用 tee
时也是如此(除非设置了 pipefail 变量).你可以在命令行上自己看看:
$ 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)
我正在使用 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
如您所见,子进程捕获标准错误输出,但 returncode
是 0
。
我的 Python 脚本有什么问题?
感谢任何帮助。
return 代码为 0。return 代码是最后一个命令的 return 代码,即使在使用 tee
时也是如此(除非设置了 pipefail 变量).你可以在命令行上自己看看:
$ 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)