Python - capture Popen stdout AND display on console?

后端 未结 5 1268
猫巷女王i
猫巷女王i 2020-12-17 02:51

I want to capture stdout from a long-ish running process started via subprocess.Popen(...) so I\'m using stdout=PIPE as an arg.

However, be

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-17 03:50

    Inspired by pty.openpty() suggestion somewhere above, tested on python2.6, linux. Publishing since it took a while to make this working properly, w/o buffering...

    def call_and_peek_output(cmd, shell=False):
        import pty, subprocess
        master, slave = pty.openpty()
        p = subprocess.Popen(cmd, shell=shell, stdin=None, stdout=slave, close_fds=True)
        os.close(slave)
        line = ""
        while True:
            try:
                ch = os.read(master, 1)
            except OSError:
                # We get this exception when the spawn process closes all references to the
                # pty descriptor which we passed him to use for stdout
                # (typically when it and its childs exit)
                break
            line += ch
            sys.stdout.write(ch)
            if ch == '\n':
                yield line
                line = ""
        if line:
            yield line
    
        ret = p.wait()
        if ret:
            raise subprocess.CalledProcessError(ret, cmd)
    
    for l in call_and_peek_output("ls /", shell=True):
        pass
    

提交回复
热议问题