推薦:
#!/usr/bin/env python3 # -*- coding: utf-8 -*-
我們知道在Python源碼的頭文件中要聲明編碼方式,如果你不只是會用到ascii碼,很多人都寫得都有點差別:
#coding=utf-8
#coding:utf-8
#-*- coding:utf-8 -*-
那么怎樣寫才是有效地呢,哪些優勢無效的呢?
可以查看下http://www.python.org/dev/peps/pep-0263/的解釋
粗略的看下:
概要:
這個PEP的目的是介紹在一個Python源文件中如何聲明編碼的語法。隨后Python解釋器會在解釋文件的時候用到這些編碼信息。最顯著的是源文件中對Unicode的解釋,使得在一個能識別Unicode的編輯器中使用如FUT-8編碼成為可能
怎么聲明呢?
如果在Python中我們並沒有聲明別的編碼方式,就是以ASCII編碼作為標准編碼方式的
為了定義源文件的編碼方式,一個魔法是的聲明應當被放在這個文件的第一行或者是第二行例如:
#coding=<encoding name>
或者(使用流行編輯器中的格式化方式)
-
#!/usr/bin/python
-
# -*- coding: <encoding name> -*-
或者
-
#!/usr/bin/python
-
# vim: set fileencoding=<encoding name> :
不管怎么樣,這些在第一行或者第二行的聲明都要符合正則表達式
"coding[:=]\s*([-\w.]+)"
所以我們就可以知道為什么使用冒號或者等號都可以了,如果聲明的編碼python不能識別就會報錯
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
...
以上幾個例子充分說明了哪些是正確的寫法,哪些是正確的寫法