read from subprocess output python

2019-08-24 13:05发布

问题:

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)

I get an error that

ValueError: I/O operation on closed file.

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.

回答1:

This should work:

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)

However, subprocess.run() is preferred these days:

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

print("output:", p.stdout)

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


回答2:

Use subprocess.check_output. It returns the output of the command.



标签: python popen