简体   繁体   English

从subprocess.Popen异步读取stdout

[英]Asynchronously read stdout from subprocess.Popen

I am running a sub-program using subprocess.popen. 我正在使用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. 当我从命令窗口(cmd.exe)启动我的Python程序时,程序会随着程序的发展在窗口中写入一些信息和日期。

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. 当我不在命令窗口中运行我的Python代码时,它会为这个子程序的输出打开一个新的命令窗口,我想避免这种情况。 When I used the following code, it doesn't show the cmd window, but it also doesn't print the status: 当我使用以下代码时,它不会显示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? 如何在程序输出中显示子程序的输出?

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缓冲区(在不写入终端窗口时通常以不同方式缓冲),因此当子程序打印时,您可能无法立即看到每一行(这取决于各种OS细节和子程序的细节)。

Also notice how I've removed the shell=True and replaced the string argument with a list, which is generally recommended. 还要注意我是如何删除shell = True并用列表替换字符串参数,这通常是推荐的。

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. 尚未尝试过。

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/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM