将UTF-8保留为默认编码

2024-05-19 12:26:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将UTF-8作为Python中的默认编码持久化。

我试过:

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

我也试过:

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

但在结束会议并开始新的会议之后,结果是:

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

如何坚持我的更改?(我知道换成UTF-8并不总是个好主意。它在Python的Docker容器中)。

我知道这是可能的。我看到有人把UTF-8作为他的默认编码(总是)。


Tags: dockerinimport编码sysasciiutf8会议
3条回答

请查看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

您始终可以在python文件的顶部添加:

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

它将在*nix系统中更改该文件的编码为utf-8。

首先,这几乎肯定是一个坏主意,因为如果您在没有完成此配置的另一台计算机上运行代码,代码将神秘地中断。

(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所指向的代码:

bgporter@Ornette ~/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'
>>>

相关问题 更多 >