I tried to persist UTF-8 as the default encoding in Python.
I tried:
>>> import sys
>>> sys.getdefaultencoding()
'ascii'
Run Code Online (Sandbox Code Playgroud)
And I also tried:
>>> import sys
>>> reload(sys)
<module 'sys' (built-in)>
>>> sys.setdefaultencoding('UTF8')
>>> sys.getdefaultencoding()
'UTF8'
>>>
Run Code Online (Sandbox Code Playgroud)
But after closing the session and opening a new session, the following was the result:
>>> import sys
>>> sys.getdefaultencoding()
'ascii'
Run Code Online (Sandbox Code Playgroud)
How can I persist my changes? (I know that it's not always a good idea to change to UTF-8. It's in a Docker container of Python).
I know it's possible. I saw someone who has UTF-8 as his default encoding (always).
首先,这几乎肯定是一个坏主意,因为如果您在尚未完成此配置的另一台机器上运行代码,代码将会神秘地中断。
(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")
Run Code Online (Sandbox Code Playgroud)
(2) 设置环境变量[PYTHONSTARTUP][1]
指向该文件。
PYTHONSTARTUP
(3) 当Python解释器加载时,首先执行指向的文件内的代码:
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'
>>>
Run Code Online (Sandbox Code Playgroud)
请查看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 !
Run Code Online (Sandbox Code Playgroud)
完整源代码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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
16822 次 |
最近记录: |