从长时间运行的子进程读取输出

从长时间运行的子进程读取输出

本文介绍了Python - 从长时间运行的子进程读取输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 subprocess 模块 (Python 2.7),我正在运行一个命令并尝试在它运行时处理它的输出.

Using the subprocess module (Python 2.7), I'm running a command and attempting to process its output as it runs.

我有如下代码:

process = subprocess.Popen(
    ['udevadm', 'monitor', '--subsystem=usb', '--property'],
    stdout=subprocess.PIPE)
for line in iter(process.stdout.readline, ''):
    print(line)

但是,即使我在打印语句之后添加 sys.stdout.flush(),输出也只会在我 Ctrl+C 之后打印出来.

However, the output only gets printed after I Ctrl+C, even if I add sys.stdout.flush() after the print statement.

为什么会发生这种情况,我如何直播这个过程的输出?

Why is this happening, and how can I live stream the output from this process?

值得注意的是,这个 udevadm monitor 命令并不打算终止,所以我不能简单地等待进程终止并立即处理其输出.

Notably, this udevadm monitor command is not intended to terminate, so I can't simply wait for the process to terminate and process its output all at once.

我找到了子进程命令的实时输出,但接受的答案中的方法并没有解决我的问题.

I found live output from subprocess command but the approach in the accepted answer did not solve my problem.

推荐答案

你可以使用 解除缓冲 :

You could use unbuffer :

process = subprocess.Popen(
    ["unbuffer", 'udevadm', 'monitor', '--subsystem=usb', '--property'],
    stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in iter(process.stdout.readline, ''):
    print(line)

这篇关于Python - 从长时间运行的子进程读取输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 18:36