python 编码问题。将 utf-8 设置为默认编码方式后在终端运行带有中文输出的 test.py 脚本时始终没有生效。

2016-08-05 23:39:37 +08:00
 zhuweiping
写了一个 test.py (含中文字符 print "开始")
终端下: python test.py
结果: SyntaxError: Non-ASCII character '\xe4' in file test.py on line 1, but no encoding declared;
test.py 首行添加# coding=utf-8 后再次 python test.py 可以正常运行。(之后删掉了# coding=utf-8 )
想着修改一下 python 的默认编码方式, Google 了一下,很多前辈和朋友都说可以这样:
在 /etc/python2.7 目录下的 sitecustomize.py 文件中添加几行代码:
import sys
sys.setdefaultencoding("utf-8")
这样操作之后终端启动 python 解释器查看当前默认的编码方式:
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.getdefaultencoding()
'utf-8'
但是在终端执行: python test.py 的时候仍然出现最开始的错误。
尝试多次检查自己过程中可能出现的错误,也重启过 python 解释器 /注销登陆等。这种方式还是没能成功运行 test.py
最后在 /usr/lib/python2.7 目录下找到 site.py 文件,在其中将 encoding = 'ascii'改成 encoding = 'utf-8'也没用:
def setencoding():
"""Set the string encoding used by the Unicode implementation. The
default is 'ascii', but if you're willing to experiment, you can
change this."""
encoding = "utf-8" # Default value set by _PyUnicode_Init()
if 0:
# Enable to support locale aware default string encodings.
import locale
loc = locale.getdefaultlocale()
if loc[1]:
encoding = loc[1]
if 0:
# Enable to switch off string to Unicode coercion and implicit
# Unicode to string conversion.
encoding = "undefined"
if encoding != "ascii":
# On Non-Unicode builds this will raise an AttributeError...
sys.setdefaultencoding(encoding) # Needs Python Unicode build !
查看了一下 site.pysitecustomize.py 文件的作用,还是没有弄明白为什么没能成功生效。求问前辈和朋友们有没有遇见过同样的问题,请教一下出现这样的问题的原因和解决途径。谢谢啦!
4303 次点击
所在节点    问与答
5 条回复
pheyer
2016-08-05 23:51:04 +08:00
今天晚上也是一直在搞这个问题,不过我的不是 py 文件的问题,而是在读文件时遇到这问题,头都大了,还没解决,明天再看
zhuweiping
2016-08-05 23:53:29 +08:00
@pheyer 嗯嗯,我也搞了一晚上了,有进展一起分享一下。
billlee
2016-08-06 00:18:37 +08:00
laoyur
2016-08-06 08:17:40 +08:00
老老实实加 coding=utf-8 吧,你能乱折腾自己的 python 环境,别人不见得会
ide 中改一下 py 模版,每次新建 py 文件都自带加这行
Sylv
2016-08-06 08:53:31 +08:00
别作死了,老老实实在文件头加编码声明,这跟 Python 的默认编码没有关系。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/297489

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX