实时读取标准输出过程 [英] Reading stdout process in real time

查看:90
本文介绍了实时读取标准输出过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑一下此片段:

Let's consider this snippet:

from subprocess import Popen, PIPE, CalledProcessError


def execute(cmd):
    with Popen(cmd, shell=True, stdout=PIPE, bufsize=1, universal_newlines=True) as p:
        for line in p.stdout:
            print(line, end='')

    if p.returncode != 0:
        raise CalledProcessError(p.returncode, p.args)

base_cmd = [
    "cmd", "/c", "d:\\virtual_envs\\py362_32\\Scripts\\activate",
    "&&"
]
cmd1 = " ".join(base_cmd + ['python -c "import sys; print(sys.version)"'])
cmd2 = " ".join(base_cmd + ["python -m http.server"])

如果我运行execute(cmd1),则将打印输出而不会出现任何问题.

If I run execute(cmd1) the output will be printed without any problems.

但是,如果我运行execute(cmd2),则什么也不会打印,这是为什么,以及如何解决它,以便可以实时查看http.server的输出.

However, If I run execute(cmd2) instead nothing will be printed, why is that and how can I fix it so I could see the http.server's output in real time.

此外,for line in p.stdout在内部如何评估?直到达到stdout eof还是某种无穷循环?

Also, how for line in p.stdout is been evaluated internally? is it some sort of endless loop till reaches stdout eof or something?

此主题已经在SO中解决了几次,但是我还没有找到Windows解决方案.上面的代码段实际上是来自 answer 的代码,并尝试从virtualenv(python3.6.2-32bits在win7上)

This topic has already been addressed few times here in SO but I haven't found yet a windows solution. The above snippet is in fact code from this answer and trying to run http.server from a virtualenv (python3.6.2-32bits on win7)

推荐答案

如果要连续读取正在运行的子进程,则必须使那个进程的输出无缓冲.您的子进程是一个Python程序,可以通过将-u传递给解释器来完成:

If you want to read continuously from a running subprocess, you have to make that process' output unbuffered. Your subprocess being a Python program, this can be done by passing -u to the interpreter:

python -u -m http.server

python -u -m http.server

这是在Windows框上的外观.

This is how it looks on a Windows box.

这篇关于实时读取标准输出过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆