有了这个代码:
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中,我发现换行字符正在输出为字节序列x0Dx0Ax00 ,这对于UTF-16来说当然是错误的。
testing鼠标指针在哪个屏幕上
如何在IDA Pro中获得.text段的统计信息?
填充Windows XP安全事件日志
更改Shell文本颜色(Windows)
subprocess.communicate()挂在Windows 8上,如果父进程创build一个孩子
是否有任何Windows本地docker的第三方私人registry?
docker-compose运行在windows中不起作用
如何find跳转列表窗口?
尝试这个:
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","rn")) def __getattr__(self,key): return getattr(self.output,key) sys.stdout = CRLFWrapper(codecs.getwriter('utf-16')(sys.stdout)) print "test1" print "test2"
换行符翻译发生在标准输出文件内部。 你正在写“test1 n”到sys.stdout(一个StreamWriter)。 StreamWriter将其转换为“t x00e x00s x00t x001 x00 n x00”,并将其发送到实际文件,即原始sys.stderr。
该文件不知道你已经将数据转换为UTF-16; 所有它知道的是,输出流中的任何 n值都需要转换为 x0D x0A,这会导致您看到的输出。
到目前为止,我已经找到了两个解决方案,但是没有一个使用 Windows风格的行结束符输出UTF-16。
首先,将Python print语句重定向到UTF-16编码的文件(输出Unix样式的行尾):
import sys import codecs sys.stdout = codecs.open("outputfile.txt","w",encoding="utf16") print "test1" print "test2"
其次,使用UTF-16编码重定向到stdout ,没有行结束的转换损坏(输出Unix样式的行结束)(感谢这个ActiveState配方 ):
import sys import codecs sys.stdout = codecs.getwriter('utf-16')(sys.stdout) if sys.platform == "win32": import os,os.O_BINARY) print "test1" print "test2"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。