使用 StringIO 对象保存 uu.encode/uu.decode 数据

发布于 2024-09-07 08:40:08 字数 655 浏览 1 评论 0原文

我想做以下事情:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北方的巷 2024-09-14 08:40:08

content.setter 方法写入后,self._content 在其末尾留下“当前点”。您可能希望在该方法的末尾添加 self._content.seek(0) ,以便接下来读取该伪文件开头(从末尾开始阅读将返回“仅此而已”,这非常正确,因为它确实从末尾开始,这可能就是给您留下“空”印象的原因;-)。

self._content is left with the "current point" at its end after the content.setter method has written to it. You probably want to add self._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";-).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文