Skip to content

Instantly share code, notes, and snippets.

@kingspp
Last active September 12, 2021 00:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kingspp/924f1f36d65a2e0478674ef180352e8e to your computer and use it in GitHub Desktop.
Save kingspp/924f1f36d65a2e0478674ef180352e8e to your computer and use it in GitHub Desktop.
Tee functionality replicated for python - Simultaneously `print` to a file and `std out`
import traceback
import sys
# Context manager that copies stdout and any exceptions to a log file
class Tee(object):
def __init__(self, filename):
self.file = open(filename, 'w')
self.stdout = sys.stdout
def __enter__(self):
sys.stdout = self
def __exit__(self, exc_type, exc_value, tb):
sys.stdout = self.stdout
if exc_type is not None:
self.file.write(traceback.format_exc())
self.file.close()
def write(self, data):
self.file.write(data)
self.stdout.write(data)
def flush(self):
self.file.flush()
self.stdout.flush()
# Usage
with Tee('app.log'):
for i in range(10):
print(i)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment