我正在尝试用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()
我遇到了麻烦,因为如果我试着写文本,现有的文本就写过头了。有谁能提出一些克服这个问题的方法吗。我不想为此目的创建另一个文件,并将文本从原始文件复制到经过修改的新文件
如果不重写所有下游内容,就无法将内容添加到文件中。你知道吗
可以使用以下逻辑:
其中
instrument_code
是修改源文件的代码。你知道吗Settrace可以用来满足这个要求。请注意,会有一个性能开销,很可能有更好的方法。。但是,这可能是一种快速(从编码的角度)满足您需求的方法。你知道吗
例如
现在定义一个简单的示例函数来跟踪
并激活跟踪
相关问题 更多 >
编程相关推荐