I have this code which runs fine in Python 2.5 but not in 2.7:

我有这个代码在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"
""")

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'

2 个解决方案

#1


14

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:

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'

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:

如果您只使用Python 2.x,则完全跳过io模块,并坚持使用StringIO。如果您确实想使用io,请将导入更改为:

from io import BytesIO as StringIO

更多相关文章

  1. 用python将二进制整数或字符串写入文件
  2. 在混合的Bash-Python代码片段中,变量的双引号和单引号
  3. Python笔记(九):字符串操作
  4. python 产生随机数,随机字符串
  5. 八大经典排序算法基本思想及代码实现(插入排序,希尔排序,选择排序,
  6. 贝叶斯学习 -- matlab、python代码分析(3)
  7. UNIX-LINUX编程实践教程->第八章->实例代码注解->写一个简单的sh
  8. Linux下objdump查看C程序编译后的汇编代码
  9. linux shell脚本编程笔记(四): 获取字符串长度的七种方法

随机推荐

  1. c语言fopen打开文件失败怎么办
  2. c语言中允许的基本数据类型包括哪些?
  3. 15道C语言开发面试题(原题分享)
  4. c语言程序格式是什么
  5. c语言有哪些合法关键字
  6. c++贪吃蛇代码是什么
  7. 经典C语言面试题(参考)
  8. 用c语言编写爱心的代码是什么
  9. c语言fun函数有什么作用
  10. C语言strcmp函数用法