使用 StringIO 对象保存 uu.encode/uu.decode 数据
我想做以下事情:
import StringIO, uu
my_data = StringIO.StringIO() # this is a file-like object
uu.encode(in_file, my_data)
# do stuff with my data (send over network)
uu.decode(my_data, out_file) # here I finally write to disk
上面的代码有效。但是,如果我将上一步实现为对象中的属性:
@property
def content(self):
out = StringIO.StringIO()
uu.decode(self._content, out)
return out.getvalue()
@content.setter
def content(self, value):
self._content = StringIO.StringIO()
with open('value', 'rb') as stream:
uu.encode(stream, self._content)
但是当我这样做时,self._content
为空(准确地说,None
)。有什么想法吗?
I would like to do the following:
import StringIO, uu
my_data = StringIO.StringIO() # this is a file-like object
uu.encode(in_file, my_data)
# do stuff with my data (send over network)
uu.decode(my_data, out_file) # here I finally write to disk
The above code works. However, if I implement the previous step as a property in an object:
@property
def content(self):
out = StringIO.StringIO()
uu.decode(self._content, out)
return out.getvalue()
@content.setter
def content(self, value):
self._content = StringIO.StringIO()
with open('value', 'rb') as stream:
uu.encode(stream, self._content)
but when I do it like that, self._content
is empty (None
, to be precise). Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在
content.setter
方法写入后,self._content
在其末尾留下“当前点”。您可能希望在该方法的末尾添加self._content.seek(0)
,以便接下来读取该伪文件开头(从末尾开始阅读将返回“仅此而已”,这非常正确,因为它确实从末尾开始,这可能就是给您留下“空”印象的原因;-)。self._content
is left with the "current point" at its end after thecontent.setter
method has written to it. You probably want to addself._content.seek(0)
at the end of that method so you can next read that pseudo-file from the beginning (reading while starting from the end will return "nothing more", quite correctly since it does start at the end, and that's probably what's leaving you with the impression that it's "empty";-).