Reputation: 23
I'm trying to run a shell program through python. I need to run a command, then while it's still running and waiting for input to continue, I need to take the output received by the program, and process that data as a string. Then I need to parse some data into that program, and simulate an enter pressing. What would be the best way to achieve this?
Upvotes: 2
Views: 1634
Reputation: 5019
subprocess.Popen
will work for this, but to read and then write and then read again you can't use communicate
(because this will cause the process to end).
Instead, you'll need to work with the process's output pipe (process.stdout
below). This is tricky to get right, because reading on the process's stdout
is blocking, so you sort of need to know when to stop trying to read (or know how much output the process is going to produce).
In this example, the subprocess is a shell script that writes a line of output, and then echoes whatever you give it until it reads EOF.
import subprocess
COMMAND_LINE = 'echo "Hello World!" ; cat'
process = subprocess.Popen(COMMAND_LINE, shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
s = process.stdout.readline().strip()
print(s)
s2 = process.communicate(s)[0]
print(s2)
Gives:
Hello World!
Hello World!
For more complicated cases, you might think about looking at something like pexpect.
Upvotes: 1
Reputation: 1341
Use subprocess.Popen to run your shell application and use communicate
to interact with it.
Upvotes: 1