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

Chr*_*ris 4 python subprocess exec frame inspect

我想在执行时打印 python 脚本的每一行,以及在执行每一行时从控制台打印日志。

例如,对于这个脚本:

import time
print 'hello'
time.sleep(3)
print 'goodbye'
Run Code Online (Sandbox Code Playgroud)

我希望它在控制台中生成以下内容:

line 1: import time
line 2: print 'hello'
hello
line 3: time.sleep(3)
line 4: print 'goodbye'
goodbye
Run Code Online (Sandbox Code Playgroud)

请参阅下面的我的尝试

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()
Run Code Online (Sandbox Code Playgroud)

虽然这会产生所需的结果,但它会在执行整个脚本后产生输出。这也是一个非常糟糕的黑客攻击,因为它很可能会根据 python_string_base 的内容而中断

use*_*107 5

您可以为此使用跟踪模块

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

python -m trace -t tmp.py 
Run Code Online (Sandbox Code Playgroud)

产生以下输出

 --- 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)
Run Code Online (Sandbox Code Playgroud)

  • 您好,也许有一种方法可以将跟踪限制为仅当前文件。因为当我设置此选项(-m trace -t &lt;my script&gt;)时,我看到了许多从内部 python 代码派生的打印输出。 (5认同)
  • **限制跟踪**的方法是使用 **`--ignore-module`** 和 **`--ignore-dir`** 参数,例如:`python3 -m trace --trace --ignore-module sys,time --ignore-dir /sys:/usr tmp.py` (2认同)