我在使用python 2.7讀取包含utf-8字符串的腳本時遇到了問題;在sitecustomize.py中將默認編碼設置爲utf-8似乎並不需要。python 2.7忽略解析腳本時在sitecustomize.py中設置的默認編碼
這裏是我的sitecustomize.py:
import sys
sys.setdefaultencoding("utf-8")
我可以確認的是,默認的編碼已在命令行中更改:
$ /usr/bin/python -c 'import sys; print(sys.getdefaultencoding())'
utf-8
然而,當我嘗試運行包含的腳本UTF-8字符串,如以下(含·在代碼點U + 00B7)test.py ...
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 &檢查PEP 263。改變默認編碼看起來像是在catkin引擎蓋下深入的唯一解決方案,或者消除了我係統上的所有非ascii路徑......並將其設置在sitecustomize.py中應該可以工作,但不能。
任何想法或見解非常感謝!
你爲什麼要在所有**處設置默認編碼**。你不應該那樣做。相反,修復你的Unicode處理代碼不要依賴默認編碼。 – 2014-09-12 18:40:21
此外,系統默認編碼從不用於源文件。這是一個硬編碼的默認值。 – 2014-09-12 18:40:51
我寧願使用編碼聲明,但腳本是由另一個程序(catkin構建系統的catkin_make)生成和運行的。在catkin_make運行之前,我無法手動向這些腳本添加編碼聲明。 – 2014-09-12 22:12:48