从子进程输出python读取 [英] read from subprocess output python

查看:95
本文介绍了从子进程输出python读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用'Popen'运行一个子进程.我需要阻塞直到该子进程完成,然后读取其输出.

I am running a subprocess using 'Popen'. I need to block till this subprocess finishes and then read its output.

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(),因为子进程需要时间,而且无论如何我都需要等待其完成.

How can I read the output after the subprocess finishes, I do not want to use poll() though as the subprocess takes time and I would need to wait for its completion anyway.

推荐答案

这应该有效:

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)

这篇关于从子进程输出python读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆