定义Python源代码编码的正确方法 [英] Correct way to define Python source code encoding

查看:32
本文介绍了定义Python源代码编码的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PEP 263 定义了如何声明 Python 源代码编码.>

通常,Python 文件的前两行应该以:

#!/usr/bin/python# -*- 编码:<编码名称>-*-

但是我看到很多文件以:

#!/usr/bin/python# -*- 编码:<编码名称>-*-

=> 编码而不是编码.

那么声明文件编码的正确方法是什么?

是否允许 编码 因为使用的正则表达式是惰性的?还是只是声明文件编码的另一种形式?

我问这个问题是因为 PEP 不讨论编码,它只讨论编码.

解决方案

检查文档 这里:

"如果 Python 脚本第一行或第二行的注释与正则表达式 coding[=:]s*([-w.]+) 匹配,则处理此注释作为编码声明"

"这个表达式的推荐形式是

# -*- coding: -*-

也被 GNU Emacs 识别,并且

# vim:fileencoding=

被 Bram Moolenaar 的 VIM 识别."

因此,您几乎可以在编码"部分之前放置任何内容,但如果您想 100% 兼容 python-docs-recommendation,请坚持使用编码"(没有前缀).

更具体地说,您需要使用 Python 识别的任何内容以及您使用的特定编辑软件(如果它需要/接受任何内容).例如.coding 形式被 GNU Emacs 识别(开箱即用),但 Vim 不能识别(是的,没有通用协议,它本质上是一个 草坪战争).

PEP 263 defines how to declare Python source code encoding.

Normally, the first 2 lines of a Python file should start with:

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

But I have seen a lot of files starting with:

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

=> encoding instead of coding.

So what is the correct way of declaring the file encoding?

Is encoding permitted because the regex used is lazy? Or is it just another form of declaring the file encoding?

I'm asking this question because the PEP does not talk about encoding, it just talks about coding.

解决方案

Check the docs here:

"If a comment in the first or second line of the Python script matches the regular expression coding[=:]s*([-w.]+), this comment is processed as an encoding declaration"

"The recommended forms of this expression are

# -*- coding: <encoding-name> -*-

which is recognized also by GNU Emacs, and

# vim:fileencoding=<encoding-name>

which is recognized by Bram Moolenaar’s VIM."

So, you can put pretty much anything before the "coding" part, but stick to "coding" (with no prefix) if you want to be 100% python-docs-recommendation-compatible.

More specifically, you need to use whatever is recognized by Python and the specific editing software you use (if it needs/accepts anything at all). E.g. the coding form is recognized (out of the box) by GNU Emacs but not Vim (yes, without a universal agreement, it's essentially a turf war).

这篇关于定义Python源代码编码的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆