windows 从 subprocess.Popen 异步读取标准输出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1822237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 13:31:13  来源:igfitidea点击:

Asynchronously read stdout from subprocess.Popen

pythonwindowssubprocess

提问by Mesut

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.

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

When I run my Python code notin 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:

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

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?

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

回答by

Use this:

用这个:

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

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).

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

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

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

回答by Tino

Looking for a recipe to process Popen data asynchronously I stumbled upon http://code.activestate.com/recipes/576759-subprocess-with-async-io-pipes-class/

寻找异步处理 Popen 数据的方法我偶然发现了http://code.activestate.com/recipes/576759-subprocess-with-async-io-pipes-class/

This looks quite promising, however I got the impression that there might be some typos in it. Not tried it yet.

这看起来很有希望,但我的印象是其中可能有一些错别字。还没试过。

回答by fviktor

It is an old post, but a common problem with a hard to find solution. Try this: http://code.activestate.com/recipes/440554-module-to-allow-asynchronous-subprocess-use-on-win/

这是一个旧帖子,但是一个很难找到解决方案的常见问题。试试这个:http: //code.activestate.com/recipes/440554-module-to-allow-asynchronous-subprocess-use-on-win/