如何制作 python 3 print() utf8

新手上路,请多包涵

如何将 python 3 (3.1) print("Some text") 成 UTF-8 标准输出,或者如何输出原始字节?

测试.py

 TestText = "Test - āĀēĒčČ..šŠūŪžŽ" # this is UTF-8
TestText2 = b"Test2 - \xc4\x81\xc4\x80\xc4\x93\xc4\x92\xc4\x8d\xc4\x8c..\xc5\xa1\xc5\xa0\xc5\xab\xc5\xaa\xc5\xbe\xc5\xbd" # just bytes
print(sys.getdefaultencoding())
print(sys.stdout.encoding)
print(TestText)
print(TestText.encode("utf8"))
print(TestText.encode("cp1252","replace"))
print(TestText2)

输出(在 CP1257 中,我将字符替换为字节值 [x00] ):

 utf-8
cp1257
Test - [xE2][xC2][xE7][C7][xE8][xC8]..[xF0][xD0][xFB][xDB][xFE][xDE]
b'Test - \xc4\x81\xc4\x80\xc4\x93\xc4\x92\xc4\x8d\xc4\x8c..\xc5\xa1\xc5\xa0\xc5\xab\xc5\xaa\xc5\xbe\xc5\xbd'
b'Test - ??????..\x9a\x8a??\x9e\x8e'
b'Test2 - \xc4\x81\xc4\x80\xc4\x93\xc4\x92\xc4\x8d\xc4\x8c..\xc5\xa1\xc5\xa0\xc5\xab\xc5\xaa\xc5\xbe\xc5\xbd'

print 太聪明了…… :D 使用编码文本是没有意义的 print (因为它总是只显示字节的表示而不是实际字节)并且不可能输出字节全部,因为无论如何都要打印并始终将其编码为 sys.stdout.encoding

例如: print(chr(255)) 抛出错误:

>  Traceback (most recent call last):
>   File "Test.py", line 1, in <module>
>     print(chr(255));
>   File "H:\Python31\lib\encodings\cp1257.py", line 19, in encode
>     return codecs.charmap_encode(input,self.errors,encoding_table)[0]
> UnicodeEncodeError: 'charmap' codec can't encode character '\xff' in position 0: character maps to <undefined>
>
> ```

顺便说一下 `print( TestText == TestText2.decode("utf8"))` 返回 `False` ,尽管打印输出是相同的。

* * *

Python 3 如何确定 `sys.stdout.encoding` 我该如何更改它?

我做了一个 `printRAW()` 函数,它工作正常(实际上它将输出编码为 UTF-8,所以它真的不是原始的......):

def printRAW(*Text): RAWOut = open(1, ‘w’, encoding=‘utf8’, closefd=False) print(*Text, file=RAWOut) RAWOut.flush() RAWOut.close()

printRAW(“Cool”, TestText)

”`

输出(现在以 UTF-8 格式打印):

 Cool Test - āĀēĒčČ..šŠūŪžŽ

printRAW(chr(252)) 也很好地打印 ü (在UTF-8中, [xC3][xBC] )并且没有错误:)

现在我正在寻找更好的解决方案,如果有的话……

原文由 davispuh 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

澄清:

 TestText = "Test - āĀēĒčČ..šŠūŪžŽ" # this not UTF-8...it is a Unicode string in Python 3.X.
TestText2 = TestText.encode('utf8') # this is a UTF-8-encoded byte string.

要将 UTF-8 发送到 stdout 而不管控制台的编码如何,请使用其接受字节的缓冲区接口:

 import sys
sys.stdout.buffer.write(TestText2)

原文由 Mark Tolonen 发布,翻译遵循 CC BY-SA 4.0 许可协议

这是我能从手册中得出的最好的结果,而且有点肮脏:

 utf8stdout = open(1, 'w', encoding='utf-8', closefd=False) # fd 1 is stdout
print(whatever, file=utf8stdout)

似乎文件对象应该有一种方法来更改它们的编码,但 AFAICT 没有。

如果您写入 utf8stdout,然后写入 sys.stdout 而没有先调用 utf8stdout.flush(),反之亦然,则可能会发生不好的事情。

原文由 zwol 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进