【问题标题】:How print every line of a python script as its being executed (including the console)?如何在执行时打印 python 脚本的每一行(包括控制台)?
【发布时间】: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


    【解决方案1】:

    您可以为此使用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)
    

    【讨论】:

    • 嗨,也许有一种方法可以将跟踪限制为仅当前文件。因为当我设置这个选项(-m trace -t )时,我看到了许多从内部 python 代码派生的打印输出。
    猜你喜欢
    • 2020-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-22
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2011-03-10
    相关资源
    最近更新 更多