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

3 投票
5 回答
11920 浏览
提问于 2025-04-18 04:06

我正在尝试在一个变量的输出中搜索一个特定的词,如果找到了这个词,就让程序做出相应的反应。

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

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

我知道我这里可能漏掉了什么重要的东西,但就是搞不清楚是什么。

提前谢谢你们帮我理清思路。

5 个回答

-1

首先,你应该使用 Popencheck_output 来获取程序的输出,然后用 communicate() 方法来获取标准输出和错误输出,并在这些变量中搜索你想要的词:

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"
0

subprocess.call 返回的是进程的退出代码,而不是它的输出内容。你可以在 这个帮助页面 上找到一个示例,教你如何获取命令的输出。如果你打算对子进程做一些更复杂的操作,pexpect 可能会更方便一些。

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(错误输出)没有被重定向。如果你把 stderr=PIPE 留着,但又不去读取 p.stderr 的内容,那么如果这个进程在错误输出上产生了足够多的内容,可能会导致它一直卡住,无法继续运行。想要在输出不受限制的情况下分别获取标准输出和错误输出,可以参考这个回答

2

使用 subprocess.check_output。这个方法会返回程序的标准输出,也就是程序运行后显示的内容。而 call 只会返回程序的退出状态,也就是程序是否成功结束的标志。(你可能需要对输出使用 splitsplitlines 来处理一下。)

2

你需要查看这个程序的标准输出(stdout),你可以这样做:

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"

这段代码是用来查看标准输出的,你也可以检查标准错误输出(stderr)。另外,这里有一些关于字符串分割的信息。

撰写回答