Created
February 21, 2019 09:03
-
-
Save plusangel/544ab4ef63719a98332e0f3d4c96b3f5 to your computer and use it in GitHub Desktop.
Store standard output on a variable in Python
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
#from StringIO import StringIO # Python2 | |
from io import StringIO # Python3 | |
import sys | |
# Store the reference, in case you want to show things again in standard output | |
old_stdout = sys.stdout | |
# This variable will store everything that is sent to the standard output | |
result = StringIO() | |
sys.stdout = result | |
print("noooo") | |
# Here we can call anything we like, like external modules, and everything that they will send to standard output will be stored on "result" | |
# do_fancy_stuff() | |
sys.stdout = old_stdout | |
print(result.getvalue()) | |
old_stdout = sys.stdout | |
result = StringIO() | |
sys.stdout = result | |
print("yes") | |
sys.stdout = old_stdout | |
print(result.getvalue()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment