简体   繁体   English

尝试在python中打印exec

[英]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 : 我正在尝试打印exec命令的结果,如下面的代码所示:

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. 现在,我发现不再支持StringIO。 I am using Python 2.7.6 on NotePad++. 我在NotePad ++上使用Python 2.7.6 Everytime i've tried to import io it's told me the module isn't supported. 每当我尝试导入io时,都会告诉我不支持该模块。

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. 编辑:我忘了提到脚本正在c#加载到IronPython中,并且我正在寻找返回exec代码的值,因此我可以使用输出文本框。

Any help would be appreciated, thank you. 任何帮助,将不胜感激,谢谢。

You don't need StringIO . 您不需要StringIO Also, you need to indent the print statement in code . 另外,您需要在code缩进print语句。 The following will work just fine: 以下将正常工作:

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

will output: 将输出:

0
1
2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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