【问题标题】:How do you search subprocess output in Python for a specific word?如何在 Python 中搜索子进程输出以查找特定单词?
【发布时间】:2014-04-24 14:41:58
【问题描述】:

我正在尝试搜索变量的输出以查找特定单词,然后让它触发响应,如果为真。

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

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

我确定我在这里遗漏了一些重要的东西,但我就是不知道它是什么。

在此先感谢您直言不讳。

【问题讨论】:

标签: python grep subprocess


【解决方案1】:

你需要检查进程的标准输出,你可以这样做:

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的信息

【讨论】:

  • 如果你使用.split()(无参数),那么它会在任何空格上分割。您可以使用re.findall(r"\w+", text) 在文本中查找单词。注意:.communicate() 在输出很大或无限制时不起作用。 You could read line by line instead.
  • 如果可能出现多次,循环可以替换为if "myword" in my_output_list:n = my_output_list.count("myword")
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    subprocess.call 返回进程的退出代码,而不是它的标准输出。 this help page 上有一个关于如何捕获命令输出的示例。如果您打算对子流程做一些更复杂的事情,pexpect 可能更方便。

    【讨论】:

      【解决方案4】:

      如果输出可能是无限的,那么您不应该使用.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 管道缓冲区,则该进程可能会永远阻塞。见this answer if you want to get both stdout/stderr separately in the unlimited case

      【讨论】:

        【解决方案5】:

        首先你应该使用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"
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-05-27
          • 2015-09-15
          • 2017-08-28
          • 2019-12-12
          • 2022-12-06
          • 1970-01-01
          • 1970-01-01
          • 2015-05-22
          相关资源
          最近更新 更多