错误编码非BMP字符

时间:2015-03-13 21:11:12

标签: python python-3.x python-idle

我在python 3.4中开发了一个小程序,但是当我尝试运行它时,最后说:
File "C:\Python34\lib\idlelib\PyShell.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

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

1 个答案:

答案 0 :(得分:2)

我认为你做了以下相同的事情。

>>> print('\U00011111')
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    print('\U00011111')
  File "C:\Programs\Python34\lib\idlelib\PyShell.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)&gt; 0xFFFF)。

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

在Windows上,控制台解释器给出了与“UCS-2”相同的错误。取而代之的是&#39; charmap&#39;。控制台解释器实际上更糟糕的是,即使对于某些BMP字符,它也会引发错误,具体取决于所使用的代码页。我不知道其他系统的情况如何。

修改 我忘了最好的选择,至少在Windows上。以下任一项都将在任何ascii终端上打印任何字符串。

>>> repr('\U00011111')
"'\U00011111'"
>>> ascii('\U00011111')
"'\\U00011111'"
回调时,

repr()不会反转双反斜杠,ascii()会。它们比空闲时需要更多的字符,但不会在&gt;&gt;&gt;处引发异常。提示。但是,由于我不明白的原因,print(repr(&#39; \ U00011111&#39;))失败,因此在程序中需要print(ascii(s))来打印s。