python 2.7/exec/有什么问题?

标签 python redirect exec stdio stringio

我的这段代码在 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")

原因:

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

关于python 2.7/exec/有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3423601/

相关文章:

python - 在 TensorFlow v1 中隐式启用 TensorFlow v2 行为

python - 从具有相同名称的脚本导入已安装的包引发 "AttributeError: module has no attribute"或 ImportError 或 NameError

javascript - document.referrer 引用超出我的函数范围的 URL

javascript - 如何使用 post 参数重定向到外部 URL?

c - 在 C 中进行系统调用时无法打开源文件

python - 禁止在 Python 中访问 exec 和 eval 中的文件系统

python - Python 的 Lettuce 示例出现控制台错误?

javascript - 提交使用 Google 脚本构建的 HTML 表单后如何重定向到 URL?

c - exec、execvp、execl、execv 之间的区别?

python - 如何使用 altair 在 hconcat 图表中显示两个不同的图例