python2在执行python代码时读取文件默认使用ASCII编码,因此我们经常看到在代码的前边有如下声明:
看起来很呆萌,对不对。为什么要有此声明,python的PEP中有说明 http://www.python.org/dev/peps/pep-0263/
并且必须将编码注释放在第一行或者第二行。
# coding=<encoding name>
or (using formats recognized by popular editors)
#!/usr/bin/python
# -*- coding: <encoding name> -*-
当然还支持其他声明方式。当然呆萌的写法大家都喜欢用咯。
下面是支持和不支持的写法说明,供大家参考。另外python3 的默认读取代码采用的是unicode,所以python3 该声明可选,如果需要其他编码的话,还是可以采用上述写法的。
Examples
These are some examples to clarify the different styles for defining the source code encoding at the top of a Python source file:
1. With interpreter binary and using Emacs style file encoding comment:
#!/usr/bin/python
# -*- coding: latin-1 -*-import os, sys
...
#!/usr/bin/python
# -*- coding: iso-8859-15 -*-
import os, sys
...
#!/usr/bin/python
# -*- coding: ascii -*-
import os, sys
...
2. Without interpreter line, using plain text:
# This Python file uses the following encoding: utf-8
import os, sys
...
3. Text editors might have different ways of defining the file's
encoding, e.g.
#!/usr/local/bin/python
# coding: latin-1
import os, sys
...
4. Without encoding comment, Python's parser will assume ASCII text:
#!/usr/local/bin/python
import os, sys
...
5. Encoding comments which don't work:
Missing "coding:" prefix:
#!/usr/local/bin/python
# latin-1
import os, sys
...
Encoding comment not on line 1 or 2:
#!/usr/local/bin/python
#
# -*- coding: latin-1 -*-
import os, sys
...
Unsupported encoding:
#!/usr/local/bin/python
# -*- coding: utf-42 -*-
import os, sys
...