在使用python3.7编码时,引入pycurl模块和StringIO模块后,容易引起上述错误
导入StringIO模块的解决方案:
只有在python2中才能导入StringIO模块,直接 from
StringIO
import
StringIO
即可
但是python3,STringIO和cStringIO模块已经没了,要使用的话,需要导入io模块:
from io import StringIO
dot_data = StringIO()
也可以通过导入six模块来使用StringIO:
from six import StringIO
或者
from sklearn.externals.six import StringIO
再提供一种python2和python3都兼容的方法:
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
至此,不同python版本导入StringIO模块的问题就解决了。
但是pycurl在进行字符串编码时,还会受到python版本的影响,具体如下:
写入stringio
在python 2下,可以使用 StringIO
对象:
import pycurl
from StringIO import StringIO
c = pycurl.Curl()
c.setopt(c.URL,'http://pycurl.io')
buffer = StringIO()
c.setopt(c.WRITEDATA, buffer)
# Same result if using WRITEFUNCTION instead:
#c.setopt(c.WRITEFUNCTION, buffer.write)
c.perform()
# ok
在python 3下,当pycurl使用 bytes
参数,响应必须写入 BytesIO
对象:
import pycurl
from io import BytesIO
c = pycurl.Curl()
c.setopt(c.URL,'http://pycurl.io')
buffer = BytesIO()
c.setopt(c.WRITEDATA, buffer)
# Same result if using WRITEFUNCTION instead:
#c.setopt(c.WRITEFUNCTION, buffer.write)
c.perform()
# ok
尝试使用 StringIO
对象将产生错误::
import pycurl
from io import StringIO
c = pycurl.Curl()
c.setopt(c.URL,'http://pycurl.io')
buffer = StringIO()
c.setopt(c.WRITEDATA, buffer)
c.perform()
错误信息如下:
以下习惯用法可用于需要与Python2和Python3兼容的代码:
import pycurl
try:
# Python 3
from io import BytesIO
except ImportError:
# Python 2
from StringIO import StringIO as BytesIO
c = pycurl.Curl()
c.setopt(c.URL,'http://pycurl.io')
buffer = BytesIO()
c.setopt(c.WRITEDATA, buffer)
c.perform()
# ok
# Decode the response body:
string_body = buffer.getvalue().decode('utf-8')