python /home/w00228598/python_test20160729/duoxc.py
運行duoxc.py腳本,報錯:
w00228598@linux02:~/python_test20160729> python duoxc.py
File "duoxc.py", line 17
SyntaxError: Non-ASCII character '\xe7' in file duoxc.py on line 17, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
w00228598@linux02:~/python_test20160729>
可按照錯誤建議網址查看http://www.python.org/peps/pep-0263.html
發現是因爲Python在默認狀態下不支持源文件中的編碼所致。解決方案有如下三種:
一、在文件頭部添加如下注釋碼:
# coding=<encoding name> 例如,可添加# coding=utf-8
二、在文件頭部添加如下兩行註釋碼:
#!/usr/bin/python
# -*- coding: <encoding name> -*- 例如,可添加# -*- coding: utf-8 -*-
三、在文件頭部添加如下兩行註釋碼:
#!/usr/bin/python
# vim: set fileencoding=<encoding name> : 例如,可添加# vim: set fileencoding=utf-8 :
附腳本:
w00228598@linux02:~/python_test20160729> cat duoxc.py
#!/usr/bin/python
# coding=utf-8
import time
import threading
def music(func):
for i in range(2):
print "I was listening to %s. %s"% (func,time.ctime())
time.sleep(2)
def movie(func):
for i in range(2):
print "I was watching to %s. %s"% (func,time.ctime())
time.sleep(5)
threads = []
t1 = threading.Thread(target=music,args=(u'愛情買賣',))
threads.append(t1)
t2 = threading.Thread(target=movie,args=(u'阿凡達',))
threads.append(t2)
if __name__ == '__main__':
for t in threads:
t.setDaemon(True)
t.start()
print "all is over. %s"% time.ctime()
w00228598@linux02:~/python_test20160729>