问题描述
我试图将UTF-8保留为Python的默认编码.
I tried to persist UTF-8 as the default encoding in Python.
我尝试过:
>>> import sys
>>> sys.getdefaultencoding()
'ascii'
我也尝试过:
>>> import sys
>>> reload(sys)
<module 'sys' (built-in)>
>>> sys.setdefaultencoding('UTF8')
>>> sys.getdefaultencoding()
'UTF8'
>>>
但是在关闭会话并打开新会话之后,结果如下:
But after closing the session and opening a new session, the following was the result:
>>> import sys
>>> sys.getdefaultencoding()
'ascii'
如何保留更改?(我知道更改为UTF-8并不总是一个好主意.它在Python的Docker容器中).
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).
我知道这是可能的.我看到某个人(总是)使用UTF-8作为其默认编码.
I know it's possible. I saw someone who has UTF-8 as his default encoding (always).
推荐答案
请查看 site.py 库-这是sys.setdefaultencoding
发生的地方.我认为,您可以修改或替换此模块,以使其在您的计算机上永久存在.这是其中的一些源代码,注释解释了一些内容:
Please take a look into site.py library - it is the place where sys.setdefaultencoding
happens. You could, I think, modify or substitute this module in order to make it permanent on your machine. Here is some of it's source code, comments explains something:
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/文件/2.7/Lib/site.py .
如果您想知道的话,这是他们删除sys.setdefaultencoding
函数的地方:
This is the place where they delete the sys.setdefaultencoding
function, if you were wondering:
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
这篇关于坚持使用UTF-8作为默认编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!