python 2.7 / exec / what is wrong?

感情迁移 提交于 2019-11-30 15:08: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:

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:

from io import BytesIO as StringIO

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 this

print "%s" % CaptureExec("""
import random
print u"hello world"
""")

however print is really broken for this as it causes 2 writes to the StringIO. The first one is u"hello world" which is fine, but then it follows with "\n"

so instead you need to write something like this

print "%s" % CaptureExec("""
import random
sys.stdout.write(u"hello world\n")
""")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!