一:threading VS Thread
眾所周知,python是支持多線程的,而且是native的線程,其中threading是對(duì)Thread模塊做了包裝,可以更加方面的被使用,threading模塊里面主要對(duì)一些線程操作對(duì)象化了,創(chuàng)建了Thread的類。
使用線程有兩種模式,一種是創(chuàng)建線程要執(zhí)行的函數(shù),把這個(gè)函數(shù)傳遞進(jìn)Thread對(duì)象里,讓它來(lái)執(zhí)行,一種是直接從Thread繼承,創(chuàng)建一個(gè)新的class,把線程執(zhí)行的代碼放到這個(gè)新的類里面,用例如下:
①使用Thread來(lái)實(shí)現(xiàn)多線程
#!/usr/bin/env python#-*- coding:utf-8 -*-import stringimport threading import timedef threadMain(a): global count,mutex #獲得線程名 threadname = threading.currentThread().getName() for x in xrange(0,int(a)): #獲得鎖 mutex.acquire() count += 1 #釋放鎖 mutex.release() print threadname,x,count time.sleep()def main(num): global count,mutex threads = [] count = 1 #創(chuàng)建一個(gè)鎖 mutex = threading.Lock() #先創(chuàng)建線程對(duì)象 for x in xrange(0,num): threads.append(threading.Thread(target = threadMain,args=(10,))) for t in threads: t.start() for t in threads: t.join()if __name__ == "__main__": num = 4 main(num);
②使用threading來(lái)實(shí)現(xiàn)多線程
#!/usr/bin/env python#-*- coding:utf-8 -*-import threadingimport timeclass Test(threading.Thread): def __init__(self,num): threading.Thread.__init__(self): self._run_num = num def run(self): global count,mutex threadName = threading.currentThread.getName() for x in xrange(0,int(self._run_num)): mutex.acquire() count += 1 mutex.release() print threadName,x,count time.sleep(1)if __name__ == "__main__": global count,mutex threads = [] num = 4 count = 1 mutex.threading.Lock() for x in xrange(o,num): threads.append(Test(10)) #啟動(dòng)線程 for t in threads: t.start() #等待子線程結(jié)束 for t in threads: t.join()
二:optparser VS getopt
①使用getopt模塊處理Unix模式的命令行選項(xiàng)
getopt模塊用于抽出命令行選項(xiàng)和參數(shù),也就是sys.argv,命令行選項(xiàng)使得程序的參數(shù)更加靈活,支持短選項(xiàng)模式和長(zhǎng)選項(xiàng)模式
例:python scriptname.py 主站蜘蛛池模板: 周宁县| 介休市| 佛学| 水富县| 巨野县| 长白| 清河县| 大英县| 巧家县| 乌兰县| 平遥县| 曲阳县| 土默特右旗| 洪洞县| 秦皇岛市| 大丰市| 永昌县| 峨山| 石棉县| 广饶县| 漾濞| 阜阳市| 康乐县| 庆云县| 榆社县| 剑阁县| 花莲县| 罗定市| 永善县| 肃北| 湟中县| 宜川县| 文山县| 个旧市| 大城县| 华亭县| 原平市| 镇巴县| 承德县| 安陆市| 平安县|