python相似模塊用例
一:threading VS Thread
眾所周知,python是支持多線程的,而且是native的線程,其中threading是對Thread模塊做了包裝,可以更加方面的被使用,threading模塊里面主要對一些線程操作對象化了,創(chuàng)建了Thread的類。
使用線程有兩種模式,一種是創(chuàng)建線程要執(zhí)行的函數(shù),把這個函數(shù)傳遞進(jìn)Thread對象里,讓它來執(zhí)行,一種是直接從Thread繼承,創(chuàng)建一個新的class,把線程執(zhí)行的代碼放到這個新的類里面,用例如下:
①使用Thread來實現(xiàn)多線程
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import string
import threading
import time
def 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)建一個鎖
mutex = threading.Lock()
#先創(chuàng)建線程對象
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來實現(xiàn)多線程
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import threading
import time
class 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))
#啟動線程
for t in threads:
t.start()
#等待子線程結(jié)束
for t in threads:
t.join()
二:optparser VS getopt
①使用getopt模塊處理Unix模式的命令行選項
getopt模塊用于抽出命令行選項和參數(shù),也就是sys.argv,命令行選項使得程序的參數(shù)更加靈活,支持短選項模式和長選項模式
例:python scriptname.py –f “hello” –directory-prefix=”/home” –t --format ‘a(chǎn)'‘b'
getopt函數(shù)的格式:getopt.getopt([命令行參數(shù)列表],‘短選項',[長選項列表])
其中短選項名后面的帶冒號(:)表示該選項必須有附加的參數(shù)
長選項名后面有等號(=)表示該選項必須有附加的參數(shù)
返回options以及args
options是一個參數(shù)選項及其value的元組((‘-f','hello'),(‘-t',''),(‘—format',''),(‘—directory-prefix','/home'))
args是除去有用參數(shù)外其他的命令行 輸入(‘a(chǎn)',‘b')
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
import getopt
def Usage():
print "Usage: %s [-a|-0|-c] [--help|--output] args..."%sys.argv[0]
if __name__ == "__main__":
try:
options,args = getopt.getopt(sys.argv[1:],"ao:c",['help',"putput="]):
print options
print "\n"
print args
for option,arg in options:
if option in ("-h","--help"):
Usage()
sys.exit(1)
elif option in ('-t','--test'):
print "for test option"
else:
print option,arg
except getopt.GetoptError:
print "Getopt Error"
Usage()
sys.exit(1)
②optparser模塊
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import optparser
def main():
usage = "Usage: %prog [option] arg1,arg2..."
parser = OptionParser(usage=usage)
parser.add_option("-v","--verbose",action="store_true",dest="verbose",default=True,help="make lots of noise [default]")
parser.add_option("-q","--quiet",action="store_false",dest="verbose",help="be vewwy quiet (I'm hunting wabbits)")
parser.add_option("-f","--filename",metavar="FILE",help="write output to FILE")
parser.add_option("-m","--mode",default="intermediate",help="interaction mode: novice, intermediate,or expert [default: %default]")
(options,args) = parser.parse_args()
if len(args) != 1:
parser.error("incorrect number of arguments")
if options.verbose:
print "reading %s..." %options.filename
if __name__ == "__main__":
main()
以上就是threading VS Thread、optparser VS getopt 的相互比較,希望對大家學(xué)習(xí)模塊有所幫助。
相關(guān)文章
python?列表套json字典根據(jù)相同的key篩選數(shù)據(jù)
這篇文章主要介紹了python?列表套json字典根據(jù)相同的key篩選數(shù)據(jù),文章基于python的相關(guān)資料展開詳細(xì)的內(nèi)容介紹需要的小伙伴可以參考一下2022-04-04
python點擊鼠標(biāo)獲取坐標(biāo)(Graphics)
這篇文章主要為大家詳細(xì)介紹了python點擊鼠標(biāo)獲取坐標(biāo),具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-08-08
詳談python read readline readlines的區(qū)別
下面小編就為大家?guī)硪黄斦刾ython read readline readlines的區(qū)別。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09
django獲取from表單multiple-select的value和id的方法
今天小編就為大家分享一篇django獲取from表單multiple-select的value和id的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07
Python中json模塊load/loads方法實戰(zhàn)以及參數(shù)詳解
經(jīng)常在Python中對JSON格式的文件進(jìn)行操作,今天對這些操作做一個總結(jié),下面這篇文章主要給大家介紹了關(guān)于Python中json模塊load/loads方法實戰(zhàn)以及參數(shù)的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-08-08
使用tensorflow顯示pb模型的所有網(wǎng)絡(luò)結(jié)點方式
今天小編就為大家分享一篇使用tensorflow顯示pb模型的所有網(wǎng)絡(luò)結(jié)點方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01
python將ip地址轉(zhuǎn)換成整數(shù)的方法
這篇文章主要介紹了python將ip地址轉(zhuǎn)換成整數(shù)的方法,涉及Python針對IP地址的轉(zhuǎn)換技巧,需要的朋友可以參考下2015-03-03

