我在Red Hat Enterprise Linux 7.5上使用的是Anaconda安装的Python 3.6.3和IPython 6.1.0。我有包含我正在尝试使用的Unicode字符的文本文件,但在尝试打印这些文件的内容时出现以下错误:
UnicodeEncodeError: 'ascii' codec can't encode character '\U0001f644' in position 1: ordinal not in range(128)
我相信这是由于IPython默认为ASCII编码:
In [1]: from IPython.utils.encoding import get_stream_enc; import sys
In [2]: get_stream_enc(sys.stdout)
Out[2]: 'ANSI_X3.4-1968'
我在IPython文档中找不到任何解释如何将其更改为UTF-8的内容。可能吗?
iPython从环境中获取其输出编码。要使用支持unicode的编码,请在调用iPython时更改用户的语言环境设置或设置PYTHONIOENCODING环境变量:
PYTHONIOENCODING=UTF-8 ipython