2

I am trying to run a command, then later run another command in the same environment (say if I set an environment variable in the first command, I want it to be available to the second command). I tried this:

import subprocess

process = subprocess.Popen("echo \"test\"", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE);

process.stdin.write("echo \"two\"\n")
process.stdin.flush()

stdout, stderr = process.communicate()
print "stdout: " + stdout
print "stderr: " + stderr

but the output is:

stdout: test

stderr:

Where I'd hope for it to be something like:

stdout: test
two

stderr:

Can anyone see what is wrong?

David Doria
  • 9,873
  • 17
  • 85
  • 147

1 Answers1

2

The problem is that you are writing to the stdin of the process echo, which is not reading from its stdin, rather than to something like bash which continues to read stdin. To get the effect you want, look at the following code:

import subprocess
process = subprocess.Popen("/bin/bash", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE);

process.stdin.write("echo \"test\"\n")
process.stdin.write("echo \"two\"\n")
process.stdin.flush()

stdout, stderr = process.communicate()
print "stdout: " + stdout
print "stderr: " + stderr

Output:

stdout: test
two

stderr: 

Update: Take a look at this question to resolve the streaming output issue.

Community
  • 1
  • 1
merlin2011
  • 71,677
  • 44
  • 195
  • 329
  • That is much closer. Now if in between commands I want to get the output (I want the output of one command at a time), what would I do? communicate() seems to get the the end of the output so then I get a : ValueError: I/O operation on closed file (see edit) – David Doria Apr 17 '14 at 18:39
  • You really should ask a second question for your second question, @DavidDoria, but the quick answer is that the whole point of `.communicate()` is to close `stdin`/`stdout`; you'll need to instead read/write to the handles in a loop and close manually when you're done. – Benjamin Pollack Apr 17 '14 at 18:56
  • @DavidDoria, I agree, that is technically a separate question, but if the linked question resolves your issue, it may save you the time of asking. :) – merlin2011 Apr 17 '14 at 18:57
  • @merlin2011 Sorry guys, I'll move it. The linked question doesn't actually show how to do what they are suggesting, as far as I can tell. – David Doria Apr 17 '14 at 18:59
  • @DavidDoria, Please accept this answer if it resolves the original issue, so that people are not confused. – merlin2011 Apr 17 '14 at 19:11
  • @merlin2011 Sorry for the confusion. I accepted this answer, truncated the question to remove the second question, and moved it to here: http://stackoverflow.com/questions/23141676/get-the-output-of-multiple-commands-from-subprocess-popen – David Doria Apr 17 '14 at 19:21