Okay. So, my question might be a bit vague. Here is what I want to do:
I have 'inherited' a large number of python scripts and I am supposed to debug,document and improve them. There isn't a whole lot of documentation available. In almost all cases I know what the input data and output data needs to be.
My plan is to wrap the original functions around a decorator function and log the output in a text file, while not interrupting the normal program flow. I also don't want to mess with the original source code for the time being. So, here is my code for the decorator:
def printoutput(func):
"""Decorator function to write the values of a function to a log file
1. If the output is a tuple or a list then the output will get written as Output1: .. , Output2:.. etc.
2. If the output is anything else, it will get written once.
"""
import time
#Accesfunc passes arguments to a calls the actual function. It also logs data.
def accessfunc(*args,**kwargs):
#Call the function with any number of arguments and keyword arguments.
y = func(*args,**kwargs)
#Save the name of the function being called.
funcname = r"D:\{}_{}_output.txt".format(time.time(), func.__name__)
#Create a file for logging data, specific to a function.
with open(funcname,'w') as fileoutput:
#if the output returned by the function is a lsit or tuple then log those on separate lines.
if isinstance(y,(tuple,list)):
for idx,outputs in enumerate(y):
fileoutput.write("Output{}:".format(idx))
fileoutput.write(str(outputs)+"\n")
#if the output is a single entity like a string or a number then log it on a single line.
else:
fileoutput.write("Output:\n")
fileoutput.write(str(y))
return y
return accessfunc
My questions are:
Is there a better way to accomplish what I am trying to do ?
I am logging the name of the function, is there a way that I could also log the name of the variables being returned. For example if function A returns B, can I log it in such a way that both "A" and "B" get mentioned in my log file ?