【问题标题】:Persist UTF-8 as Default Encoding坚持 UTF-8 作为默认编码
【发布时间】:2016-08-06 00:41:50
【问题描述】:

我尝试将 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 作为他的默认编码(总是)。

【问题讨论】:

    标签: python utf-8 utf


    【解决方案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指向的文件里面的代码会先被执行:

    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'
    >>>
    

    【讨论】:

      【解决方案2】:

      请查看site.py 库 - 这是sys.setdefaultencoding 发生的地方。我认为,您可以修改或替换此模块,以使其在您的机器上永久存在。这是它的一些源代码,cmets 解释了一些东西:

      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
      

      【讨论】:

        【解决方案3】:

        你总是可以在你的 python 文件的顶部添加:

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

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

        【讨论】:

        • 您也可以使用相同的格式定义其他编码。它必须是文件的第一行或第二行。背后的详细信息:python.org/dev/peps/pep-0263
        • OP 正在使用终端(这就是他说关闭/打开会话的原因),而不是文件。
        • 谢谢,但我没有更改文件的权限。
        • 这个技巧永远不会改变任何东西。在处理之前解码对象。
        猜你喜欢
        • 2012-03-10
        • 2012-02-01
        • 2014-04-23
        • 2014-02-09
        • 2012-02-14
        • 1970-01-01
        • 1970-01-01
        • 2013-04-28
        • 2015-04-14
        相关资源
        最近更新 更多