【问题标题】:Python 2 assumes different source code encodingsPython 2 采用不同的源代码编码
【发布时间】:2018-08-05 15:44:59
【问题描述】:

我注意到,如果没有源代码编码声明,Python 2 解释器假定源代码是用 scriptsstandard input 以 ASCII 编码的:

$ python test.py  # where test.py holds the line: print u'é'
  File "test.py", line 1
SyntaxError: Non-ASCII character '\xc3' in file test.py on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

$ echo "print u'é'" | python
  File "/dev/fd/63", line 1
SyntaxError: Non-ASCII character '\xc3' in file /dev/fd/63 on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

它以 ISO-8859-1 编码,带有 -m module-c command 标志:

$ python -m test  # where test.py holds the line: print u'é'
é

$ python -c "print u'é'"
é

记录在哪里?

与 Python 3 相比,Python 3 始终假定源代码以 UTF-8 编码,因此在四种情况下打印 é

注意。 – 我在 macOS 10.13 和 Ubuntu Linux 17.10 上的 CPython 2.7.14 上对此进行了测试,控制台编码设置为 UTF-8。

【问题讨论】:

    标签: python character-encoding ascii iso-8859-1 python-internals


    【解决方案1】:

    -c-m 开关最终(*)运行exec statementcompile() function 提供的代码,两者都采用Latin-1 源代码:

    第一个表达式的计算结果应为 Unicode 字符串、Latin-1 编码字符串、打开的文件对象、代码对象或元组。

    这没有记录,它是一个实现细节,可能会或可能不会被视为错误。

    我不认为这是值得修复的东西,而且 Latin-1 是 ASCII 的超集,所以几乎没有丢失。如何处理来自-c-m 的代码已在Python 3 中进行了清理,并且在那里更加一致;使用-c 传入的代码使用当前语言环境进行解码,使用-m 开关加载的模块像往常一样默认为UTF-8。


    (*)如果您想知道所使用的具体实现,请从Py_Main() function in Modules/main.c 开始,它将-c-m 处理为:

    if (command) {
        sts = PyRun_SimpleStringFlags(command, &cf) != 0;
        free(command);
    } else if (module) {
        sts = RunModule(module, 1);
        free(module);
    }
    

    【讨论】:

    • 另一件事,Python 2 文档states:“默认情况下,Python 源文件被视为以 UTF-8 编码。”我上面的第一个测试显示 ASCII 是默认的,所以这是一个文档错误,对吧?
    • @Maggyero:哦,男孩,是的,这是教程中的错误。语言参考是官方出处,见Lexical Analysis sectionPython 程序文本使用 7 位 ASCII 字符集。
    • @Maggyero:我找到了incorrect revision,这个错误是最近引入的。我已提交a Python bug report 进行更正。
    猜你喜欢
    • 2013-02-19
    • 2012-01-25
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    • 2014-09-03
    • 2022-01-01
    • 1970-01-01
    • 2020-10-27
    相关资源
    最近更新 更多