如何使用Python流对象?
我有一个函数,它接受一个打开的文件对象 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如 io 的文档所述:
即,如果您使用向后移植的 Python 3 IO 库,则必须使用 unicode。但是,原始的 StringIO 类(考虑字节(Python 2 字符串)文本并接受它们)仍然存在于 Python 2.7 中,只是不在向后移植的 io 中。相反,它有自己的模块,也称为 StringIO。
As the documentation of
io
states: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 backportedio
. Instead, it has its own module, also calledStringIO
.