如何使用Python流对象?

发布于 2024-11-11 18:21:56 字数 728 浏览 4 评论 0原文

我有一个函数,它接受一个打开的文件对象 file 并向其中写入数据,如下所示:

def Write(self, file):
    file.write("Data")

现在我想测试该函数,我认为使用某种流来做到这一点会很巧妙没有将数据写入文件。除了 StringIO 类。然而,在Python2.7中,此类在write函数中需要一个unicode字符串。 (file.write(u"Data")) 因此我无法使用 StringIO 类测试我的 Write 函数。
在我的解决方法中,我创建了一个小虚拟类

class MyStream(object):
    S = property(lambda self: self._S)

    def __init__(self):
        self._S = ""

    def write(self, s):
        self._S += s

,现在可以使用它成功测试我的 Write 函数。

我的问题:
是否有一个本机 python 类可以执行相同的操作?
提前感谢您的任何建议
问候沃尔坦

I have a function that takes an opened file object file and writes data to it like so:

def Write(self, file):
    file.write("Data")

Now I would like to test that function and I thought it would be neat to do that with some kind of stream that is not writing data to a file. I could not find a Python2.7 class that does the job except the StringIO class. However, in Python2.7 this class expects a unicode string in the write function. (file.write(u"Data")) So I cannot test my Write function with the StringIO class.
In my workaround I created a little dummy class

class MyStream(object):
    S = property(lambda self: self._S)

    def __init__(self):
        self._S = ""

    def write(self, s):
        self._S += s

with which I can now successfully test my Write function.

My question:
Is there a native python class that does the same trick?
Thx in advance for any suggestions
Regards Woltan

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

幼儿园老大 2024-11-18 18:21:56

正如 io 的文档所述:

由于该模块主要是为 Python 3.x 设计的,因此您必须注意,本文档中所有使用的“bytes”均指的是 str 类型(其中 bytes 是别名),并且所有使用“ text”指的是unicode类型。此外,这两种类型在 io API 中不可互换。

即,如果您使用向后移植的 Python 3 IO 库,则必须使用 unicode。但是,原始的 StringIO 类(考虑字节(Python 2 字符串)文本并接受它们)仍然存在于 Python 2.7 中,只是不在向后移植的 io 中。相反,它有自己的模块,也称为 StringIO。

As the documentation of io states:

Since this module has been designed primarily for Python 3.x, you have to be aware that all uses of “bytes” in this document refer to the str type (of which bytes is an alias), and all uses of “text” refer to the unicode type. Furthermore, those two types are not interchangeable in the io APIs.

I.e. if you use the backported Python 3 IO library, you have to use unicode. However, the original StringIO class - which considers bytes (Python 2 strings) text and accepts them - still exists in Python 2.7, it's just not in the backported io. Instead, it has its own module, also called StringIO.

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