[英]How can I capture the stdout output of a child process?
I'm trying to write a program in Python and I'm told to run an .exe file. 我正在尝试用Python编写程序,并且我被告知要运行.exe文件。 When this .exe file is run it spits out a lot of data and I need a certain line printed out to the screen.
当运行此.exe文件时,它会吐出大量数据,我需要在屏幕上打印一行。 I'm pretty sure I need to use
subprocess.popen
or something similar but I'm new to subprocess and have no clue. 我很确定我需要使用
subprocess.popen
或类似的东西,但我是subprocess的新手并且没有任何线索。 Anyone have an easy way for me to get this done? 任何人都有一个简单的方法来完成这项工作?
@Paolo's solution is perfect if you are interested in printing output after the process has finished executing. 如果您对过程执行完毕后打印输出感兴趣,@ Paolo的解决方案是完美的。 In case you want to poll output while the process is running you have to do it this way:
如果你想在进程运行时轮询输出,你必须这样做:
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()
Something like this: 像这样的东西:
import subprocess
process = subprocess.Popen(["yourcommand"], stdout=subprocess.PIPE)
result = process.communicate()[0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.