Last active
May 29, 2022 06:00
-
-
Save elazarcoh/d3587ea55bf4a1484cb6c96f3a059bbe to your computer and use it in GitHub Desktop.
A Tee context manager to redirect `print` calls to a file, as a quick logging method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
class Tee(object): | |
def __init__(self, name, mode, autoflush=False): | |
self.file = open(name, mode) | |
self.stdout = sys.stdout | |
sys.stdout = self | |
self.autoflush = autoflush | |
def write(self, data): | |
self.file.write(data) | |
self.stdout.write(data) | |
if self.autoflush: | |
self.flush() | |
def flush(self): | |
self.file.flush() | |
self.stdout.flush() | |
def close(self): | |
self.file.close() | |
sys.stdout = self.stdout | |
def __enter__(self): | |
return self | |
def __exit__(self, _type, _value, _traceback): | |
self.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment