root@fb6e7c6fbe5c:/home/binss# python3 amazon_test.py Traceback (most recent call last): File "amazon_test.py", line 30, in print(s) UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-7: ordinal not in range(128)
Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character '\u8266' in position 0: ordinal not in range(128)
尝试了各种姿势,结果还是没能解决。
最后突发奇想,print不行,那我把其输出到文件捏?
1 2 3
>>> s = '\u8266' >>> withopen('xxx.txt', mode='w') as pubilc_file: ... pubilc_file.write(s)
依然报错
1 2 3
Traceback (most recent call last): File "", line 2, in UnicodeEncodeError: 'ascii' codec can't encode character '\u8266' in position 0: ordinal not in range(128)
那换成二进制输出呢?
1 2 3
>>> s = '\u8266'.encode('utf-8') >>> withopen('xxx.txt', mode='wb') as pubilc_file: ... pubilc_file.write(s)
竟然成功输出了正确的字符——“艦”!这,难道是因为终端的stdout不支持utf-8输出?
于是打印看看当前的stdout是啥
1 2 3 4 5 6 7 8
root@fb6e7c6fbe5c:/home/binss# python3 Python 3.5.1 (default, Dec 182015, 00:00:00) [GCC 4.8.4] on linux Type"help", "copyright", "credits"or"license"for more information. >>> import sys >>> sys.stdout <_io.TextIOWrapper name='' mode='w' encoding='ANSI_X3.4-1968'> >>>