-1

我有一个 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?”?

4

3 回答 3

1

I wrote the following C program:

#include "stdio.h"

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

... which I called countOutput.c and the following Python script, modified from yours:

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)

... which I called countTest.py, and then ran:

$ python countTest.py
count is equal to 199

... which all works as expected. I'd therefore tend to agree with @kichik in thinking that the external command that you're using may be writing to stderr rather than stdout.

于 2013-08-15T00:38:35.673 回答
1
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
于 2013-08-15T00:29:51.503 回答
0

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

于 2013-08-15T00:28:41.483 回答