Mac sublime 编译Python UnicodeEncodeError: 'ascii' codec can't encode characters in position 6-8: ordinal not in range(128)

  刚学Python,想打印个“hello 张林峰”,代码如下:

#!/usr/bin/env python3
# -*- coding: utf-8 -*- print('hello 张林峰')

  用sublime运行一下,竟然报错???

Traceback (most recent call last):
File "/Users/zhanglinfeng/Documents/Python/\u7ec3\u4e60/\u5b57\u7b26\u4e32\u7f16\u7801\u53ca\u8f93\u51fa\u683c\u5f0f.py", line 4, in <module>
print('hello \u5f20\u6797\u5cf0')
UnicodeEncodeError: 'ascii' codec can't encode characters in position 6-8: ordinal not in range(128)
[Finished in 0.1s with exit code 1]
[cmd: ['/Library/Frameworks/Python.framework/Versions/3.6/bin/python3', '-u', '/Users/zhanglinfeng/Documents/Python/练习/字符串编码及输出格式.py']]
[dir: /Users/zhanglinfeng/Documents/Python/练习]
[path: /usr/bin:/bin:/usr/sbin:/sbin]

  可我明明写了# -*- coding: utf-8 -*-的啊。去终端运行下这个py文件,特么终端竟然对的,可以打印hello 张林峰了。什么情况啊?

  网上搜了下,哟呵,报这个错的人还挺多啊。大概有以下几种答案:

  1.是因为默认的编码是ascii,要把需要自己将python的默认编码设置为utf8的编码格式

  查询系统默认编码可以在解释器中输入以下命令:

>>>import sys
>>>sys.getdefaultencoding()

  设置默认编码时使用:

>>>import sys
>>>reload(sys)
>>>sys.setdefaultencoding('utf8')

  这个方法在终端上运行Python时有用的,然而在sublime上还是不行。

  2.认为是print的的局限性

  需要在前面加上下面代码

import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8') #改变标准输出的默认编码

  我的就是第二个答案解决的。注意:这里有一个坑,我已经设置sublime运行3.6版本的Python,用SublimeREPL插件进行交互式运行时,竟然还是2.7。用2.7版本的Python时sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8')会报错。所以还要对SublimeREPL设置Python版本。这个卡了我好久,曾一度认为网上答案都是错的,只是网上答案不全而已,可能遇到的坑都没说。

上一篇:Android强制横屏+全屏的几种常用方法


下一篇:python爬虫中对含中文的url处理以 及 Python3—UnicodeEncodeError 'ascii' codec can't encode characters in position