tôi có mã này chạy tốt trong Python 2.5 nhưng không phải trong 2,7:python 2.7/exec/có gì sai?
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"
""")
Và tôi nhận được:
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'
ý kiến nhỏ: phong cách Pythonic là sử dụng TitleCase cho các lớp học mà thôi, nó phải được 'captureExec' hoặc' capture_exec'. Ngoài ra, bạn nên đặc biệt nắm bắt 'ImportError' trong khối' try ... except'. – katrielalex