views:

51

answers:

3

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

A: 

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

Blam
i must do it in python only :/thanks for the answer
it is in python only :P
Blam
i've got a : codeproc = subprocess.Popen(command, stdout=subprocess.PIPE) File "C:\DEV\Python27\lib\subprocess.py", line 672, in __init__ errread, errwrite) File "C:\DEV\Python27\lib\subprocess.py", line 882, in _execute_child startupinfo)WindowsError: [Error 2] Le fichier spécifié est introuvable (file not found in french)
+2  A: 

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()
Frédéric Hamidi
+3  A: 

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()
THC4k
amazing thanks a lot
i've got a :File "D:\Documents\perso\dev\meta\Server.py", line 77, in decompress_html with self.stdoutIO() as s:AttributeError: __exit__
@user462794: It seems you ignored the `@contextlib.contextmanager` line
THC4k