如何打印python脚本的每一行(包括控制台)?

时间:2017-04-28 18:31:51

标签: python subprocess exec frame inspect

我希望在执行时打印每一行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()

虽然这会产生所需的结果,但它会在执行整个脚本后生成输出。它也是一个非常糟糕的黑客,因为它很可能会破坏,具体取决于python_string_base是什么

1 个答案:

答案 0 :(得分:0)

您可以将trace module用于此

如果你的4行代码在tmp.py中,则将其称为

python -m trace -t tmp.py 

生成以下输出

 --- modulename: tmp, funcname: <module>
tmp.py(1): import time
tmp.py(2): print 'hello'
hello
tmp.py(3): time.sleep(3)
tmp.py(4): print 'goodbye'
goodbye
 --- modulename: trace, funcname: _unsettrace
trace.py(80):         sys.settrace(None)