I am trying to write a script in Python which will read any python script searching for function definitions and add a print statement inside the function for debugging purpose.
e.g.
def function_for_test:
print "this line should be added for debugging purpose"
more code here....
more code here....
so far I have this code
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()
I have run in to trouble because if I try to write text, the existing text is getting over written. Could anyone please suggest some way to overcome this. I don't want to create another file for this purpose and copy text from original to new file with modifications