I want to get the output of an exec(...)
Here is my code:
code = """
i = [0,1,2]
for j in i :
print j
"""
result = exec(code)
How could I get the things that print outputed? How can I get something like:
0
1
2
Regards and thanks.
What does exec return in Python? Python exec() does not return a value; instead, it returns None. A string is parsed as Python statements, which are then executed and checked for any syntax errors. If there are no syntax errors, the parsed string is executed.
exec() in Python. exec() function is used for the dynamic execution of Python program which can either be a string or object code. If it is a string, the string is parsed as a suite of Python statements which is then executed unless a syntax error occurs and if it is an object code, it is simply executed.
Since Python 3.4 there is a solution is the stdlib: https://docs.python.org/3/library/contextlib.html#contextlib.redirect_stdout
from io import StringIO from contextlib import redirect_stdout f = StringIO() with redirect_stdout(f): help(pow) s = f.getvalue()
In older versions you can write a context manager to handle replacing 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: exec(code) print("out:", s.getvalue())
Here is Py3-friendly version of @Jochen's answer. I also added try-except
clause to recover in case of errors in the code
.
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: exec(code) except: print("Something wrong with the code") print("out:", s.getvalue())
You can redirect the standard output to a string for the duration of the exec call:
import sys
from cStringIO import StringIO
code = """
i = [0,1,2]
for j in i:
print(j)
"""
old_stdout = sys.stdout
redirected_output = sys.stdout = StringIO()
exec(code)
sys.stdout = old_stdout
print(redirected_output.getvalue())
import sys
from io import StringIO
code = """
i = [0,1,2]
for j in i:
print(j)
"""
old_stdout = sys.stdout
redirected_output = sys.stdout = StringIO()
exec(code)
sys.stdout = old_stdout
print(redirected_output.getvalue())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With