【发布时间】:2014-11-07 00:14:10
【问题描述】:
我在让 python 2.7 读取包含 utf-8 字符串的脚本时遇到问题;在 sitecustomize.py 中将默认编码设置为 utf-8 似乎不需要。
这是我的 sitecustomize.py:
import sys
sys.setdefaultencoding("utf-8")
我可以从命令行验证默认编码是否已更改:
$ /usr/bin/python -c 'import sys; print(sys.getdefaultencoding())'
utf-8
但是,当我尝试运行包含 utf-8 字符串的脚本时,如下面的 test.py 中(在代码点 U+00b7 处包含·)...
filename = 'utf-8·filename.txt'
print(filename)
…默认编码似乎被忽略了:
$ /usr/bin/python test.py
File "test.py", line 1
SyntaxError: Non-ASCII character '\xc2' in file test.py on line 1, but
no encoding declared; see http://www.python.org/peps/pep-0263.html for details
使用encoding declaration,如下面的test-coding.py...
# coding=utf-8
filename = 'utf-8·filename.txt'
print(filename)
…确实工作:
$ /usr/bin/python test-coding.py
utf-8·filename.txt
不幸的是,问题出在由另一个程序(catkin 构建系统的 catkin_make)生成和运行的脚本上。在 catkin_make 运行它们之前,我无法手动将编码声明添加到这些脚本中,从而给出 SyntaxError & check PEP 263。更改默认编码似乎是唯一没有深入了解 catkin 的解决方案,或者消除我系统上的所有非 ascii 路径……并且在 sitecustomize.py 中设置它应该可以工作,但不会。
非常感谢任何想法或见解!
【问题讨论】:
-
你为什么要设置默认编码根本。你不应该那样做。相反,请修复您的 Unicode 处理代码,使其不依赖默认编码。
-
此外,系统默认编码从不用于源文件。这是硬编码的默认值。
-
我宁愿使用编码声明,但脚本是由另一个程序(catkin 构建系统的 catkin_make)生成和运行的。在 catkin_make 运行它们之前,我无法手动将编码声明添加到这些脚本中。
标签: python python-2.7 encoding utf-8