【问题标题】:Check output of a python command检查 python 命令的输出
【发布时间】:2013-08-17 03:46:14
【问题描述】:

我有一个 python 脚本,它尝试运行外部命令并查找命令的结果。它需要使用外部命令输出中的值'count='

COUNT_EXP = re.compile("count=(.*)")
cmd = [] # external command
p = subprocess.Popen(cmd,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.STDOUT)
      for line in iter(p.stdout.readline, b''):
          result = COUNT_EXP.match(line)
          if result:
              print "count= " + result.group(1)
              return int(result.group(1))

当我尝试运行我的脚本时,我的外部命令 ("cmd") 得到执行,我在 shell 中看到 count=10。但是为什么我的 python 在上面的 'if' 子句中找不到并打印出 "count= 10?"?

【问题讨论】:

  • 您的 if 子句可能评估为 False,因此您永远不会打印计数。也许您的 python 工作目录不包含该文件。

标签: python


【解决方案1】:

我编写了以下 C 程序:

#include "stdio.h"

int main() {
    printf ("count=199");
    return 0;
}

...我称之为 countOutput.c 和以下 Python 脚本,从你的修改:

import subprocess, re

COUNT_EXP = re.compile("count=(.*)")
cmd = "./countOutput" # external command
p = subprocess.Popen(cmd,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT)
for line in iter(p.stdout.readline, b''):
    result = COUNT_EXP.match(line)
    if result:
        print "count is equal to " + result.group(1)

...我称之为countTest.py,然后运行:

$ python countTest.py
count is equal to 199

... 这一切都按预期工作。因此,我倾向于同意@kichik 的观点,即您正在使用的外部命令可能正在写入stderr 而不是stdout

【讨论】:

    【解决方案2】:
    p = subprocess.Popen(['python','blah.py'],stdout=subprocess.PIPE)
    while True:
      line = proc.stdout.readline()
      if len(line) != 0:
        print "success"  #if this code works, expanding to your regex should also work
    

    【讨论】:

      【解决方案3】:

      可能会将其打印到stderr。尝试将那个重定向到PIPE 并从那里读取数据。您还可以将2>&1 附加到命令的末尾,以使shell 将stderr 重定向到stdout。您可能需要为此添加 shell=True

      【讨论】:

        猜你喜欢
        • 2010-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-03
        • 1970-01-01
        • 1970-01-01
        • 2013-02-19
        相关资源
        最近更新 更多