111111
111111

Reputation: 16168

Python subprocess: get all stdout data after proccess has terminated

I am using subprocess in python to invoke another executable, write some data to it's stdin (close the stream once everything is written - which is how the sub process knows it's recieved everything) and then receive all of it's stdout data after it's terminated - which it will after some period of time.

In pseudo code:

I have tried the following:

import subprocess
p = subprocess.Popen([cmd], 
stdout=subprocess.PIPE,stdin=subprocess.PIPE)
p.stdin.write(str(data))
p.stdin.close()
p.wait()
result = p.communicate()[0]

However I get the following stack trace:

    result = p.communicate()[0]
  File "/usr/lib64/python2.7/subprocess.py", line 800, in communicate .
    return self._communicate(input)
  File "/usr/lib64/python2.7/subprocess.py", line 1396, in _communicate
    self.stdin.flush()
  ValueError: I/O operation on closed file

Please advise

Upvotes: 0

Views: 212

Answers (1)

Daniel
Daniel

Reputation: 42778

Use communicate:

import subprocess
p = subprocess.Popen([cmd], stdout=subprocess.PIPE, stdin=subprocess.PIPE)
result = p.communicate(data)[0]

Upvotes: 1

Related Questions