python相似模組用例

來源:互聯網
上載者:User
一:threading VS Thread

眾所周知,python是支援多線程的,而且是native的線程,其中threading是對Thread模組做了封裝,可以更加方面的被使用,threading模組裡面主要對一些線程操作對象化了,建立了Thread的類。

使用線程有兩種模式,一種是建立線程要執行的函數,把這個函數傳遞進Thread對象裡,讓它來執行,一種是直接從Thread繼承,建立一個新的class,把線程執行的代碼放到這個新的類裡面,用例如下:

①使用Thread來實現多線程

#!/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  #建立一個鎖  mutex = threading.Lock()  #先建立線程對象  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來實現多線程

#!/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))  #啟動線程  for t in threads:    t.start()  #等待子線程結束  for t in threads:    t.join()

二:optparser VS getopt

①使用getopt模組處理Unix模式的命令列選項

getopt模組用於抽出命令列選項和參數,也就是sys.argv,命令列選項使得程式的參數更加靈活,支援短選項模式和長選項模式

例:python scriptname.py –f “hello” –directory-prefix=”/home” –t --format ‘a'‘b'

getopt函數的格式:getopt.getopt([命令列參數列表],‘短選項',[長選項列表])

其中短選項名後面的帶冒號(:)表示該選項必須有附加的參數

長選項名後面有等號(=)表示該選項必須有附加的參數

返回options以及args

options是一個參數選項及其value的元組((‘-f','hello'),(‘-t',''),(‘—format',''),(‘—directory-prefix','/home'))

args是除去有用參數外其他的命令列 輸入(‘a',‘b')

#!/usr/bin/env python# -*- coding:utf-8 -*-import sysimport getoptdef 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 optparserdef 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 的相互比較,希望對大家學習模組有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.