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

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

问题描述

PEP 263 定义了如何定义Python源代码编码。 p>

通常,Python文件的前2行应以:开头:

 # -  *  - 编码:<编码名称> -  *  -  

但是我看到很多文件从以下开始:

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

- > 编码而不是 strong>。



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



编码因为所使用的正则表达式是懒惰的?或者这只是另一种声明文件编码的形式?



我提出这个问题,因为PEP没有谈论编码,它

解决方案

查看文档 here



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



此表达式的推荐形式是

 # -  *  - 编码:< encoding-name>  -  *  -  

这是GNU Emacs ,和

 #vim:fileencoding =< encoding-name> 
pre>

这被Bram Moolenaar的VIM认可。



所以,你可以把几乎所有的编码部分之前,但坚持编码(没有前缀),如果你想要是100%python-docs推荐兼容。



更具体地说,您需要使用Python 和您使用的特定编辑软件所确认的任何内容(如果需要/接受任何内容)。例如。 编码格式被GNU Emacs识别(开箱即用),但不是Vim(是的,没有普遍的协议,它本质上是一个草皮战争)。


PEP 263 defines how to define 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天全站免登陆