向Python文件添加行以进行调试

2024-04-24 07:47:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用Python编写一个脚本,它将读取搜索函数定义的任何Python脚本,并在函数中添加一个print语句以进行调试。你知道吗

例如

def function_for_test:
    print "this line should be added for debugging purpose"
    more code here....
    more code here....

到目前为止我有这个密码

import os
import re
import sys

match_class = re.compile(r'^[ \t]*(def|class)[ \t]+([a-zA-Z_][a-zA-Z0-9_]*)[ \t]*[:\(]')


for root, dirs, files in  os.walk(sys.argv[1]):
        for fn in files:
                if fn.endswith(".py"):
                        with open(os.path.join(root, fn), "r+") as source:
                                        while True:
                                                line = source.readline()
                                                if line == "": break
                                                m = match_class.match(line.expandtabs())
                                                if m:
                                                        print m.groups()

我遇到了麻烦,因为如果我试着写文本,现有的文本就写过头了。有谁能提出一些克服这个问题的方法吗。我不想为此目的创建另一个文件,并将文本从原始文件复制到经过修改的新文件


Tags: 文件函数文本import脚本forifos
2条回答

如果不重写所有下游内容,就无法将内容添加到文件中。你知道吗

可以使用以下逻辑:

with open(filename, 'r+') as f:
    lines = f.readlines()
    modified_lines = instrument_code(lines)

    f.seek(0)  # Go back to file start
    f.writelines(modified_lines)

    # Remove trailing content in case your file is shorter than original
    f.truncate()  

其中instrument_code是修改源文件的代码。你知道吗

Settrace可以用来满足这个要求。请注意,会有一个性能开销,很可能有更好的方法。。但是,这可能是一种快速(从编码的角度)满足您需求的方法。你知道吗

例如

import sys

def trace_f(frame, event, arg):
    if event == "call":
        print 'Execute {f} '.format(f=frame.f_code)

现在定义一个简单的示例函数来跟踪

def multiply_by_two(x):
    print x*2

并激活跟踪

sys.settrace(trace_f)

multiply_by_two(12)

相关问题 更多 >