【问题标题】:How can I capture the output of a child process spawned by a piped process?如何捕获由管道进程生成的子进程的输出?
【发布时间】:2018-11-03 23:00:42
【问题描述】:

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

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

我正在使用subprocess.Popen

编辑:一位评论者要求提供代码示例,我认为这不会增加太多,但这是我的代码(PopenProcesssubrpocess.Popen 的智能包装类,但没有什么特别之处):

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()

【问题讨论】:

  • 能否提供代码示例?
  • @Serge ,我在问题中提供了我的代码

标签: python subprocess pipe stdout


【解决方案1】:

作为管道进程而不是

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

应该使用

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

然后就可以了。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-10
    • 2010-10-29
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多