Skip to content

Instantly share code, notes, and snippets.

@Musinux
Last active March 4, 2019 22:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Musinux/912626d2e3d5e9628b8f822551beadf6 to your computer and use it in GitHub Desktop.
Save Musinux/912626d2e3d5e9628b8f822551beadf6 to your computer and use it in GitHub Desktop.
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