我有一段代码,它在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' Traceback (most recent call last): File "D:\3.py", line 13, in CaptureExec exec(stmt, globals(), globals()) File "", line 3, in TypeError: 期望传入字符串类型的参数,但实际接收到的是 'str'
captureExec
或capture_exec
。此外,在try...except
块中应该特别捕获ImportError
。 - Katriel