Created
January 15, 2018 10:28
-
-
Save Longhanks/c7979bddc04e3fa4958a8daa0d2842a3 to your computer and use it in GitHub Desktop.
Ekans eval with captured stdout
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
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