Python UTF-16 输出和 Windows 行结尾的错误? [英] Bug with Python UTF-16 output and Windows line endings?

查看:33
本文介绍了Python UTF-16 输出和 Windows 行结尾的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用此代码:

test.py

import sys
import codecs

sys.stdout = codecs.getwriter('utf-16')(sys.stdout)

print "test1"
print "test2"

然后我运行它:

test.py > test.txt

在 Windows 2000 上的 Python 2.6 中,我发现换行符被输出为字节序列 \x0D\x0A\x00 这当然是错误的对于 UTF-16.

In Python 2.6 on Windows 2000, I'm finding that the newline characters are being output as the byte sequence \x0D\x0A\x00 which of course is wrong for UTF-16.

我是否遗漏了什么,或者这是一个错误?

Am I missing something, or is this a bug?

推荐答案

试试这个:

import sys
import codecs

if sys.platform == "win32":
    import os, msvcrt
    msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

class CRLFWrapper(object):
    def __init__(self, output):
        self.output = output

    def write(self, s):
        self.output.write(s.replace("\n", "\r\n"))

    def __getattr__(self, key):
        return getattr(self.output, key)

sys.stdout = CRLFWrapper(codecs.getwriter('utf-16')(sys.stdout))
print "test1"
print "test2"

这篇关于Python UTF-16 输出和 Windows 行结尾的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆