Tee
1import sys 2import datetime 3 4class Tee: 5 def __init__(self, filename, mode='a'): # Use 'a' for append mode 6 self.file = open(filename, mode) 7 self.stdout = sys.stdout 8 sys.stdout = self 9 10 def write(self, message): 11 timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') 12 message_with_timestamp = f"{timestamp} - {message}" 13 self.stdout.write("\n") 14 self.stdout.write(message_with_timestamp) 15 self.file.write(message_with_timestamp) 16 self.file.flush() 17 18 def flush(self): 19 self.stdout.flush() 20 self.file.flush() 21 22 def close(self): 23 sys.stdout = self.stdout 24 self.file.close()
class
Tee:
5class Tee: 6 def __init__(self, filename, mode='a'): # Use 'a' for append mode 7 self.file = open(filename, mode) 8 self.stdout = sys.stdout 9 sys.stdout = self 10 11 def write(self, message): 12 timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') 13 message_with_timestamp = f"{timestamp} - {message}" 14 self.stdout.write("\n") 15 self.stdout.write(message_with_timestamp) 16 self.file.write(message_with_timestamp) 17 self.file.flush() 18 19 def flush(self): 20 self.stdout.flush() 21 self.file.flush() 22 23 def close(self): 24 sys.stdout = self.stdout 25 self.file.close()