Skip to content

Instantly share code, notes, and snippets.

@Musinux
Last active March 4, 2019 22:29
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
import sys
from contextlib import contextmanager
from io import StringIO
@contextmanager
def captured_output():
new_out = StringIO()
old_out = sys.stdout
try:
sys.stdout = new_out
yield sys.stdout
finally:
sys.stdout = old_out
print("bonjour")
with captured_output() as out:
print("pas bonjour")
print("au revoir")
with captured_output() as out2:
print("pas bonjour 2")
output = out.getvalue()
print("my output", output)
output2 = out2.getvalue()
print("my output", output2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment