本文介绍了如何打印正在执行的python脚本的每一行(包括控制台)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在执行脚本时打印每行python脚本,并在执行每一行时打印来自控制台的日志.

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.

例如,对于此脚本:

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

我的尝试见下文

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是什么而中断

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

推荐答案

您可以使用跟踪模块为此

如果您的4行代码位于tmp.py中,则将其称为

If your 4 lines of code are in tmp.py, calling it as

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)

这篇关于如何打印正在执行的python脚本的每一行(包括控制台)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 06:59