我很好奇python源代码如何设置Py_FileSystemDefaultEncoding的值。我收到了一件奇怪的事情。
自从Pythondoc https://docs.python.org/2/library/sys.html#sys.getfilesystemencoding关于 sys.getfilesystemencoding() 说:
在 Unix 上,编码是用户根据 nl_langinfo(CODESET) 结果的偏好,如果 nl_langinfo(CODESET) 失败则为 None。
我使用Python 2.7.6
```
>>>import sys
>>>sys.getfilesystemencoding()
>>>'UTF-8'
>>>import locale
>>>locale.nl_langinfo(locale.CODESET)
>>>'ANSI_X3.4-1968'
```
问题是:为什么 getfilesystemencoding() 的值与 locale.nl_landinfo() 的值不同,因为文档说 getfilesystemencoding() 是从 locale.nl_landinfo() 派生的。
这是我的终端中的区域设置命令输出:
LANG=en_US.UTF-8
LANGUAGE=en_US:en
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC=zh_CN.UTF-8
LC_TIME=zh_CN.UTF-8
LC_COLLATE="en_US.UTF-8"
LC_MONETARY=zh_CN.UTF-8
LC_MESSAGES="en_US.UTF-8"
LC_PAPER=zh_CN.UTF-8
LC_NAME=zh_CN.UTF-8
LC_ADDRESS=zh_CN.UTF-8
LC_TELEPHONE=zh_CN.UTF-8
LC_MEASUREMENT=zh_CN.UTF-8
LC_IDENTIFICATION=zh_CN.UTF-8
LC_ALL=
概括:sys.getfilesystemencoding()
行为如记录的那样。混乱是由于之间的差异setlocale(LC_CTYPE, "")
(用户的首选项)和默认的 C 语言环境。
该脚本始终以默认的 C 语言环境开头:
>>> import locale
>>> locale.nl_langinfo(locale.CODESET)
'ANSI_X3.4-1968'
But getfilesystemencoding()
使用用户的区域设置:
>>> import sys
>>> sys.getfilesystemencoding()
'UTF-8'
>>> locale.setlocale(locale.LC_CTYPE, '')
'en_US.UTF-8'
>>> locale.nl_langinfo(locale.CODESET)
'UTF-8'
空字符串作为区域设置名称根据用户选择的适当环境变量来选择区域设置 http://www.gnu.org/software/libc/manual/html_node/Setting-the-Locale.html.
$ LC_CTYPE=C python -c 'import sys; print(sys.getfilesystemencoding())'
ANSI_X3.4-1968
$ LC_CTYPE=C.UTF-8 python -c 'import sys; print(sys.getfilesystemencoding())'
UTF-8
我在哪里可以找到有关设置 Py_FileSystemDefaultEncoding 的源代码。
Python 2.7的源代码中有两个地方:
-
bltinmodule.c https://hg.python.org/cpython/file/2.7/Python/bltinmodule.c#l17指定
Py_FileSystemDefaultEncoding
在 Windows 和 OS X 上
-
Py_InitializeEx()在其他 Unix 系统上设置它 https://hg.python.org/cpython/file/2.7/Python/pythonrun.c#l283- 注意:
setlocale(LC_CTYPE, "")
之前被调用nl_langinfo(CODESET)
并恢复回来setlocale(LC_CTYPE, saved_locale)
after.
你能给我一些如何在 python 源代码中搜索某些关键字的建议吗
要找到这些地方:
-
克隆Python 2.7源代码 https://docs.python.org/devguide/:
$ hg clone https://hg.python.org/cpython && cd cpython
$ hg update 2.7
-
搜索Py_FileSystemDefaultEncoding *=
在编辑器中输入正则表达式,例如:
$ make TAGS # to create tags table
在 Emacs 中:M-x tags-search RET Py_FileSystemDefaultEncoding *= RET
and M-,
继续搜索。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)