Skip to content

Instantly share code, notes, and snippets.

@yunwilliamyu
Created January 4, 2017 19:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yunwilliamyu/8e76b391aa366cbdb77c231111ba2f52 to your computer and use it in GitHub Desktop.
Save yunwilliamyu/8e76b391aa366cbdb77c231111ba2f52 to your computer and use it in GitHub Desktop.
Redirect Python stderr/stdout for a block
import sys
import contextlib
@contextlib.contextmanager
def output_wrapper():
save_stdout = sys.stdout
save_stderr = sys.stderr
sys.stdout = open('stdout.log', 'a')
sys.stderr = open('stderr.log', 'a')
yield
sys.stdout = save_stdout
sys.stderr = save_stderr
with output_wrapper():
printf("Hello log!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment