问题描述
在您告诉我阅读之前,请保留阅读...
Before you go telling me to read PEP 0263, keep reading...
我找不到任何详细信息的文档哪些文件编码支持Python 3源文件。
I can't find any documentation that details which file encodings are supported for Python 3 source files.
我发现了数百(数千)的问题,答案,帖子,电子邮件等关于如何声明 - 在源文件的顶部 - 编码的源文件,但他们都没有回答我的问题。与我一起想象(或者实际尝试)以下内容:
I've found hundreds (thousands?) of questions, answers, posts, emails, etc. about how to declare - at the top of your source file - the encoding of that source file, but none of them answer my question. Bear with me and imagine doing (or actually try) the following:
- 打开记事本(我在Windows 7上使用常规的旧记事本,但我怀疑它很重要,我相信你的上级编辑可以做类似的事情。)
- 输入你最喜爱的Python代码行(我使用
print('Hello选择文件 - >保存
- 选择一个文件夹和文件名(我使用E:\Temp\hello.py)
- 将Encoding:设置从默认的ANSI更改为Unicode
- 按保存
- 打开命令提示符,切换到包含新文件的文件夹,然后尝试运行
Open Notepad (I'm using regular old Notepad on Windows 7, but I doubt it matters; I'm sure your superior editor can do something similar.)
Type your favorite line of Python code ( I used
print( 'Hello, world!' )
)Select "File" -> "Save"
Select a folder and file name ( I used "E:\Temp\hello.py" )
Change the "Encoding:" setting from the default "ANSI" to "Unicode"
Press "Save"
Open a command prompt, change to the folder containing your new file, and try to run it
这是我得到的输出:
E:\Temp>python --version
Python 3.4.1
E:\Temp>python "hello.py"
File "hello.py", line 1
SyntaxError: Non-UTF-8 code starting with '\xff' in file hello.py on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
现在,当我在中打开同一个文件时,看看编码菜单,它有选项选择UCS-2小尾编码。 - 以及关于它的一切 - 在网络上,我尝试添加一个这样的评论到第一行文件
So I go and read PEP 0263 - and everything else regarding it - on the web, and I try adding a comment like this to the first line of the file
# coding: utf-16
与编码的各种不同的值,没有任何帮助。但是它不能帮助,对吧?因为Python甚至不能达到我的编码声明;它源于源文件的第一个字节窒息!
with all sorts of different values for the encoding, and nothing helps. But it can't help, right? Because Python isn't even getting as far as my encoding declaration; It's choking on the first byte of the source file!
所以我真正想知道的是...
So what I really want to know is...
- 为什么Python 3解释器不能读取这个文件?
- 如果是Unicode或UCS-2 Little Endian或 UTF-16或不支持,什么是???
Why can't the Python 3 interpreter read this file?
If "Unicode" or "UCS-2 Little Endian" or "UTF-16" or whatever isn't supported, what is???
我甚至发现
The encoding that Windows misleadingly calls "Unicode", UTF-16LE, is not ASCII-compatible (and generally is a barrel of problems you should try to avoid using). Python would need special encoding-specific support to detect UTF-16 source files and this feature has been declined for now.
您应该使用的
#编码:
几乎总是UTF-8。
The
# coding:
you should use is almost invariably UTF-8.
这篇关于哪些文件编码支持Python 3源文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!