如何在Python中搜索子进程输出的特定词语?

3
我正在尝试搜索变量的输出以查找特定单词,如果为True,则触发响应。
variable = subprocess.call(["some", "command", "here"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

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

我肯定我错过了什么重要的东西,但我就是想不出来是什么。
感谢您提前纠正。

可能是Wrap subprocess' stdout/stderr的重复问题。 - mmmmmm
5个回答

2
您需要检查进程的标准输出,您可以这样做:
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"

这是用来输出标准输出的,你也可以检查标准错误信息。并且这里有一些关于分割字符串的信息。


如果您使用.split()(无参数),则会在任何空格上进行拆分。 您可以使用re.findall(r"\w+", text)在文本中查找单词。注意:如果输出很大或无限,则.communicate()无法正常工作。您可以逐行阅读 - jfs
循环可以被替换为 if "myword" in my_output_list: 或者 n = my_output_list.count("myword") 如果可能存在多个出现。 - jfs

2

使用 subprocess.check_output 方法。该方法返回进程的标准输出。而 call 方法只返回退出状态。(您需要在输出上调用 splitsplitlines 方法)


0
如果输出可能是无限的,那么您不应该使用 .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`未被重定向。如果您在稍后不从`p.stderr`读取的情况下保留`stderr=PIPE`,则进程可能会永远阻塞,如果它生成足够的输出以填充其操作系统管道缓冲区,则会发生这种情况。如果您想在无限制的情况下分别获取`stdout/stderr`,请参见此答案

0

subprocess.call 返回的是进程的退出码,而不是它的标准输出。这个帮助页面上有一个示例,展示如何捕获命令的输出。如果您计划在子进程中执行更复杂的操作,pexpect 可能更方便。


-1
首先,您应该使用Popencheck_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"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接