python3子进程不提供输出

2024-04-26 17:22:27 发布

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

我有以下问题。在groovy程序中,我启动一个python程序来启动一个子进程。此子进程的输出将被读入变量。(操作系统是ubuntu)

git = subprocess.Popen(args, stdout = subprocess.PIPE, env=environ)
data = git.stdout.read(); 

但是变量总是空的,我不知道为什么。 (在运行的shell中启动Python)


Tags: git程序envreaddata进程ubuntustdout
5条回答

试试这个:

git = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environ)
data, err = git.communicate()
print(data.decode('utf-8'))
print(err.decode('utf-8'))

几乎可以肯定的是,输出是出stderr的,您没有捕获到它,您需要添加一个stderr = subprocess.PIPE并使用communicate,但是如果您使用python>;=2.7,那么check_output将是最好的使用方法,任何非零退出状态都会引发一个CalledProcessError

from subprocess import check_output,CalledProcessError
try:
   data = check_output(args, env=environ)
except CalledProcessError as e:
    print(e.output)
else:
    print(data)

相关问题 更多 >