我有這樣的代碼,其運行正常在Python 2.5,但不是在2.7:python 2.7/exec /出了什麼問題?
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"
""")
我也得到:
string argument expected, got 'str' Traceback (most recent call last): File "D:\3.py", line 13, in CaptureExec exec(stmt, globals(), globals()) File "", line 3, in TypeError: string argument expected, got 'str'
小意見:Python的風格是隻使用首字母大寫的類,它應該是'captureExec'或'capture_exec'。另外,你應該特別抓住'try ... except'塊中的'ImportError'。 – katrielalex 2010-08-06 12:39:20