从 subprocess.Popen 异步读取标准输出 [英] Asynchronously read stdout from subprocess.Popen

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

问题描述

我正在使用 subprocess.popen 运行子程序.当我从命令窗口 (cmd.exe) 启动我的 Python 程序时,程序会随着程序的发展在窗口中写入一些信息和日期.

I am running a sub-program using subprocess.popen. When I start my Python program from the command window (cmd.exe), the program writes some info and dates in the window as the program evolves.

当我在命令窗口中运行我的 Python 代码 not 时,它会为此子程序的输出打开一个新的命令窗口,我想避免这种情况.当我使用以下代码时,它不显示 cmd 窗口,但也不打印状态:

When I run my Python code not in a command window, it opens a new command window for this sub-program's output, and I want to avoid that. When I used the following code, it doesn't show the cmd window, but it also doesn't print the status:

p = subprocess.Popen("c:/flow/flow.exe", shell=True, stdout=subprocess.PIPE)
print p.stdout.read()

如何在我的程序输出中显示子程序的输出?

How can I show the sub-program's output in my program's output as it occurs?

推荐答案

使用这个:

cmd = subprocess.Popen(["c:/flow/flow.exe"], stdout=subprocess.PIPE)
for line in cmd.stdout:
    print line.rstrip("\n")
cmd.wait()  # you may already be handling this in your current code

请注意,您仍然需要等待子程序刷新其 stdout 缓冲区(通常在不写入终端窗口时缓冲不同),因此您可能不会在子程序打印时立即看到每一行它(这取决于各种操作系统细节和子程序的细节).

Note that you will still have to wait for the sub-program to flush its stdout buffer (which is commonly buffered differently when not writing to a terminal window), so you may not see each line instantaneously as the sub-program prints it (this depends on various OS details and details of the sub-program).

还要注意我是如何删除 shell=True 并将字符串参数替换为列表的,这通常是推荐的.

Also notice how I've removed the shell=True and replaced the string argument with a list, which is generally recommended.

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

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