Python 編程常見問題
經常使用Python編程,把經常遇到問題在這裡記錄一下,省得到網上尋找,因此這篇文章會持續更新,需要的可以Mark一下。進入正題:
1.Python常用的檔案頭聲明
#!/usr/bin/python#-*- coding: UTF-8 -*-## @filename: # @author: # @since: 2013-# @version: 0.0.1## Usage:###############################################################################import osimport sysimport shutilimport fileinput# utf8import codecs
2.Python命令參數解析(長參數和短參數)
################################################################ command line for this app:# $ python app.py -s 5555 -p 5556# or# $ python app.py --sink-port 5555 --publish-port 5556###############################################################import osimport optparsepid = os.getpid()# parse our options# see usage for optparse.OptionParser():# http://docs.python.org/2/library/optparse.html#parser = optparse.OptionParser()parser.add_option("-s", "--sink-port", action="store", dest="sink_port", help="Specifies sink port on that service is listening")parser.add_option("-p", "--publish-port", action="store", dest="publish_port", help="Specifies publish port service publish to")# parse args and get options(options, args) = parser.parse_args()sink_port = options.sink_portpub_port = options.publish_portprint ("[Process:%d] is listening on (tcp://*:%s) and publish to (tcp://*:%s) ..." % (pid, sink_port, pub_port))
3.Python擷取外部中斷命令(Ctrl+C)結束本程式
import timeimport osimport signalis_exit = Falsepid = os.getpid()def sigint_handler(signum, frame): global is_exit is_exit = True print "[Process:%d] Receive a signal %d, is_exit = %d" % (pid, signum, is_exit)signal.signal(signal.SIGINT, sigint_handler)signal.signal(signal.SIGTERM, sigint_handler)while not is_exit:# sleep 1 secondtime.sleep(1)print "."print "[Process:%d] exit!" % (pid)
4.Python UTF-8檔案操作
一個好的習慣就是永遠使用UTF-8編碼作一切事情,包括Python檔案本身。下面使用UTF-8編碼開啟檔案並寫入資料:
#!/usr/bin/python#-*- coding: UTF-8 -*-# !!!請確保本Python檔案以UTF-8儲存!!!# utf8import codecsdef openFileUtf8(fname): fd = codecs.open(fname, "w", encoding = "UTF-8") return fddef closeFile(fd): fd.close()def writeUtf8(fd, str): fd.write(unicode(str, "UTF-8"))def writelnUtf8(fd, str): fd.write(unicode(str, "UTF-8") + '\r\n')fw = openFileUtf8("/path/to/yourfile.txt")writeUtf8(fw, "我愛你,中國")closeFile(fw)
5.Python UTF-8中文字串操作
下面示範如何擷取UTF8字串長度(有效文字個數)和截斷:
#!/usr/bin/python#-*- coding: UTF-8 -*-# !!!請確保本Python檔案以UTF-8儲存!!!# 對於中文UTF-8編碼的字串,如何得到長度並截斷其中的字元呢?# 思路就是:# 首先把UTF-8字串轉成UTF-16(Unicode)字串,# 然後判斷UTF-16長度,截斷UTF-16字串,再轉回UTF-8:import codecsutf8str = "我愛你love,中國"print "utf8:", utf8strutf16str = utf8str.decode('utf-8')print "utf16 len (==10):", len(utf16str)# 截取前3個字元utf16str = utf16str[0:7]# 截取到的字元轉回UTF-8utf8substr = utf16str.encode('utf-8')print "utf8 substr:", utf8substrprint "上面全部過程寫成一句話: utf8substr = utf8str.decode('utf-8')[0:7].encode('utf-8') "utf8substr = utf8str.decode('utf-8')[0:7].encode('utf-8')print "utf8 substr:", utf8substr
運行:
6. MySQL - Python
在Ubuntu上使用Python操作MySQL, 首先是安裝:
$ wget http://sourceforge.net/projects/mysql-python/files/mysql-python/1.2.3/MySQL-python-1.2.3.tar.gz$ tar -zxvf MySQL-python-1.2.3.tar.gz$ cd MySQL-python-1.2.3$ sudo python setup.py install
錯誤解決辦法:
錯誤:Traceback (most recent call last): File "setup.py", line 5, in from setuptools import setup, ExtensionImportError: No module named setuptools解決:$ sudo apt-get install python-setuptools錯誤:sh: mysql_config: not found...EnvironmentError: mysql_config not found解決:$ sudo apt-get install libmysqlclient-dev錯誤:...error: command 'gcc' failed with exit status 1解決:$ sudo apt-get install python-dev
7. 使用 MySQL - Python
http://www.cnblogs.com/ceniy/archive/2010/08/31/1814066.html
(未完待續...)