简体   繁体   中英

UnicodeEncodeError in IPython but not standard REPL

I'm reading in a file that contains Unicode characters using Python 3.6.3 . In the standard Python REPL, I'm able to read the file with no problems by specifying UTF-8 encoding:

>>> with open("emoji.csv", encoding='utf-8') as f:
...     lines = f.readlines()
>>> lines
['this line has an emoji \U0001f644\n']

No problems there. However, when I try the same in IPython 6.1.0, I get the following UnicodeEncodeError :

In [1]: with open('emoji.csv', encoding='utf-8') as f:
...:     lines = f.readlines()
...:

In [2]: lines
Out[2]: ---------------------------------------------------------------------------
UnicodeEncodeError                        Traceback (most recent call last)
<ipython-input-2-3fb162a4fe05> in <module>()
----> 1 lines

/opt/anaconda/lib/python3.6/site-packages/IPython/core/displayhook.py in __call__(self, result)
    259             self.fill_exec_result(result)
    260             if format_dict:
--> 261                 self.write_format_data(format_dict, md_dict)
    262                 self.log_output(format_dict)
    263             self.finish_displayhook()

/opt/anaconda/lib/python3.6/site-packages/IPython/core/displayhook.py in write_format_data(self, format_dict, md_dict)
    188                 result_repr = '\n' + result_repr
    189 
--> 190         print(result_repr)
    191 
    192     def update_user_ns(self, result):

UnicodeEncodeError: 'ascii' codec can't encode character '\U0001f644' in position 24: ordinal not in range(128)

Similarly, if I try to simply encode and decode the Unicode character by itself, I get the same error:

In [1]: '\U0001f644'.encode('utf-8').decode('utf-8')
Out[1]: ---------------------------------------------------------------------------
...
...
UnicodeEncodeError: 'ascii' codec can't encode character '\U0001f644' in position 1: ordinal not in range(128)

What is causing this, and how do I read this file in IPython?

Edit : It seems this is a function of IPython using an ASCII encoding by default:

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'

However, I don't see anything in the IPython documentation on how to change this. Is this possible?

This is due to my system using a POSIX locale. Setting $PYTHONIOENCODING=UTF-8 resolved the issue by overriding the ASCII-based encoding IPython was using by default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM