问题描述
在Python 3.6.1中,我尝试将tempfile.SpooledTemporaryFile包装在io.TextIOWrapper中:
In Python 3.6.1, I've tried wrapping a tempfile.SpooledTemporaryFile in an io.TextIOWrapper:
with tempfile.SpooledTemporaryFile() as tfh:
do_some_download(tfh)
tfh.seek(0)
wrapper = io.TextIOWrapper(tfh, encoding='utf-8')
yield from do_some_text_formatting(wrapper)
wrapper = io.TextIOWrapper(tfh, encoding='utf-8')
行给我一个错误:
AttributeError: 'SpooledTemporaryFile' object has no attribute 'readable'
如果我创建像这样的简单类,则可以绕过该错误(对于writable
和seekable
,我也会收到类似的错误):
If I create a simple class like this, I can bypass the error (I get similar errors for writable
and seekable
):
class MySpooledTempfile(tempfile.SpooledTemporaryFile):
@property
def readable(self):
return self._file.readable
@property
def writable(self):
return self._file.writable
@property
def seekable(self):
return self._file.seekable
是否有充分的理由说明tempfile.SpooledTemporaryFile不具有这些属性?
Is there a good reason why tempfile.SpooledTemporaryFile doesn't already have these attributes?
推荐答案
SpooledTemporaryFile
实际上在后台使用了两种不同的_file
实现-最初是io
缓冲区(StringIO
或BytesIO
),直到它翻滚并通过tempfile.TemporaryFile()
创建一个文件状对象"(例如,当超出max_size
时).
SpooledTemporaryFile
actually uses 2 different _file
implementations under the hood - initially an io
Buffer (StringIO
or BytesIO
), until it rolls over and creates a "file-like object" via tempfile.TemporaryFile()
(for example, when max_size
is exceeded).
io.TextIOWrapper
需要一个BufferedIOBase
基类/接口,该基类/接口由io.StringIO
和io.BytesIO
提供,但不一定由TemporaryFile()
返回的对象提供(尽管在我对OSX的测试中,TemporaryFile()
返回了具有所需接口的_io.BufferedRandom
对象,我的理论是这可能取决于平台).
io.TextIOWrapper
requires a BufferedIOBase
base class/interface, which is provided by io.StringIO
and io.BytesIO
, but not necessarily by the object returned by TemporaryFile()
(though in my testing on OSX, TemporaryFile()
returned an _io.BufferedRandom
object, which had the desired interface, my theory is this may depend on platform).
因此,我希望您的MySpooledTempfile
包装器在翻转后在某些平台上可能会失败.
So, I would expect your MySpooledTempfile
wrapper to possibly fail on some platforms after rollover.
这篇关于为什么tempfile.SpooledTemporaryFile不实现可读,可写,可搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!