我的这段代码在 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"
""")
然后我得到:
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'
最佳答案
io.StringIO
在 Python 2.7 中令人困惑,因为它是从 3.x 字节/字符串世界向后移植的。此代码与您的错误相同:
from io import StringIO
sio = StringIO()
sio.write("Hello\n")
原因:
Traceback (most recent call last):
File "so2.py", line 3, in <module>
sio.write("Hello\n")
TypeError: string argument expected, got 'str'
如果您只使用 Python 2.x,则完全跳过 io
模块,并坚持使用 StringIO。如果您真的想使用 io
,请将导入更改为:
from io import BytesIO as StringIO
关于python 2.7/exec/有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3423601/