如何在Python中搜索子流程输出中的特定单词?
我试图搜索一个变量的输出以找到一个特定的单词,然后让它在为真时触发一个响应如何在Python中搜索子流程输出中的特定单词?,python,grep,subprocess,Python,Grep,Subprocess,我试图搜索一个变量的输出以找到一个特定的单词,然后让它在为真时触发一个响应 variable = subprocess.call(["some", "command", "here"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) for word in variable: if word == "myword": print "something something" 我肯定我错过了一些重要的东西,但我就是不知道它
variable = subprocess.call(["some", "command", "here"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for word in variable:
if word == "myword":
print "something something"
我肯定我错过了一些重要的东西,但我就是不知道它是什么
事先谢谢你帮我澄清 使用。返回进程的标准输出<代码>调用仅返回退出状态。(您需要在输出上调用
split
或splitlines
)首先,您应该使用Popen
或check_output
来获取流程输出,然后使用communicate()
方法来获取stdout和stderr,并在这些变量中搜索您的单词:
variable = subprocess.Popen(["some", "command", "here"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = variable.communicate()
if (word in stdout) or (word in stderr):
print "something something"
您需要检查流程的标准,您可以执行以下操作:
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"
这是针对stdout的,您也可以检查stderr,这里还有一些关于子进程的信息。call返回进程的退出代码,而不是它的stdout。这里有一个关于如何捕获命令输出的示例。如果您计划对子流程执行更复杂的操作,可能会更方便。如果输出可能是无限制的,则不应使用
.communicate()
来避免计算机内存不足。您可以逐行读取子流程的输出:
import re
from subprocess import Popen, PIPE
word = "myword"
p = Popen(["some", "command", "here"],
stdout=PIPE, universal_newlines=True)
for line in p.stdout:
if word in line:
for _ in range(re.findall(r"\w+", line).count(word)):
print("something something")
注意:
stderr
未重定向。如果您稍后离开stderr=PIPE
而不读取p.stderr
,则如果进程在stderr上生成足够的输出以填充其OS管道缓冲区,则该进程可能会永远阻塞。请参阅。的可能重复。如果使用.split()
(无参数),则它会在任何空格上拆分。您可以使用re.findall(r“\w+”,text)
在文本中查找单词。注意:.communicate()
如果输出较大或不受限制,则不起作用。如果my_output_列表中的“myword”,则循环可以替换为:
或n=my_output_列表。计数(“myword”)
(如果可能多次出现)