简体   繁体   English

使用io.StringIO模拟文件时出现Unicode问题

[英]Unicode problems when using io.StringIO to mock a file

I am using an io.StringIO object to mock a file in a unit-test for a class. 我正在使用io.StringIO对象来模拟一个类的单元测试中的文件。 The problem is that this class seems expect all strings to be unicode by default, but the builtin str does not return unicode strings: 问题是这个类似乎希望默认情况下所有字符串都是unicode,但是内置的str不会返回unicode字符串:

>>> buffer = io.StringIO()
>>> buffer.write(str((1, 2)))
TypeError: can't write str to text stream

But

>>> buffer.write(str((1, 2)) + u"")
6

works. 作品。 I assume this is because the concatenation with a unicode string makes the result unicode as well. 我假设这是因为与unicode字符串的串联也会使结果成为unicode。 Is there a more elegant solution to this problem? 这个问题有更优雅的解决方案吗?

The io package provides python3.x compatibility. io包提供了python3.x兼容性。 In python 3, strings are unicode by default. 在python 3中,默认情况下字符串是unicode。

Your code works fine with the standard StringIO package, 您的代码可以使用标准的StringIO包,

>>> from StringIO import StringIO
>>> StringIO().write(str((1,2)))
>>>

If you want to do it the python 3 way, use unicode() in stead of str(). 如果你想用python 3方式做,请使用unicode()代替str()。 You have to be explicit here. 你必须在这里明确。

>>> io.StringIO().write(unicode((1,2)))
6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM