Richard
Richard

Reputation: 135

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.

Upvotes: 0

Views: 223

Answers (1)

jh314
jh314

Reputation: 27802

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

Upvotes: 1

Related Questions