问题
I'd like to print every line of python script as it's being executed, as well as the log from the console as every line is being executed.
For example, for this script:
import time
print 'hello'
time.sleep(3)
print 'goodbye'
I'd like it to generate the following in the console:
line 1: import time
line 2: print 'hello'
hello
line 3: time.sleep(3)
line 4: print 'goodbye'
goodbye
See below for my attempt
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()
Although, this produces the desired result, it produces the output after the entire script is executed. It also is a very bad hack since it will most likely break depending on what python_string_base is
回答1:
You can use the trace module for this
If your 4 lines of code are in tmp.py, calling it as
python -m trace -t tmp.py
Produces the following output
--- 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)
来源:https://stackoverflow.com/questions/43686761/how-print-every-line-of-a-python-script-as-its-being-executed-including-the-con