【问题标题】:Must the encoding definition be in the 1st/2nd line in Python?编码定义必须在 Python 的第 1 行/第 2 行吗?
【发布时间】:2017-03-14 04:38:10
【问题描述】:

来自PEP263

要定义源代码编码,必须将魔术注释放在源文件中,作为文件的第一行或第二行,例如:

# coding=<encoding name>

或(使用流行编辑器认可的格式):

#!/usr/bin/python
# -*- coding: <encoding name> -*-

如果在某些情况下许可信息出现在最上面一行,例如来自https://github.com/google/seq2seq/blob/master/seq2seq/training/utils.py

# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# -*- coding: utf-8 -*-
"""Miscellaneous training utility functions.
"""

编码定义是否仍会被 Python 解释器“神奇地”接受?如果答案能解释为什么它必须位于第一两行并且指向解释器代码的指针会太棒了!

【问题讨论】:

  • 你引用的措辞很清楚,编码必须在第一行或第二行。
  • 你试过了吗?你会怎么做才能确定这个编码行是否在做它打算做的事情?
  • 我们怎样才能知道编码行是否在做它打算做的事情?在代码中添加一些“utf8”字符?
  • 如果不知道“你现在在做什么”,第一行和第二行对你没有任何帮助。编码有更多的变种(操作系统、系统、python 模块等),要看到神奇,需要选择限制编程的所有神奇力量!

标签: python encoding pep


【解决方案1】:

是的,在 Python 2 中,UTF-8 编码需要该编码标记,如果它超出第二行,并且文件中有任何非 ASCII 字符,您将引发如下错误:

File "encoded.py", line 5
SyntaxError: Non-ASCII character '\xe1' in file encoded.py on line 5, but 
no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

如果文件只包含 ASCII 字符,它仍然可以工作,即使 UTF-8 编码标记晚于第 2 行。ASCII 是 UTF-8 的子集,基本上,后期编码指令被忽略。 (您引用的特定utils.py 似乎就是这种情况。)

许多解析器和其他文件处理器要求将此类魔术命令置于文件开头,因为必须扫描并考虑这些命令才能正确解释文件。稍后再放它们,效率会很低,需要扫描整个文件才能找到一些“神奇”的特殊情况。

您将在 Python 3 中获得一些余地,它采用 UTF-8 编码。尽管如果您的文件以其他方式编码,您仍然希望包含它。

【讨论】:

    【解决方案2】:

    规范允许前 两行 行允许在 unix 系统上使用 shebang #!...

    不行,第二行之后是不允许的。

    这是来自 cpython 标记器的代码,用于检查(并解析)编码 cookie:https://github.com/python/cpython/blob/9e52c907b5511393ab7e44321e9521fe0967e34d/Parser/tokenizer.c#L613-L616

    【讨论】:

    • 很好的源链接 =)
    猜你喜欢
    • 2017-06-06
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多