我的代码在 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")
causes:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)