python 2.7 / exec / 有什么问题?
我的代码在 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'
I have this code which runs fine in Python 2.5 but not in 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"
""")
And I get:
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'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
io.StringIO
在 Python 2.7 中很令人困惑,因为它是从 3.x 字节/字符串世界向后移植的。此代码得到与您的错误相同的错误:原因:
如果您仅使用 Python 2.x,则完全跳过 io 模块,并坚持使用 StringIO。如果您确实想使用 io,请将导入更改为:
io.StringIO
is confusing in Python 2.7 because it's backported from the 3.x bytes/string world. This code gets the same error as yours:causes:
If you are only using Python 2.x, then skip the
io
module altogether, and stick with StringIO. If you really want to useio
, change your import to:这是个坏消息
io.StringIO 想要使用 unicode。您可能认为可以通过在要打印的字符串前面放置一个
u
来修复它,如下所示,但是
print
确实会损坏此问题,因为它会导致 2 次写入字符串IO。第一个是u"hello world"
,这很好,但后面跟着"\n"
所以你需要写这样的东西
It's bad news
io.StringIO wants to work with unicode. You might think you can fix it by putting a
u
in front of the string you want to print like thishowever
print
is really broken for this as it causes 2 writes to the StringIO. The first one isu"hello world"
which is fine, but then it follows with"\n"
so instead you need to write something like this