python 2.7/exec/怎么了? [英] python 2.7 / exec / what is wrong?

查看:217
本文介绍了python 2.7/exec/怎么了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码可以在Python 2.5中正常运行,但不能在2.7中运行:

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"
""")

我得到:


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字节/字符串世界反向移植的.此代码与您的错误相同:

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:

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,请将导入更改为:

If you are only using Python 2.x, then skip the io module altogether, and stick with StringIO. If you really want to use io, change your import to:

from io import BytesIO as StringIO

这篇关于python 2.7/exec/怎么了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆