0

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.

3
  • what is the issue, your code runs fine once you put \tprint j Commented Aug 20, 2014 at 16:28
  • Where are the full error messages that you get? Also, I don't understand whether the problem is NotePad++ or whether you get a program error. BTW: you do not need to define old_stdout. The original value is already stored at sys.__stdout__.
    – Bakuriu
    Commented Aug 20, 2014 at 16:35
  • The issue is that the script is being loaded into IronPython in c#. Everything I have compiles it's just returning the output of the execution of code to a textbox in c#. So I was looking for a way to return the output of exec.
    – Richard
    Commented Aug 20, 2014 at 16:44

1 Answer 1

1

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
2
  • I think I do as it isn't Python running the code, it's IronPython embedded into c#. The way I have it returning the print statement I need it to to the correct text box is using a return statement in python.
    – Richard
    Commented Aug 20, 2014 at 16:42
  • Have a look here: blogs.msdn.com/b/charlie/archive/2009/10/25/…
    – jh314
    Commented Aug 20, 2014 at 17:53

Not the answer you're looking for? Browse other questions tagged or ask your own question.