Skip to content

Instantly share code, notes, and snippets.

@chm123
Created February 28, 2020 19:06
Show Gist options
  • Select an option

  • Save chm123/c435d80a3df2024ba673ad1032a3c2f0 to your computer and use it in GitHub Desktop.

Select an option

Save chm123/c435d80a3df2024ba673ad1032a3c2f0 to your computer and use it in GitHub Desktop.
Python redirect stdout to console and file
"""https://stackoverflow.com/questions/14906764/how-to-redirect-stdout-to-both-file-and-console-with-scripting"""
import sys
import traceback
class Tee(object):
"""Context manager that copies stdout and any exceptions to a log file.
Example usage:
print("Print")
with Tee('test.txt'):
print("Print+Write")
raise Exception("Test")
print("Print")
"""
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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment