Python Similar module use case

Source: Internet
Author: User
Tags mutex

One: Threading VS Thread

As we all know, Python is to support multi-threaded, and is a native thread, where threading is the thread module has been packaged, can be used more, threading module inside the main to some of the thread Operation object, created the thread class.

There are two modes of using threads, one is to create a function to execute the thread, to pass the function into the thread object, to execute it, to inherit directly from thread, to create a new class, to put the code executed by the thread into the new class, using the following use case:

① using thread to implement multithreading

#!/usr/bin/env python#-*-coding:utf-8-*-ImportstringImportThreadingImport TimedefThreadMain (a):GlobalCount,mutex#get the thread nameThreadName =Threading.currentthread (). GetName () forXinchxrange (0,int (a)):#Get lockMutex.acquire () Count+ = 1#Release Lockmutex.release ()Printthreadname,x,count time.sleep ()defMain (num):GlobalCount,mutex Threads=[] Count= 1#Create a lockMutex =Threading. Lock ()#Create a Thread object first     forXinchxrange (0,num): Threads.append (Threading. Thread (Target= threadmain,args= (10,)))  forTinchThreads:t.start () forTinchThreads:t.join ()if __name__=="__main__": Num= 4main (num);

② using threading to implement multithreading

#!/usr/bin/env python#-*-coding:utf-8-*-ImportThreadingImport TimeclassTest (Threading. Thread):def __init__(self,num): Threading. Thread.__init__(self): Self._run_num=NumdefRun (self):GlobalCount,mutex ThreadName=Threading.currentThread.getName () forXinchxrange (0,int (Self._run_num)): Mutex.acquire () Count+ = 1mutex.release ()PrintThreadname,x,count Time.sleep (1)if __name__=="__main__":    GlobalCount,mutex Threads=[] Num= 4Count= 1Mutex.threading.Lock () forXinchxrange (o,num): Threads.append (Test (10))    #Start Thread     forTinchThreads:t.start ()#wait for the child thread to end     forTinchThreads:t.join ()

II: Optparser VS getopt

① command-line options for UNIX mode with the Getopt module

The Getopt module is used to extract command-line options and parameters, i.e., SYS.ARGV, which makes the program's parameters more flexible, supports both short and long option modes

Example: Python scriptname.py–f "Hello" –directory-prefix= "/Home" –t--format ' a ' B '

Format of the getopt function: getopt.getopt ([command line argument list], ' short options ', [long list of options])

Where the short option name is followed by a colon (:) indicates that the option must have additional parameters

An equal sign (=) after the long option name indicates that the option must have additional parameters

Back to options and args

Options is a tuple of parameter options and their value ('-f ', ' Hello '), ('-t ', '), ('-format ', '), ('-directory-prefix ', '/home ')

Args is a command-line input (' A ', ' B ') that removes useful arguments

#!/usr/bin/env python#-*-coding:utf-8-*-ImportSYSImportgetoptdefUsage ():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="]):        PrintOptionsPrint "\ n"        Printargs forOption,arginchOptions:ifOptioninch("- H","--help"): Usage () sys.exit (1)            elifOptioninch('- T','--test'):                Print "For test Option"            Else:                PrintOption,argexceptgetopt. Getopterror:Print "Getopt Error"Usage () sys.exit (1)

②optparser Module

#!/usr/bin/env python#-*-coding:utf-8-*-ImportOptparserdefMain (): 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 ()ifLen (args)! = 1: Parser.error ("incorrect number of arguments")    ifOptions.verbose:Print "Reading%s ..."%Options.filenameif __name__=="__main__": Main ()

Python Similar module use case

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.