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.)
Author by
PythonNewb
Updated on June 05, 2022Comments
-
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.
-
mmmmmm about 10 yearspossible duplicate of Wrap subprocess' stdout/stderr
-
-
jfs about 10 yearsIf you use
.split()
(no argument) then it splits on any whitespace. You could usere.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 about 10 yearsthe loop could be replaced by
if "myword" in my_output_list:
orn = my_output_list.count("myword")
if multiple occurences are possible