简体   繁体   中英

Trying to print exec in python

After searching on Stack Overflow all the results i've found have been out-dated. I'm trying to print out the results of an exec command like the code below shows :

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()

Now i've found out that StringIO is no longer supported. I am using Python 2.7.6 on NotePad++. Everytime i've tried to import io it's told me the module isn't supported.

Edit: I forgot to mention the script is being loaded into IronPython in c# and i'm looking to return the value of exec code so I can have a textbox with the output.

Any help would be appreciated, thank you.

You don't need StringIO . Also, you need to indent the print statement in code . The following will work just fine:

code = """
i = [0,1,2]
for j in i :
    print j
""" 
exec(code)

will output:

0
1
2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM