The code below creates a "tee" object that tees stdout to a file as well as the terminal.
If do del t as below when I'm done tee-ing, the object doesn't get deleted and the __del__() member doesn't get called (so the tee-ing continues):
t = tee("foo.txt")
print("bar")
del t
But if I call __del__() directly, things work fine:
t = tee("foo.txt")
print("bar")
t.__del__()
Why doesn't the del work? What's the right way to do this?
class tee():
def __init__(self, filepath):
self.old_stdout = sys.stdout
self.old_stderr = sys.stderr
self.name = filepath
sys.stdout = self
sys.stderr = self
def write(self, text):
self.old_stdout.write(text)
with open(self.name, 'a', encoding="utf-8") as f:
f.write(text)
def flush(self):
pass
def __del__(self):
sys.stdout = self.old_stdout
sys.stdout = self.old_stderr