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

10,214

Solution 1

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

Solution 2

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.)

Share:
10,214
PythonNewb
Author by

PythonNewb

Updated on June 05, 2022

Comments

  • PythonNewb
    PythonNewb almost 2 years

    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.

  • jfs
    jfs about 10 years
    If you use .split() (no argument) then it splits on any whitespace. You could use re.findall(r"\w+", text) to find words in a text. Note: .communicate() doesn't work if the output is large or unlimited. You could read line by line instead.
  • jfs
    jfs about 10 years
    the loop could be replaced by if "myword" in my_output_list: or n = my_output_list.count("myword") if multiple occurences are possible