Skip to content

Instantly share code, notes, and snippets.

@elazarcoh
Last active May 29, 2022 06:00
Show Gist options
  • Save elazarcoh/d3587ea55bf4a1484cb6c96f3a059bbe to your computer and use it in GitHub Desktop.
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
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