SoFunction
Updated on 2024-11-12

python similar module use case

I: threading VS Thread

As we all know, python supports multi-threading, and it is a native thread, in which threading is a wrapping of the Thread module, which can be used in more aspects, and the threading module mainly objectifies some thread operations and creates the Thread class.

There are two modes of using threads, one is to create a function to be executed by the thread, and pass this function into the Thread object for it to execute, and the other is to inherit directly from Thread, create a new class, and put the code to be executed by the thread into this new class, using the following example:

①Use Thread to implement multithreading

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import string
import threading 
import time

def threadMain(a):
  global count,mutex
  #Get the thread name
  threadname = ().getName()

  for x in xrange(0,int(a)):
    # Get the lock
    ()
    count += 1
    # Release the lock
    ()
    print threadname,x,count
    ()

def main(num):
  global count,mutex
  threads = []
  count = 1
  # Create a lock
  mutex = ()
  # Create the thread object first
  for x in xrange(0,num):
    ((target = threadMain,args=(10,)))
  for t in threads:
    ()
  for t in threads:
    ()

if __name__ == "__main__":
  num = 4
  main(num);

② Use threading to implement multithreading

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import threading
import time

class Test():
  def __init__(self,num):
    .__init__(self):
    self._run_num = num

  def run(self):
    global count,mutex
    threadName = ()
    for x in xrange(0,int(self._run_num)):
      ()
      count += 1
      ()
      print threadName,x,count
      (1)

if __name__ == "__main__":
  global count,mutex
  threads = []
  num = 4
  count = 1
  ()
  for x in xrange(o,num):
    (Test(10))
  #Starting threads
  for t in threads:
    ()
  # Wait for the child thread to finish
  for t in threads:
    ()

II: optparser vs getopt

① Use the getopt module to handle Unix mode command line options

The getopt module is used to extract command line options and arguments, i.e., command line options make the program's arguments more flexible, supporting both short and long option modes

Example: python -f "hello" -directory-prefix="/home" -t -- format 'a''b'

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

where a colon (:) after the short option name indicates that the option must have additional arguments

A long option name followed by an equal sign (=) indicates that the option must have additional arguments

Returns options and args

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

args is the command line input ('a','b') excluding useful arguments.

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import sys
import getopt

def Usage():
  print "Usage: %s [-a|-0|-c] [--help|--output] args..."%[0]

if __name__ == "__main__":
  try:
    options,args = ([1:],"ao:c",['help',"putput="]):
    print options
    print "\n"
    print args

    for option,arg in options:
      if option in ("-h","--help"):
        Usage()
        (1)
      elif option in ('-t','--test'):
        print "for test option"
      else:
        print option,arg
  except :
    print "Getopt Error"
    Usage()
    (1)

②optparser module

#!/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:
    ("incorrect number of arguments")
  if :
    print "reading %s..." % 

if __name__ == "__main__":
  main()

That's all.threading VS Thread、optparser VS getopt The intercomparison of the modules will hopefully help you to learn the modules.