[英]Read console output of another program in Python
There are two programs - parent.py and myscript.py, shown below. 有两个程序 - parent.py和myscript.py,如下所示。 parent.py keeps printing messages in the console. parent.py在控制台中保持打印消息。 And myscript.py needs access to what parent.py prints. 并且myscript.py需要访问parent.py打印的内容。
parent.py: parent.py:
import time
while 1:
time.sleep(1)
print "test"
myscript.py: myscript.py:
import subprocess
p = None
p = subprocess.Popen(['python', 'parent.py'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
for line in p.stdout:
print line
I want myscript.py to catch the output of parent.py dynamically. 我希望myscript.py动态地捕获parent.py的输出。 As it can be seen that parent.py has an infinite loop - the script is never gonna stop, but whenever it outputs the word 'test', myscript.py should also output the same. 可以看出,parent.py有一个无限循环 - 脚本永远不会停止,但每当它输出单词'test'时,myscript.py也应输出相同的内容。 But myscript.py doesn't give out any output. 但myscript.py没有给出任何输出。
I tried replacing the code in parent.py with just 我尝试用parent替换parent.py中的代码
print "Hello"
Since the program finished executing, myscript.py also printed "Hello". 程序完成执行后,myscript.py也打印出“Hello”。 So I guess unless the execution of parent.py is complete, myscript.py doesn't read it. 所以我想除非parent.py的执行完成,否则myscript.py不会读取它。 Is that whats happening? 那是什么事吗?
I also tried replacing the loop in myscript.py with this snippet: 我也尝试用这个片段替换myscript.py中的循环:
for line in iter(p.stdout.readline, ''):
print line
Still, no output. 仍然没有输出。
My question is: How do I get myscript.py dynamically read all that is being printed by parent.py even when parent.py is never going to complete its execution. 我的问题是:即使parent.py永远不会完成执行,我如何让myscript.py动态读取parent.py正在打印的所有内容。
(I found similar questions, but they either didn't work or there were no answers at all in some of them.) (我发现了类似的问题,但是它们要么不起作用,要么根本没有答案。)
It is a block buffering issue : when stdout is redirected to a pipe parent.py
accumulates its output in an internal buffer (~4K-8K) ie, you won't see anything for around an hour until the buffer overflows. 这是一个块缓冲问题 :当stdout被重定向到管道parent.py
在内部缓冲区(~4K-8K)中累积其输出,即,在缓冲区溢出之前,您将看不到任何大约一个小时的内容。
To disable buffering, pass -u
command-line option: 要禁用缓冲,请传递-u
命令行选项:
#!/usr/bin/env python
import os
import sys
from subprocess import Popen, PIPE, STDOUT
script_path = os.path.join(get_script_dir(), 'parent.py')
p = Popen([sys.executable, '-u', script_path],
stdout=PIPE, stderr=STDOUT, bufsize=1)
with p.stdout:
for line in iter(p.stdout.readline, b''):
print line,
p.wait()
See: 看到:
Note: if you don't need to do anything with the output then just drop stdout=PIPE
, to see the output in the console: 注意:如果您不需要对输出执行任何操作,则只需删除stdout=PIPE
,即可在控制台中查看输出:
subprocess.check_call([sys.executable, script_path])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.