PEP 263 http://www.python.org/dev/peps/pep-0263/定义如何声明Python源代码编码。通常,Python 文件的前两行应以以下内容开头:
#!/usr/bin/python
# -*- coding: <encoding name> -*-
但我看到很多文件都是这样开头的:
#!/usr/bin/python
# -*- encoding: <encoding name> -*-
即,它说encoding
而不是coding
.
文件编码应该如何声明?
Please use "SyntaxError: Non-ASCII character ..." or "SyntaxError: Non-UTF-8 code starting with ..." trying to use non-ASCII text in a Python script https://stackoverflow.com/questions/10589620 to close duplicate questions about syntax errors resulting from a missing or faulty encoding declaration. This question, on the other hand, is the canonical for questions about how the declaration is written and whether it is necessary.
检查文档here http://docs.python.org/reference/lexical_analysis.html#encoding-declarations:
“如果Python脚本的第一行或第二行中的注释与正则表达式匹配coding[=:]\s*([-\w.]+)
,该注释被处理为编码声明”
“该表达式的推荐形式是
# -*- coding: <encoding-name> -*-
GNU Emacs 也认可它,并且
# vim:fileencoding=<encoding-name>
这是 Bram Moolenaar 的 VIM 所认可的。”
因此,您可以在“编码”部分之前放置几乎任何内容,但如果您想 100% python-docs-recommendation 兼容,请坚持使用“编码”(没有前缀)。
更具体地说,你需要使用Python可以识别的任何东西以及您使用的具体编辑软件(如果它需要/接受任何东西)。例如。这coding
形式被 GNU Emacs 识别(开箱即用),但 Vim 不识别(是的,没有通用协议,它本质上是一个turf war https://en.wikipedia.org/wiki/Turf_war).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)