Reputation: 1288
I have a terminal command that is to be run once. Basically, when you execute the command, the program runs continuously until told otherwise. While the program is running, it will keep outputting strings of text into the terminal. I would like to somehow store these strings as a variable so I can check to see if it contains specific keywords. I tried using os.system, but alas, that does not store the response from the program. Thanks in advance, and I'm sorry for my naivety
Upvotes: 2
Views: 94
Reputation: 76929
To spawn a subprocess running a command, use subprocess.Popen
:
proc = subprocess.Popen(['cat', 'myfile'], stdout = subprocess.PIPE)
By setting stdout
to PIPE
, you'll make cat
output text through a channel that you control.
When Popen
returns, proc.stdout
will be a file-like
object that you can read()
. It also exposes readline()
, for convenience.
readline()
returns the next line of the stream, \n
at the end included. When it returns ''
, there's nothing left to read.
line = proc.stdout.readline()
while line != '':
print line
You can also create a line iterator to walk the output line by line. You can give this iterator to other functions, that can then consume the output of your subprocess without interacting with the process object directly:
iterator = iter(proc.stdout.readline, '')
# Somewhere else in your program...
for line in iterator:
print line
Upvotes: 3