对非 BMP 字符进行编码时出错



我在python 3.4中开发了一个小程序,但是当我尝试运行它时,最后说:
File "C:Python34libidlelibPyShell.py", line 1352, in write return self.shell.write(s, self.tags) UnicodeEncodeError: 'UCS-2' codec can't encode characters in position 39559-39559: Non-BMP character not supported in Tk

我已经尝试了所有方法,但一无所获。请帮忙!

我想你做了以下等效的事情。

>>> print('U00011111')
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    print('U00011111')
  File "C:ProgramsPython34libidlelibPyShell.py", line 1347, in write
    return self.shell.write(s, self.tags)
UnicodeEncodeError: 'UCS-2' codec can't encode character 'U00011111' in position 0: Non-BMP character not supported in Tk

问题如前所述:Idle 使用 tkinter 接口来 tcl/tk,并且 tk 无法显示非 BMP 补充字符(ord(char)> 0xFFFF)。

只要使用 utf-8(或 -16 或 -32)进行编码,将包含非 BMP 字符的字符串保存到文件中就可以正常工作。

在Windows上,控制台解释器给出相同的错误,"UCS-2"替换为"charmap"。 控制台解释器实际上更糟糕,因为它即使对于某些 BMP 字符也会引发错误,具体取决于所使用的代码页。我不知道其他系统的情况如何。

编辑我忘记了最好的选择,至少在Windows上是这样。以下任一操作将打印任何 ascii 终端上的任何字符串。

>>> repr('U00011111')
"'U00011111'"
>>> ascii('U00011111')
"'\U00011111'"

repr() 在回显时不会双反斜杠,ascii() 会。 这些转义的字符数超过了 Idle 所需的字符数,但不会在>>>提示符下引发异常。 但是,由于我不明白的原因,print(repr('\U00011111')) 失败了,所以程序中需要 print(ascii(s)) 来打印 s。

最新更新