Use a decorator. A simplified example:
def my_decorator(func): def wrapped_func(*args,**kwargs): return func("I've been decorated!",*args,**kwargs) return wrapped_func print = my_decorator(print)
Test:
print("TESTING")
So, to print to a file at the same time, you can:
def super_print(filename): '''filename is the file where output will be written''' def wrap(func): '''func is the function you are "overriding", ie wrapping''' def wrapped_func(*args,**kwargs): '''*args and **kwargs are the arguments supplied to the overridden function'''
If you compare this with the above example, you will see that there is additional closure in this situation (i.e. return wrapped_func AND return wrap instead of return wrapped_func ). This second close allows us to send an additional argument ( filename ) to the wrapper / decorator function.
The syntax for this last line looks a little strange, but this is the right way. Calling super_print('output.txt') returns an object, which then receives the print function object as an additional argument. All this works through closure; explore them if you are not in speed.
Then:
print('test')
test will be written to console output and output.txt.
source share