我正在尝试用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()
我遇到了麻烦,因为如果我尝试编写文本,现有文本就会被覆盖。任何人都可以提出一些方法来克服这个问题。我不想为此目的创建另一个文件并通过修改将文本从原始文件复制到新文件
如果不重写所有下游内容,就无法向文件添加内容。
您可以使用以下逻辑:
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)