其中Py_FileSystemDefaultEncoding在python源代码中设置

时间:2015-02-15 04:28:46

标签: python python-2.7 locale

我很好奇python源代码如何设置Py_FileSystemDefaultEncoding的值。我收到了一件奇怪的事。

因为关于sys.getfilesystemencoding()的python doc说:

  

在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()的值不同,因为doc说getfilesystemencoding()是从locale.nl_landinfo()派生的。

以下是终端中的locale命令输出:

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=

1 个答案:

答案 0 :(得分:4)

摘要:sys.getfilesystemencoding()的行为与记录一致。混淆是由于setlocale(LC_CTYPE, "")(用户首选项)和默认C语言环境之间的差异。


脚本始终以默认的C语言环境开头:

>>> import locale
>>> locale.nl_langinfo(locale.CODESET)
'ANSI_X3.4-1968'

getfilesystemencoding()使用用户的区域设置:

>>> import sys
>>> sys.getfilesystemencoding()
'UTF-8'
>>> locale.setlocale(locale.LC_CTYPE, '')
'en_US.UTF-8'
>>> locale.nl_langinfo(locale.CODESET)
'UTF-8'

将字符串空字符串作为区域设置名称selects a locale based on the user choice of the appropriate environment variables

$ 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的源代码中有两个地方:


  

您能否给我一些建议,如何在python源代码中搜索一些关键字

找到这些地方:

  • clone Python 2.7 source code

    $ 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 *= RETM-,继续搜索。