2016-04-14 75 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' 
>>>