python相似模塊用例
一:threading VS Thread
眾所周知,python是支持多線程的,而且是native的線程,其中threading是對Thread模塊做了包裝,可以更加方面的被使用,threading模塊里面主要對一些線程操作對象化了,創(chuàng)建了Thread的類。
使用線程有兩種模式,一種是創(chuàng)建線程要執(zhí)行的函數(shù),把這個(gè)函數(shù)傳遞進(jìn)Thread對象里,讓它來執(zhí)行,一種是直接從Thread繼承,創(chuàng)建一個(gè)新的class,把線程執(zhí)行的代碼放到這個(gè)新的類里面,用例如下:
①使用Thread來實(shí)現(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)建一個(gè)鎖
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來實(shí)現(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))
#啟動(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)模式和長選項(xiàng)模式
例:python scriptname.py –f “hello” –directory-prefix=”/home” –t --format ‘a(chǎn)'‘b'
getopt函數(shù)的格式:getopt.getopt([命令行參數(shù)列表],‘短選項(xiàng)',[長選項(xiàng)列表])
其中短選項(xiàng)名后面的帶冒號(hào)(:)表示該選項(xiàng)必須有附加的參數(shù)
長選項(xiàng)名后面有等號(hào)(=)表示該選項(xiàng)必須有附加的參數(shù)
返回options以及args
options是一個(gè)參數(shù)選項(xiàng)及其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í)模塊有所幫助。
- python thread 并發(fā)且順序運(yùn)行示例
- python getopt 參數(shù)處理小示例
- python線程鎖(thread)學(xué)習(xí)示例
- Python getopt模塊處理命令行選項(xiàng)實(shí)例
- Python中多線程thread與threading的實(shí)現(xiàn)方法
- Python threading多線程編程實(shí)例
- python采用getopt解析命令行輸入?yún)?shù)實(shí)例
- python多線程threading.Lock鎖用法實(shí)例
- Python THREADING模塊中的JOIN()方法深入理解
- Python中的getopt函數(shù)使用詳解
相關(guān)文章
python中shapefile庫讀取shapefile文件信息
本文主要介紹了python中shapefile庫讀取shapefile文件信息,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06
Python iter()函數(shù)用法實(shí)例分析
這篇文章主要介紹了Python iter()函數(shù)用法,結(jié)合實(shí)例形式詳細(xì)分析了Python iter()函數(shù)的功能、使用方法及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下2018-03-03
Python類和對象的定義與實(shí)際應(yīng)用案例分析
這篇文章主要介紹了Python類和對象的定義與實(shí)際應(yīng)用,結(jié)合三個(gè)具體案例形式分析了Python面向?qū)ο蟪绦蛟O(shè)計(jì)中類與對象的定義、應(yīng)用、設(shè)計(jì)模式等相關(guān)操作技巧,需要的朋友可以參考下2018-12-12
解決python執(zhí)行較大excel文件openpyxl慢問題
這篇文章主要介紹了解決python執(zhí)行較大excel文件openpyxl慢問題,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05
Python queue隊(duì)列原理與應(yīng)用案例分析
這篇文章主要介紹了Python queue隊(duì)列原理與應(yīng)用,結(jié)合具體案例形式分析了Python queue隊(duì)列的原理、功能、實(shí)現(xiàn)方法與使用技巧,需要的朋友可以參考下2019-09-09
python程序快速縮進(jìn)多行代碼方法總結(jié)
在本篇文章里小編給大家整理了關(guān)于python程序如何快速縮進(jìn)多行代碼的相關(guān)知識(shí)點(diǎn),需要的朋友們學(xué)習(xí)下。2019-06-06

