从子进程输出python读取

从子进程输出python读取,python,popen,Python,Popen,我正在使用“Popen”运行子进程。我需要阻塞,直到这个子进程完成,然后读取它的输出 p = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE, encoding="utf-8") p.communicate(): output = p.stdout.readline() print(output) 我得到一个错误 ValueError: I/O operation on closed file. 如何在子流程完成后读取输出,但我不想使用

我正在使用“Popen”运行子进程。我需要阻塞,直到这个子进程完成,然后读取它的输出

p = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE, encoding="utf-8")
p.communicate():
output = p.stdout.readline()
print(output)
我得到一个错误

ValueError: I/O operation on closed file.
如何在子流程完成后读取输出,但我不想使用poll(),因为子流程需要时间,而且我需要等待其完成。

这应该可以:

p = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE, encoding="utf-8")
output, error = p.communicate()

print(output)
if error:
    print('error:', error, file=sys.stderr)
但是,现在首选
subprocess.run()

p = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

print("output:", p.stdout)

if proc.stderr:
    print("error:", p.stderr, file=sys.stderr)

使用。它返回命令的输出。

p.communicate()
返回输出。是否有任何特定原因导致您没有使用
子流程。run()
或旧版
子流程。请检查输出()?如果可以的话,你应该避免Popen
,因为这很难正确操作。@jasonharper,
p.communicate()
返回
绑定方法Popen.communicate of
输出,error=p.communicate()
应该可以工作,该输出看起来就像你正在打印
p.communicate
(没有括号)。