Skip to content

Instantly share code, notes, and snippets.

@wwj718
Created January 10, 2019 12:39
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 wwj718/90cbcba431daae59adf36f399b35587e to your computer and use it in GitHub Desktop.
Save wwj718/90cbcba431daae59adf36f399b35587e to your computer and use it in GitHub Desktop.
import sys
from io import StringIO
import contextlib
@contextlib.contextmanager
def stdoutIO(stdout=None):
old = sys.stdout
if stdout is None:
stdout = StringIO()
sys.stdout = stdout
yield stdout
sys.stdout = old
code = """
i = [0,1,2]
for j in i :
print(j)
"""
with stdoutIO() as s:
exec(code)
print("out:", s.getvalue())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment