【问题标题】:python - capturing stderr of subprocesses with their shell stdout alivepython - 使用它们的shell标准输出捕获子进程的标准错误
【发布时间】:2011-07-21 01:54:42
【问题描述】:

以下是我正在尝试做的事情:

-python 进程捕获多个子进程的stderr来观察子进程 - 每个子进程在显示标准输出的单独窗口上运行。

当我使用 Popen(command,stderr = fp4tempfile),

(好)python进程可以捕获子进程的stderr (坏)子进程外壳停止显示标准输出。

当我使用 Popen(command)

(好)每个子进程外壳都显示标准输出(以及标准错误,这对我来说并不重要), (坏)python 进程无法捕获标准错误。

我想要两个“好”。我能为此做些什么?提前致谢。 (目前我在windows7中使用python3.2开发)

这是用python编写的父进程源代码:

import os,subprocess
import time
fpws = []
fprs = []

def run_command(command):
    <specifying a file to write -- skipped>
    fpw = open(ftempname,'w')
    fpr = open(ftempname,'r')
    #cmd_redirect = "%s 2>%s" % (command,ftempname)#didnt do anything
    #starting a sub-program:
    pp = subprocess.Popen(command,stderr = fpw) #++
    #pp = subprocess.Popen(command)             #@@
    fpws.append(fpw)
    fprs.append(fpr)    

def watch_program():
    while True: #running forever for simplfication
        for fpr in  fprs:
            outchunk = fpr.read()
            <do something for subprocesses stderr -- skipped>
            time.sleep(1.0)

if __name__ == '__main__':
    cmd1 = '(path to program1)'
    cmd2 = '(path to program2)'
    run_command(cmd1)  #kicking cmd1
    run_command(cmd2)  #kicking cmd2
    watch_program()          #hearing stderr msg from the other process

注意:在子进程端,根据需要调用fflush(stdout)和fflush(stderr)。

【问题讨论】:

    标签: python subprocess stdout stderr


    【解决方案1】:

    还没有测试过,但是你能做吗

    import sys
    
    pp = subprocess.Popen(command, stderr = fpw, stdout = sys.stdout)
    

    【讨论】:

    • 编辑:没有注意到子进程在不同的窗口中。不知道为什么更改标准错误会对输出到标准输出的内容产生任何影响。您确定输出消失的原因是它实际上是标准错误吗?
    【解决方案2】:

    I82非常感谢您的回答和评论。

    是的,您对 stderr 的评论是绝对正确的。我在windows7中开发。在linux(ubuntu10)中,简单地解决了以下问题:

    cmd_line4sub = 命令 + '2>' + ftempname pp = subprocess.Popen(['/usr/bin/xterm','-e',cmd_line4sub],stderr = fpw)

    它会打开新的 shell,打印子进程标准输出。父进程捕获子进程stderr。这是我的第一个目标。

    如果我能弄清楚如何在 Windows 中做,我会发布我的答案;)

    (我和提问者是同一个用户,但我不能让他们成为同一个帐户...)

    【讨论】:

      猜你喜欢
      • 2012-09-17
      • 1970-01-01
      • 2013-01-22
      • 2013-05-11
      • 1970-01-01
      • 2011-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多