Python similar module Use Case (1), python module use case
I. threading VS Thread
As we all know, python supports multiple threads and native threads. Among them, threading encapsulates the Thread module and can be used in more aspects, the threading module mainly targets some Thread operations and creates a Thread class.
There are two ways to use a Thread. One is to create a function to be executed by the Thread, pass the function into the Thread object for execution, and the other is to inherit from the Thread directly, create a new class and put the code executed by the thread into the new class. The use case is as follows:
① Use Thread to implement Multithreading
#! /Usr/bin/env python #-*-coding: UTF-8-*-import stringimport threading import timedef threadMain (a): global count, mutex # obtain the thread name threadname = threading. currentThread (). getName () for x in xrange (0, int (a): # obtain the lock mutex. acquire () count + = 1 # Release the lock mutex. release () print threadname, x, count time. sleep () def main (num): global count, mutex threads = [] count = 1 # create a lock mutex = threading. lock () # first create a thread object 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 );
② Use threading to implement Multithreading
#! /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) # Start the thread for t in threads: t. start () # Wait until the sub-thread ends for t in threads: t. join ()
Ii. optparser VS getopt
① Use the getopt module to process command line options in Unix Mode
The getopt module is used to extract command line options and parameters, that is, sys. argv. The command line options make program parameters more flexible and support the short option mode and long option mode.
For example, python scriptname. py-f "hello"-directory-prefix = "/home"-t -- format 'A' B'
Format of the getopt function: getopt. getopt ([command line parameter list], 'short options', [long Option List])
The short option name is followed by a colon (:), indicating that the option must have additional parameters.
The long option name is followed by an equal sign (=), indicating that the option must have additional parameters.
Return options and args
Options is a parameter option and its value tuples ('-F', 'Hello'), ('-t', ''), ('-format ', ''), ('-directory-prefix','/home '))
Args is a command line input ('A', 'B') except for useful parameters ')
#!/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 Module
#!/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()