Skip to content Skip to sidebar Skip to footer

Persistent Subprocess.popen Session

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 se

Solution 1:

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: " + stdoutprint"stderr: " + stderr

Output:

stdout: test
two

stderr: 

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

Post a Comment for "Persistent Subprocess.popen Session"