【发布时间】:2017-04-28 18:31:51
【问题描述】:
我想在执行 Python 脚本时打印每一行,以及在执行每一行时打印来自控制台的日志。
例如,对于这个脚本:
import time
print 'hello'
time.sleep(3)
print 'goodbye'
我希望它在控制台中生成以下内容:
line 1: import time
line 2: print 'hello'
hello
line 3: time.sleep(3)
line 4: print 'goodbye'
goodbye
下面是我的尝试
import subprocess as subp
python_string = """
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":
file_dict = dict(enumerate("{}".split("|")))
line_number = frame.f_lineno-25
if line_number > 0:
print "line " + str(line_number)+ ": " + file_dict[line_number]
return monitor
def run():
{}
with SetTrace(monitor):
run()
"""
python_string_example = """
import time
print 'hello'
time.sleep(3)
print 'goodbye'
"""
python_string = python_string.format("|".join([i.strip() for i in python_string_example.split("\n")]),python_string_example)
proc = subp.Popen(['python', '-'], stdin=subp.PIPE,stdout=subp.PIPE, stderr=subp.STDOUT)
proc.stdin.write(python_string)
proc.stdin.close()
for line in proc.stdout:
print '{}'.format(line.strip())
proc.wait()
虽然这会产生所需的结果,但它会在整个脚本执行后产生输出。这也是一个非常糟糕的 hack,因为它很可能会根据 python_string_base 是什么而中断
【问题讨论】:
标签: python subprocess exec frame inspect