Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Redirect stdout to a file in python using with block
import sys
class stdout_to_file:
def __init__(self, f):
self.f = f
self.stdout = sys.stdout
def __enter__(self):
sys.stdout = self.f
def __exit__(self, exc_type, exc_value, traceback):
sys.stdout = self.stdout
with open('test.txt', 'w') as f:
with stdout_to_file(f):
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.