Last active
March 10, 2019 11:28
-
-
Save GreatBahram/4f8a1d0bba2dfd161b7484d04488852d to your computer and use it in GitHub Desktop.
Redirect stdout to what ever you want: context manager and decorator implementation
This file contains 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 sys | |
from contextlib import contextmanager | |
from functools import wraps | |
def redirect_stdout_to(out_new): | |
"""Redirect stdout to out_new with context manager.""" | |
out_old = sys.stdout | |
sys.stdout = out_new | |
yield | |
sys.stdout = out_old | |
def redirect_stdout_to(out_new): | |
"""Redirect stdout to out_new with decorator.""" | |
def decorator(func): | |
@wraps(func) | |
def wrapper(*args, **kwargs): | |
out_old = sys.stdout | |
sys.stdout = out_new | |
try: | |
return func(*args, **kwargs) | |
finally: | |
sys.stdout = out_old | |
return wrapper | |
return decorator | |
@contextmanager | |
def redirect_stdout_to(out_new): | |
""" | |
Redirect stdout to out_new. It can be used as both context manager and a decorator. | |
""" | |
stdout_old = sys.stdout | |
sys.stdout = out_new | |
try: | |
yield | |
except Exception as e: | |
exception_name = e.__class__.__name__ | |
print(e) | |
finally: | |
sys.stdout = stdout_old | |
# Usage | |
with redirect_stdout_to(sys.stderr): | |
print('Hello stderr') | |
@redirect_stdout_to(sys.stderr) | |
def whatnot(): | |
print('whatnot is the worsest name that you can choose') | |
whatnot() | |
class Person: | |
@redirect_stdout_to(sys.stderr) | |
def whanot(self): | |
print('Hello, world!') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment