i've got a little problem 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 ? bref here how can i get in something :
0
1
2
regards and thanks Bussiere
i've got a little problem 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 ? bref here how can i get in something :
0
1
2
regards and thanks Bussiere
Something like:
codeproc = subprocess.Popen(code, stdout=subprocess.PIPE)
print(codeproc.stdout.read())
should execute the code in a different process and pipe the output back to your main program via codeproc.stdout. But I've not personally used it so if there's something I've done wrong feel free to point it out :P
You can redirect the standard output to a string for the duration of the exec call:
code = """
i = [0,1,2]
for j in i :
print j
"""
from cStringIO import StringIO
old_stdout = sys.stdout
redirected_output = sys.stdout = StringIO()
exec(code)
sys.stdout = old_stdout
print redirected_output.getvalue()
I had the same idea as Frédéric, but i wrote a context manager to handle replacing stdout:
import sys
import StringIO
import contextlib
@contextlib.contextmanager
def stdoutIO(stdout=None):
old = sys.stdout
if stdout is None:
stdout = StringIO.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()