在源文件中声明编码的问题

problems with declaring encoding in a source file

我正在尝试学习在阅读 PEP 263 的源文件中使用编码声明,我正在自己试验,但遇到了一些麻烦。

这是我的文件cod.py:

# -*- coding: utf-16 -*-
print('ciao')

并且我使用UTF-16编码保存了它;现在:

antox@antox-pc ~/Scrivania $ python3 cod.py 
  File "cod.py", line 1
SyntaxError: Non-UTF-8 code starting with '\xff' in file cod.py on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

所以我不明白我哪里错了。

P.S。我正在使用 gedit 2.30.4

UTF-16 不被接受为 Python 源代码的编码。来自 PEP 263(概念部分,第 1 项):

Any encoding which allows processing the first two lines in the way indicated above is allowed as source code encoding, this includes ASCII compatible encodings as well as certain multi-byte encodings such as Shift_JIS. It does not include encodings which use two or more bytes for all characters like e.g. UTF-16. The reason for this is to keep the encoding detection algorithm in the tokenizer simple.

所以您收到的错误是预料之中的:您可以使用不同的编码(默认的 UTF-8 除外),只要它可以被 Python 检测到即可。