1

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.

marc
  • 949
  • 14
  • 33
  • 2
    `p.communicate()` returns the output. – jasonharper Aug 02 '18 at 18:29
  • Any particular reason you're not using `subprocess.run()` or the legacy `subprocess.check_output()`? You should avoid `Popen` if you can precisely because it's tricky to get right. – tripleee Aug 02 '18 at 18:29
  • @jasonharper, `p.communicate()` returns `bound method Popen.communicate of – marc Aug 02 '18 at 18:34
  • `output, error = p.communicate()` should work, that output looks like you are just printing `p.communicate` (without the parentheses). – cdarke Aug 02 '18 at 18:36

2 Answers2

2

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)
Niko Föhr
  • 28,336
  • 10
  • 93
  • 96
cdarke
  • 42,728
  • 8
  • 80
  • 84
0

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

Zags
  • 37,389
  • 14
  • 105
  • 140