【问题标题】:where Py_FileSystemDefaultEncoding is set in python source code其中 Py_FileSystemDefaultEncoding 在 python 源代码中设置
【发布时间】:2015-02-15 04:28:46
【问题描述】:

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

既然pythondoc关于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=

【问题讨论】:

    标签: python python-2.7 locale


    【解决方案1】:

    总结: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-, 继续搜索。

    【讨论】:

    • 你能告诉我在哪里可以找到关于设置 Py_FileSystemDefaultEncoding 的源代码。
    • @andy:我添加了 Python 2.7 源代码的摘要和链接
    • 我明白了,很好。你能给我一些建议如何在python源代码中搜索一些关键字。
    • @andy:我添加了一种可能的方法来查找 Py_FileSystemDefaultEncoding 的定义位置
    猜你喜欢
    • 2015-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2021-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多