Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you search subprocess output in Python for a specific word?

I'm trying to search through a variable's output to find a specific word, then have that trigger a response if True.

variable = subprocess.call(["some", "command", "here"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

for word in variable:
    if word == "myword":
        print "something something"

I'm sure I'm missing something big here, but I just can't figure out what it is.

Thanks in advance for setting me straight.

like image 240
PythonNewb Avatar asked Mar 15 '26 21:03

PythonNewb


2 Answers

You need to check the stdout of the process, you can do something like that:

mainProcess = subprocess.Popen(['python', file, param], stdout=subprocess.PIPE, stderr=subprocess.PIPE)  
communicateRes = mainProcess.communicate() 
stdOutValue, stdErrValue = communicateRes

# you can split by any value, here is by space
my_output_list = stdOutValue.split(" ")

# after the split we have a list of string in my_output_list 
for word in my_output_list :
    if word == "myword":
        print "something something"

This is for stdout, you can check the stderr also, Also here is some info about split

like image 159
Kobi K Avatar answered Mar 21 '26 19:03

Kobi K


Use subprocess.check_output. That returns the standard output from the process. call only returns the exit status. (You'll want to call split or splitlines on the output.)

like image 42
Fred Foo Avatar answered Mar 21 '26 20:03

Fred Foo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!