Python,迭代 subprocess.Popen() 的 stdout/stderr

7

有许多类似的帖子,但我没有找到答案。

在Gnu / Linux上,使用Pythonsubprocess模块,我使用以下代码迭代处理由subprocess启动的命令的stdout/stderr:

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

查看如何刷新Python打印输出?

你需要使用-u选项运行Python子进程:

-u 强制使stdin,stdout和stderr完全不带缓冲区。在需要的系统上,也将stdin,stdout和stderr置于二进制模式中。请注意,xreadlines(),readlines()和文件对象迭代器(“for line in sys.stdin”)中存在内部缓冲区,该缓冲区不受此选项的影响。为了解决这个问题,您需要在“while 1:”循环中使用“sys.stdin.readline()”。

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

import sys
sys.stdout.flush()

谢谢!我太专注于Shell类了,以至于忘记在Python子进程脚本中刷新输出。再次感谢。 - user744629

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接