Reputation: 10273
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?
Upvotes: 2
Views: 5273
Reputation: 75579
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.
Upvotes: 3