我该如何让Python 3(3.1)print("Some text")
输出到标准输出流,并以UTF-8编码输出,或者如何输出原始字节?
Test.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
没有意义(因为它始终只显示字节的表示而不是实际字节),并且根本无法输出字节,因为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]
),而且没有错误 :)
现在我正在寻找更好的解决方案,如果有的话...