Last active
September 12, 2021 00:29
-
-
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`
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 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