Python 这是从哪里来的:-*- 编码:utf-8 -*-

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4872007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 17:55:55  来源:igfitidea点击:

Where does this come from: -*- coding: utf-8 -*-

pythonfiletextencodingemacs

提问by hamstergene

Python recognizes the following as instruction which defines file's encoding:

Python 将以下内容识别为定义文件编码的指令:

# -*- coding: utf-8 -*-

I definitely saw this kind of instructions before (-*- var: value -*-). Where does it come from? What is the full specification, e.g. can the value include spaces, special symbols, newlines, even -*-itself?

我之前肯定看过这种说明(-*- var: value -*-)。它从何而来?完整的规范是什么,例如,值可以包括空格、特殊符号、换行符,甚至-*-本身吗?

My program will be writing plain text files and I'd like to include some metadata in them using this format.

我的程序将编写纯文本文件,我想使用这种格式在其中包含一些元数据。

采纳答案by Andrea Spadaccini

This way of specifying the encoding of a Python file comes from PEP 0263 - Defining Python Source Code Encodings.

这种指定 Python 文件编码的方式来自PEP 0263 - 定义 Python 源代码编码

It is also recognized by GNU Emacs (see Python Language Reference, 2.1.4 Encoding declarations), though I don't know if it was the first program to use that syntax.

它也被 GNU Emacs 识别(参见Python 语言参考,2.1.4 编码声明),但我不知道它是否是第一个使用该语法的程序。

回答by Alex Ott

This is so called file local variables, that are understood by Emacs and set correspondingly. See corresponding section in Emacs manual- you can define them either in header or in footer of file

这就是所谓的文件局部变量,它被 Emacs 理解并相应地设置。请参阅Emacs 手册中的相应部分- 您可以在文件的页眉或页脚中定义它们

回答by cwp393

In PyCharm, I'd leave it out. It turns off the UTF-8 indicator at the bottom with a warning that the encoding is hard-coded. Don't think you need the PyCharm comment mentioned above.

在 PyCharm 中,我会忽略它。它关闭底部的 UTF-8 指示器,并警告编码是硬编码的。不要认为你需要上面提到的 PyCharm 注释。

回答by Boris

# -*- coding: utf-8 -*-is a Python 2 thing. In Python 3+, the default encoding of source files is UTF-8 and that line is useless.

# -*- coding: utf-8 -*-是 Python 2 的东西。在 Python 3+ 中,源文件的默认编码是 UTF-8,该行没有用。

See: Should I use encoding declaration in Python 3?

请参阅:我应该在 Python 3 中使用编码声明吗?

pyupgradeis a tool you can run on your code to remove those comments and other no-longer-useful leftovers from Python 2, like having all your classes inherit from object.

pyupgrade是一种可以在代码上运行的工具,用于从 Python 2 中删除这些注释和其他不再有用的剩余部分,例如让所有类都继承自object.