I need to output all my print statements to both terminal and file. I've found a solution in this stackoverflow question So i use
class Tee(object):
def __init__(self, name):
self.file = open(name, "a")
self.stdout = sys.stdout
sys.stdout = self
def __del__(self):
sys.stdout = self.stdout
self.file.close()
def write(self, data):
self.file.write(data)
self.stdout.write(data)
sys.stdout = Tee("log.txt")
That's works great ,
My problem is when i want to stop writing to file and go back to normal operation that's print only to terminal
I tried to use del(sys.stdout) to invoke the del method with no luck.
i even tried to change the last line to:
multiple_print = Tee("log.txt")
sys.stdout = multiple_print
and than use del(multiple_print) and failed
No matter what i tried , further uses of print still written to terminal and file both.
Any ideas?
You need to save a reference to the original file-descriptor before reassignment:
oldstdout = sys.stdout
and afterwards reassign it to sys.stdout
!
The del
statement doesn't call __del__
directly, but rather decreases the reference counter of your object. the __del__
method is called if the reference counter reaches zero and your object is about to get destroyed. So you can't force the reassignment, because it's up to the garbage collector, to call your __del__
method.
You need to directly reassign the sys.stdout variable:
Try:
sys.stdout = sys.__stdout__
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With