Skip to content

Instantly share code, notes, and snippets.

@Longhanks
Created January 15, 2018 10:28
Show Gist options
  • Save Longhanks/c7979bddc04e3fa4958a8daa0d2842a3 to your computer and use it in GitHub Desktop.
Save Longhanks/c7979bddc04e3fa4958a8daa0d2842a3 to your computer and use it in GitHub Desktop.
Ekans eval with captured stdout
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:
try:
codeC = compile(code, '<string>', 'exec')
eval(codeC)
except:
print("Something wrong with the code")
print("out:", s.getvalue())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment