本文共 3195 字,大约阅读时间需要 10 分钟。
是用来说明脚本语言是python的
是要用/usr/bin下面的程序(工具)python,这个解释器,来解释python脚本,来运行python脚本的。
是用来指定文件编码为utf-8的
详情可以参考:
在此,详细的(主要是翻译)解释一下,为何要加这个编码声明,以及如何添加编码声明:
Python 2.1中,想要输入Unicode字符,只能用基于Latin-1的"unicode-escape"的方式输入 -> 对于其他非Latin-1的国家和用户,想要输入Unicode字符,就显得很繁琐,不方便。
希望是:
编程人员,根据自己的喜好和需要,以任意编码方式输入字符串,都可以,这样才正常。
所以,才有人给Python官方建议,所以才有此PEP 0263。
此建议就是:
允许在Python文件中,通过文件开始处的,放在注释中的,字符串形式的,声明,声明自己的python文件,用何种编码。
由此,需要很多地方做相应的改动,尤其是Python文件的解析器,可以识别此种文件编码声明。
上面已经说了,是,文件开始处的,放在注释中的,字符串形式的,声明。
那具体如何声明,以什么样的格式去声明呢?
其实就是,你之前就见过的,这种:
1 | # -*- coding: utf-8 -*- |
对此格式的详细解释是:
1 | # coding=<encoding name> |
1 2 | #!/usr/bin/python # -*- coding: <encoding name> -*- |
1 2 | #!/usr/bin/python # vim: set fileencoding=<encoding name> : |
1 | "coding[:=]\s*([-\w.]+)" |
1 2 3 4 5 | coding: utf - 8 coding = utf - 8 coding = utf - 8 encoding:utf - 8 crifanEncoding = utf - 8 |
针对上面的规则,下面给出各种,合法的,非法的,例子,供参考:
1 2 3 4 | #!/usr/bin/python # -*- coding: latin-1 -*- import os, sys ... |
1 2 3 4 | #!/usr/bin/python # -*- coding: iso-8859-15 -*- import os, sys ... |
1 2 3 4 | #!/usr/bin/python # -*- coding: ascii -*- import os, sys ... |
1 2 3 | # This Python file uses the following encoding: utf-8 import os, sys ... |
1 2 3 4 | #!/usr/local/bin/python # coding: latin-1 import os, sys ... |
1 2 3 | #!/usr/local/bin/python import os, sys ... |
1 2 3 4 | #!/usr/local/bin/python # latin-1 import os, sys ... |
1 2 3 4 5 | #!/usr/local/bin/python # # -*- coding: latin-1 -*- import os, sys ... |
1 2 3 4 | #!/usr/local/bin/python # -*- coding: utf-42 -*- import os, sys ... |
1.单个的完整的python源码文件中,只用单一的编码。
->
不允许嵌入了多种的编码的数据
否则会导致(python解释器去解析你的python文件时)报编码错误。
不太懂这段:
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. |
2.这段也不太懂:
Handling of escape sequences should continue to work as it does now, but with all possible source code encodings, that is standard string literals (both 8-bit and Unicode) are subject to escape sequence expansion while raw string literals only expand a very small subset of escape sequences. |
3.Python的分词器+编译器,会按照如下的逻辑去工作:
要注意的是:
Python中的标识符,都是ASCII的。
其余的内容,不翻译了。
至此,已经解释的够清楚了。
转载地址:http://uwzub.baihongyu.com/