我想创建一个函数来执行python脚本,同时在执行时实时存储控制台输出。
例如,我使用子进程模块来运行example.py,但我只在整个脚本运行后才收到控制台输出,而不是在运行时获得控制台输出。换句话说,根据下面的脚本,我希望立即接收控制台输出"hello world“,然后等待60秒,然后接收控制台输出”告别world“。
example.py
import time
print "hello world!"
time.sleep(60)
print "goodbye world"下面是在example.py中运行该脚本并在之后存储控制台的脚本
import subprocess
script = open('example.py',"r+").read()
process = subprocess.Popen(['python', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
process.stdin.write(script)
stored_console_output, stored_console_output_error = process.communicate()
print stored_console_output在执行完整个脚本后,这将以字符串的形式返回以下内容
hello world!
goodbye world注意:我不能更改python脚本example.py。我只能更改调用它的函数。
除了获得实时控制台输出(如果可能)之外,我还希望获得导致该控制台输出的python行。例如,我希望实现以下目标
import time
print "hello world!"
hello world
time.sleep(60)
print "goodbye world"
goodbye world我还尝试使用sys模块,但它不存储控制台输出:
import sys
import inspect
class SetTrace(object):
def __init__(self, func):
self.func = func
def __enter__(self):
sys.settrace(self.func)
return self
def __exit__(self, ext_type, exc_value, traceback):
sys.settrace(None)
def monitor(frame, event, arg):
if event == "line":
print event
return monitor
with SetTrace(monitor):
exec(open('example.py',"r+").read())这将返回以下内容,并实时执行该操作。
line
line
line
hello world!
line
line
goodbye world
line发布于 2017-08-07 03:23:35
This post在很大程度上回答了您的问题,尽管one comment提供了解决特定问题的关键:在调用example.py时需要-u标志,以防止sleep()上的STDOUT缓冲。
这个解决方案很大程度上借鉴了前面提到的答案:
from subprocess import Popen, PIPE
def execute(cmd):
popen = Popen(cmd, stdout=PIPE, universal_newlines=True)
for stdout_line in iter(popen.stdout.readline, ""):
yield stdout_line
popen.stdout.close()
for statement in execute(['python', '-u', 'example.py']):
print(statement, end="")输出:
Hello
# pauses for the number of sleep seconds
Goodbyehttps://stackoverflow.com/questions/45527115
复制相似问题