V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
zhuweiping
V2EX  ›  问与答

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

  •  
  •   zhuweiping · 2016-08-05 23:39:37 +08:00 · 4296 次点击
    这是一个创建于 2821 天前的主题,其中的信息可能已经有所发展或是发生改变。
    写了一个 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.py 和 sitecustomize.py 文件的作用,还是没有弄明白为什么没能成功生效。求问前辈和朋友们有没有遇见过同样的问题,请教一下出现这样的问题的原因和解决途径。谢谢啦!
    5 条回复    2016-08-06 08:53:31 +08:00
    pheyer
        1
    pheyer  
       2016-08-05 23:51:04 +08:00
    今天晚上也是一直在搞这个问题,不过我的不是 py 文件的问题,而是在读文件时遇到这问题,头都大了,还没解决,明天再看
    zhuweiping
        2
    zhuweiping  
    OP
       2016-08-05 23:53:29 +08:00
    @pheyer 嗯嗯,我也搞了一晚上了,有进展一起分享一下。
    billlee
        3
    billlee  
       2016-08-06 00:18:37 +08:00
    laoyur
        4
    laoyur  
       2016-08-06 08:17:40 +08:00 via iPhone
    老老实实加 coding=utf-8 吧,你能乱折腾自己的 python 环境,别人不见得会
    ide 中改一下 py 模版,每次新建 py 文件都自带加这行
    Sylv
        5
    Sylv  
       2016-08-06 08:53:31 +08:00 via iPhone
    别作死了,老老实实在文件头加编码声明,这跟 Python 的默认编码没有关系。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2851 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 06:52 · PVG 14:52 · LAX 23:52 · JFK 02:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.