如何捕获管道进程生成的子进程的输出?

How can I capture the output of a child process spawned by a piped process?

我想连续监视一个管道进程并在它进入时打印它的 stdoutstderr(我不想在它退出后立即获得全部输出)。问题是管道进程生成了另一个子进程,并且无法使用原始进程的管道访问该生成进程的 stdoutstderr

即我想以这种方式运行一个python程序,所以管道进程是python解释器,但是python解释器产生运行ning 在另一个子进程中的 python 程序,所以我无法获得它的输出(实际程序输出)。如果启动程序时出错,我可以得到它,因为它被打印到原始 python 解释器的 stderr。但是实际程序中的正常 stdout 对我来说丢失了。

我正在使用 subprocess.Popen .

编辑:一位评论者要求提供代码示例,我认为这不会增加太多,但这是我的代码(PopenProcess 是 [=19= 的智能包装器 class ] 但没有做任何特别的事情 ):

class BTask:
    def __init__(self, name, cmds, color = "NONE"):
        self.name = name
        self.cmds = cmds
        self.color = color
        self.proc = None

    def procreadline(self, sline):
        print(ANSI[self.color] + self.name + ANSI["ENDC"] + " > " + ANSI[self.color] + sline)

    def procreaderror(self, sline):
        print(ANSI[self.color] + self.name + ANSI["BRIGHTWHITE"] + " ! " + ANSI["BRIGHTRED"] + sline)

    def run(self):        
        print(ANSI["GREEN"])
        print("running task: {} {}".format(ANSI["BRIGHTGREEN"], self.name))
        pargs = []
        if len(self.cmds) > 1:
            pargs = self.cmds[1:]        
        print(ANSI[self.color])
        self.proc = PopenProcess(
            self.cmds[0],
            self.procreadline,
            read_error_callback = self.procreaderror,
            proc_args = pargs,
            ignore_cwd = True
            )

    def kill(self):
        print(ANSI["RED"])
        print("killing task: {} {}".format(ANSI["BRIGHTRED"], self.name))
        self.proc.kill()

    def is_alive():
        return self.proc.is_alive()

作为管道进程而不是

subprocess.Popen(['python', 'myprog.py'])

应该使用

subprocess.Popen(['python', '-u', 'myprog.py'])

然后就可以了。

问题出在缓冲输出上,-u 开关将其关闭(允许无缓冲输出)。