Python設定編碼和PYTHONPATH
Python中的編碼是個惱人的問題,第一個是檔案編碼,在第一行設定了#-*- coding: utf-8 -*-就可以解決。
第二個是環境編碼,就是你有個中文unicode的encode或decode操作,它給你報錯。
我們最不喜歡看見這段出錯資訊了:
UnicodeDecodeError: `ascii` codec can`t decode byte 0xe6 in position 0: ordinal not in range(128)
加入這段程式碼在專案入口檔案開頭,可以解決這個問題。
import sys try: reload(sys) sys.setdefaultencoding("utf-8") except AttributeError: pass #沒起作用
或者將這段程式碼放在專案根目錄下的sitecustomize.py檔案中。
問題是python2.5之後的版本,有時不在專案開頭自動載入這個檔案。糾結啊,自己定義的方式自己有時不支援。
只好在入口檔案加一段,確保執行sitecustomize.py
# -*- coding: utf-8 -*- #解決Python2.5之後有時無法載入sitecustomize.py的問題 import sys import os sys.path = [os.getcwd()] + sys.path import sitecustomize reload(sitecustomize)
另外關於python的搜尋路徑PYTHONPATH,可以用以下方式增加一個路徑到其中,比如專案根目錄下的library
# -*- coding: utf-8 -*- import os.path import sys import site try: reload(sys) sys.setdefaultencoding("utf-8") except AttributeError: pass base_dir = os.path.dirname(os.path.abspath(__file__)) prev_sys_path = list(sys.path) # site.addsitedir adds this directory to sys.path then scans for .pth files # and adds them to the path too. site.addsitedir(os.path.join(base_dir, `library`)) # addsitedir adds its directories at the end, but we want our local stuff # to take precedence over system-installed packages. # See http://code.google.com/p/modwsgi/issues/detail?id=112 new_sys_path = [] for item in list(sys.path): if item not in prev_sys_path: new_sys_path.append(item) sys.path.remove(item) sys.path[:0] = new_sys_path
相關文章
- Python 設定系統預設編碼Python
- JPA設定MySQL編碼MySql
- 編碼設定應注意
- Tomcat 設定編碼Tomcat
- java編譯、編碼、語言設定Java編譯
- MyEclipse設定文字編碼Eclipse
- MySQL字元編碼設定方法MySql字元
- Ubuntu 下設定中文編碼Ubuntu
- spring字元編碼設定Spring字元
- MyEclipse設定編碼方式Eclipse
- Python編碼和UnicodePythonUnicode
- JSP中的編碼設定JS
- 小型機設定WebSphere的預設編碼Web
- 我的 VIM 中文設定,支援 CJK 多種檔案編碼和 locale 設定(轉)
- Windows下CMD和Tomcat設定編碼為UTF-8WindowsTomcat
- python處理抓取中文編碼和判斷編碼Python
- eclipse設定jsp字元編碼EclipseJS字元
- Eclipse中設定編碼的方式Eclipse
- python教程3.3:字元和編碼Python字元
- Docker映象製作實戰:設定時區和系統編碼Docker
- Python檔案讀寫詳解及設定檔案的字元編碼Python字元
- php匯入時設定不同的編碼PHP
- Windows CMD永久設定UTF-8編碼Windows
- 【程式設計素質】Java編碼約定程式設計Java
- 設定Tomcat的UTF-8編碼Tomcat
- MySQL設定utf8mb4編碼MySql
- Vim中輸入法與編碼設定
- python基礎之字串和編碼Python字串
- Python urlencode 編碼和url拼接Python
- SAP常見Number range編碼範圍配置和增量跳位設定
- 網頁字元編碼、語言程式碼設定與SEO網頁字元
- 設定myeclipse的預設編碼為utf-8Eclipse
- 人人都能學會的python程式設計教程3:字串和編碼Python程式設計字串
- Centos-Mysql建立資料庫-編碼設定CentOSMySql資料庫
- 設定編譯比特幣原始碼-linux編譯比特幣原始碼Linux
- linux上mysql編碼 utf-8設定LinuxMySql
- Linux設定語言編碼(字符集)Linux
- Eclipse檔案編碼設定的問題Eclipse