如何使 python StreamWriter 需要 unicode 输入?
python 编解码器模块提供了 StreamWriter 类,用于透明地编码输出流。例如:
outstream = codecs.getwriter('utf8')(sys.__stdout__)
outstream.write(u'\u2713')
outstream.write(' A-OK!\n') # I want this to fail!
outstream.close()
然而,我对默认 StreamWriter 的问题是它会排除 str 对象和 unicode 对象。如果我的程序正在向该流写入 str,那么这是一个错误,我希望它失败!有没有一种方法可以实现这一点,而无需编写自己的 StreamWriter 来强制写入对象的类型?
另外,我不希望我的解决方案对 sys.stdout.encoding
、sys.stdout.isatty()
、locale.getpreferredencoding()< 敏感/code>、
sys.getfilesystemencoding()
、os.environ["PYTHONIOENCODING"]
或 python 试图变得聪明的任何其他方式。
The python codecs module provides StreamWriter classes for transparently encoding output streams. For instance:
outstream = codecs.getwriter('utf8')(sys.__stdout__)
outstream.write(u'\u2713')
outstream.write(' A-OK!\n') # I want this to fail!
outstream.close()
However the problem I have with the default StreamWriter is that it will except str objects as well as unicode objects. If my program is writing a str to this stream, it is a bug and I want it to fail! Is there a way to make this happen without writing my own StreamWriter that enforces the type of objects written?
Also, I don't want my solution to be sensitive to sys.stdout.encoding
, sys.stdout.isatty()
, locale.getpreferredencoding()
, sys.getfilesystemencoding()
, os.environ["PYTHONIOENCODING"]
or whatever other ways python has of trying to be clever.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果可能的话,请执行您在 Python 3 中尝试执行的操作,Python 3 在 unicode 和 bytes 之间有更强的区别。如果做不到这一点,您需要子类化
StreamWriter
,例如:If possible, do what you're trying to do in Python 3, which has a much stronger distinction between unicode and bytes. Failing that, you'll need to subclass
StreamWriter
, for example: