首页 文章

python,迭代subprocess.Popen()stdout / stderr

提问于
浏览
7

有很多类似的帖子,但我没有找到答案 .

在Gnu / Linux上,使用 Pythonsubprocess 模块,我使用以下代码迭代使用子进程启动的命令的stdout / sdterr:

class Shell:
    """ 
    run a command and iterate over the stdout/stderr lines
    """

    def __init__(self):

        pass

    def __call__(self,args,cwd='./'):

        p = subprocess.Popen(args,
                cwd=cwd, 
                stdout = subprocess.PIPE,
                stderr = subprocess.STDOUT,
                )

        while True:

            line = p.stdout.readline()
            self.code = p.poll()

            if line == '':
                if self.code != None:
                    break
                else:
                    continue

            yield line

#example of use
args = ["./foo"]
shell = Shell()
for line in shell(args):
     #do something with line
     print line,

这样工作正常......除非执行的命令是 python ,例如`args = ['python','foo.py'],在这种情况下输出不会刷新,而是仅在命令完成时打印 .

有解决方案吗?

1 回答

  • 2

    看看How to flush output of Python print? .

    您需要使用-u选项运行python子进程:

    -u强制stdin,stdout和stderr完全无缓冲 . 在重要的系统上,还将stdin,stdout和stderr置于二进制模式 . 请注意,xreadlines(),readlines()和file-object迭代器(“for sys.stdin中的行”)中存在内部缓冲,不受此选项的影响 . 要解决此问题,您需要在“while 1:”循环中使用“sys.stdin.readline()” .

    或者,如果您可以控制python子流程脚本,则可以使用sys.stdout.flush()在每次打印时刷新输出 .

    import sys
    sys.stdout.flush()
    

相关问题