python 如何捕获子进程的 stdout 输出?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/923079/
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
How can I capture the stdout output of a child process?
提问by Tyler
I'm trying to write a program in Python and I'm told to run an .exe file. When this .exe file is run it spits out a lot of data and I need a certain line printed out to the screen. I'm pretty sure I need to use subprocess.popen
or something similar but I'm new to subprocess and have no clue. Anyone have an easy way for me to get this done?
我正在尝试用 Python 编写一个程序,我被告知要运行一个 .exe 文件。当这个 .exe 文件运行时,它会吐出大量数据,我需要将某一行打印到屏幕上。我很确定我需要使用subprocess.popen
或类似的东西,但我是 subprocess 的新手并且不知道。任何人都有一个简单的方法来完成这项工作?
回答by Nadia Alramli
@Paolo's solution is perfect if you are interested in printing output after the process has finished executing. In case you want to poll output while the process is running you have to do it this way:
如果您有兴趣在流程完成后打印输出,@Paolo 的解决方案是完美的。如果您想在进程运行时轮询输出,您必须这样做:
process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
while True:
out = process.stdout.readline(1)
if out == '' and process.poll() != None:
break
if out.startswith('myline'):
sys.stdout.write(out)
sys.stdout.flush()
回答by Paolo Bergantino
Something like this:
像这样的东西:
import subprocess
process = subprocess.Popen(["yourcommand"], stdout=subprocess.PIPE)
result = process.communicate()[0]