Categories
overloading python python-3.x

How to overload print function to expand its functionality?

I am wondering if the build-in function print could be overridden so that the following statement will write to the console and a file at the same time.

print("test0","test1","test2",sep='\n') 

Also, may I know if it is possible to modify the source code of the build-in print function?

You can create a class with a write method and inside of that method you can print both stdout as well as write to the file.

import sys
class A(object):
def __init__(self, f):
self.f = open(f, 'w')
def __enter__(self):
return self # return instance of A which is assign to `f`.
def write(self, text):
sys.stdout.write(text) # print to the shell
self.f.write(text) # write in the file
def __exit__(self, *args):
self.f.close()
return True
with A('foo.txt') as f:
print("test0","test1","test4",sep='\n', file=f) #`file = f` calls `write` method