python 2.7 / exec /有什么问题?
16lz
2021-01-22
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
更多相关文章
- 用python将二进制整数或字符串写入文件
- 在混合的Bash-Python代码片段中,变量的双引号和单引号
- Python笔记(九):字符串操作
- python 产生随机数,随机字符串
- 八大经典排序算法基本思想及代码实现(插入排序,希尔排序,选择排序,
- 贝叶斯学习 -- matlab、python代码分析(3)
- UNIX-LINUX编程实践教程->第八章->实例代码注解->写一个简单的sh
- Linux下objdump查看C程序编译后的汇编代码
- linux shell脚本编程笔记(四): 获取字符串长度的七种方法