2016-04-14 73 views
2

我試圖堅持utf8作爲python的默認編碼。 我想:堅持UTF-8作爲默認編碼

>>> import sys 
>>> sys.getdefaultencoding() 
'ascii' 

所以我做:

>>> import sys 
>>> reload(sys) 
<module 'sys' (built-in)> 
>>> sys.setdefaultencoding('UTF8') 
>>> sys.getdefaultencoding() 
'UTF8' 
>>> 

但會議結束時,打開一個新的會話後:

>>> import sys 
>>> sys.getdefaultencoding() 
'ascii' 

我如何能堅持我的變化? (我知道轉換爲utf8並不總是一個好主意,它在Python的碼頭集裝箱中)

我知道這是可能的,我看到有人將utf8作爲默認編碼(總是)。

回答

2

請看看到site.py庫 - 它就是sys.setdefaultencoding發生的地方。我認爲,您可以修改或替換此模塊,以使其在您的機器上永久保存。下面是它的一些源代碼,評論解釋了一句:

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 = "ascii" # 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 ! 

完整的源https://hg.python.org/cpython/file/2.7/Lib/site.py

這是他們刪除sys.setdefaultencoding功能,如果你想知道的地方:

def main(): 

    ... 

    # Remove sys.setdefaultencoding() so that users cannot change the 
    # encoding after initialization. The test for presence is needed when 
    # this module is run as a script, because this code is executed twice. 
    if hasattr(sys, "setdefaultencoding"): 
     del sys.setdefaultencoding 
1

您可以隨時添加你的Python文件的頂部:

# -*- coding: utf-8 -*- 

將在* nix系統更改編碼爲UTF-8該文件。

+0

您也可以定義使用相同的格式,其他編碼。它必須是文件的第一行或第二行。在這裏的詳細信息:https://www.python.org/dev/peps/pep-0263/ – saltycraig

+0

OP正在與一個終端(這就是爲什麼他說關閉/打開sesions),而不是與文件。 –

+0

謝謝,但我沒有權限更改文件。 – DenCowboy

1

首先,這幾乎肯定是一個糟糕的主意,因爲如果你在另一臺沒有完成配置的機器上運行它,代碼會神祕地破壞。

(1)像這樣創建一個新的文件(我叫setEncoding.py):

import sys 
# reload because Python removes setdefaultencoding() from the namespace 
# see http://stackoverflow.com/questions/2276200/changing-default-encoding-of-python 
reload(sys) 
sys.setdefaultencoding("utf-8") 

(2)設置環境變量[PYTHONSTARTUP][1]在這個文件指向。

(3)當Python解釋器加載,文件中的代碼PYTHONSTARTUP點,將首先執行:

[email protected] ~/temp:python 
Python 2.7.10 (default, Oct 23 2015, 19:19:21) 
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> sys.getdefaultencoding() 
'utf-8' 
>>>