【发布时间】:2011-03-26 07:32:53
【问题描述】:
我的这段代码在 Python 2.5 中运行良好,但在 2.7 中却没有:
import sys
import traceback
try:
from io import StringIO
except:
from StringIO import StringIO
def CaptureExec(stmt):
oldio = (sys.stdin, sys.stdout, sys.stderr)
sio = StringIO()
sys.stdout = sys.stderr = sio
try:
exec(stmt, globals(), globals())
out = sio.getvalue()
except Exception, e:
out = str(e) + "\n" + traceback.format_exc()
sys.stdin, sys.stdout, sys.stderr = oldio
return out
print "%s" % CaptureExec("""
import random
print "hello world"
""")
我得到:
需要字符串参数,得到'str' 回溯(最近一次通话最后): CaptureExec 中的文件“D:\3.py”,第 13 行 执行(stmt,全局(),全局()) 文件“”,第 3 行,在 TypeError:需要字符串参数,得到'str'【问题讨论】:
-
Minor cmets:Pythonic 风格是只对类使用 TitleCase,它应该是
captureExec或capture_exec。此外,您应该专门在try...except块中捕获ImportError。
标签: python redirect exec stdio stringio