Python parameter analysis module sys, getopt, argparse using Comparative Analysis

Xiao Bian today to share an article on Python argument parsing module sys, getopt, argparse use and comparative analysis of small series that the content very good, for everyone to share and now has a good reference value, a friend in need with little follow ed a look
some of the command-line tools can greatly simplify the maintenance costs of the code of the script, to enhance reusability, several mainstream today is provided by means of python parameter analysis tool to achieve a simple function, mainly to study and practice mainly, this is the first chapter of the new year started, it took a lot of effort to complete the writing and experiments, hoping to help friends in need, new year, I wish you all wishes come true!

Well, ado, enter the following text.

Python three built-in modules for processing command line parameters:

First: sys, easiest, can only provide a simple parameter parsing

Second: getopt, only simple processing command line parameters, a little better than the package sys

Third: argparse, making it easier to write user-friendly command line interface. It needed to define the parameters of the program process, argparse will be better resolved sys.argv. Meanwhile argparse module can automatically generate tips and information to help users enter the wrong parameters.

Into the command line parameter "-" and "-" models, as well as the use of specific methods and the similarities and differences in the following I will introduce to practical use, mainly done correctly distinguish between two kinds of command line parameters mode a. Next practice, firstly sys module, for example, to observe the process parameter analysis module practice as follows:

def sysFunc():
  '''
  基于 sys 模块的简单参数解析功能
  选项的写法要求:
  对于短格式:
        "-"号后面要紧跟一个选项字母,如果还有此选项的附加参数,可以用空格分开,也可以不分开。
        长度任意,可以用引号。
        如: -h  -ls -l s  等等
  对于长格式:
       "--"号后面要跟一个单词,如果还有些选项的附加参数,后面要紧跟"=",再加上参数。
       "="号前后不能有空格。
       如: --input=data.txt
  长格式是在Linux下引入的,许多Linux程序都支持这两种格式。在Python中提供了getopt模块很好
  的实现了对着两种用法的支持,而且使用简单。
  执行示例:
       python demo.py -d data.txt
       python demo.py --data=data.txt
  '''
  if len(sys.argv)==1: 
    print 'Nothing need to be done!'
    sys.exit()
  else:
    para_list=sys.argv
    print 'Parameters is: ',para_list
    if para_list[1].startswith('--'):
      print 'DataFile name is: ',para_list[1].split('=')[-1].strip()
      print 'Longopts,do your actions here!!!'
    elif para_list[1].startswith('-'):
      print 'DataFile name is: ',para_list[2]
      print 'Shortopts,do your actions here!!!'

And precautions on the use of the module I have explained in the above code snippet clear, I believe it is easy to understand, I have attached the execution example, let's look at the implementation of the code above results are as follows:
Here Insert Picture Description
Next we use getopt module command line parameter parsing operation, the code, we use two IP and port attributes to be passed as a parameter, the following practice:
DEF getoptFunc ():
'' '
based getopt parameter parsing module to achieve
the function getopt (args, shortopts, longopts = [])
args parameter is generally the sys.argv [. 1:]
shortopts short form (-)
longopts long format (-)
Note points:
the definition command line parameters, define with '-' parameter options, no redefinition '-' parameters
execution example:

     python demo.py -i 172.19.7.217 -p 8066 data.txt 88
      python demo.py --ip=172.19.7.217 --port=8066 data.txt 88
  '''
  if len(sys.argv)==1:
    print 'Nothing need to be done!'
    sys.exit()
  try:
    opts,args=getopt.getopt(sys.argv[1:],"hp:i:",["help","ip=","port="]) #过滤掉脚本名称
    '''
    opts是个包含元祖的列表,args是个列表,包含那些没有‘-'或‘--'的参数
    短格式 --- h 后面没有冒号:表示后面不带参数,p:和 i:后面有冒号表示后面需要参数
    长格式 --- help后面没有等号=,表示后面不带参数,其他三个有=,表示后面需要参数
    '''
    print 'opts: ',opts
    print 'args: ',args
  except getopt.GetoptError:
    print "argv error,please input"
    sys.exit()
  #打印具体参数
  map_dict={'-i':'IP','--ip':'IP','-p':'Port','--port':'Port'}
  for name,value in opts:
    if name in ("-h","--help"):
      print  """
          Usage:sys.args[0] [option]
          -h or --help:显示帮助信息
          -p or --ip: IP地址
          -p or --port: IP端口
          """
    if name in ('-i','--ip','-p','--port'):
      print '{0} is=======>{1}'.format(map_dict[name],value)

Use getopt module analyzes the command line parameters roughly divided into three steps:

1. Import getopt, sys module
2. Analysis of command line parameters
3. The processing result
Similarly, we added the detailed description and annotation module help understand the mechanism, we have attached relevant execution example, the results of running the above code obtained as shown below:
Here Insert Picture Description
Finally, we practice what argparse module, the module relative to the first two modules, the package is more advanced degree, more convenient to use what specific practices are as follows:

def argparseFunc():
  '''
  基于argparse模块实现高级的参数解析功能
  执行示例:
       python demo.py -i 172.19.7.236 -p 7077 -f -w
       python demo.py -i 172.19.7.236 -p 7077 -f -r
  '''
  parser=argparse.ArgumentParser(description="show example") #使用argparse的构造函数来创建对象
  parser.add_argument("-i","--ip",help="IP Address") #添加可解析的参数
  parser.add_argument("-p","--port",help="IP Port") #添加可解析的参数
  parser.add_argument("-f","--flag",help="Flag",action="store_true") #action=store_true的意义是如果使用了这个参数则值默认为TRUE
  exptypegroup=parser.add_mutually_exclusive_group() #添加一组互斥的选项,如上例中的-l和-r只能用一个
  exptypegroup.add_argument("-r","--read",help="Read Action",action="store_true")
  exptypegroup.add_argument("-w","--write",help="Write Action",action="store_true")
  ARGS=parser.parse_args()
  print 'ARGS:',ARGS
  if ARGS.ip:
    print "IP is: "+ARGS.ip
  if ARGS.port:
    print "Port is: "+ARGS.port
  if ARGS.flag:
    print "Flag is: "+str(ARGS.flag)
  if ARGS.read:
    print "Read action is: "+str(ARGS.read)
  if ARGS.write:
    print "Write action is: "+str(ARGS.write)

We recommend learning Python buckle qun: 913066266, look at how seniors are learning! From basic web development python script to, reptiles, django, data mining, etc. [PDF, actual source code], zero-based projects to combat data are finishing. Given to every little python partner! Every day, Daniel explain the timing Python technology, to share some of the ways to learn and need to pay attention to small details, click on Join us python learner gathering

Using this module is more widely used first constructor to create the module provides a ArgumentParser objects, such as the introduction and subsequent parameter specifies the work is carried out based on ArgumentParser objects, which, add_argument option to add a parameter object, add_mutually_exclusive_group a mutually exclusive option to add, for example: the above-described read and write operations is exclusive, the above code performs given an example, the same experiment we are still based on two parameters IP and port options, the following results shows: Here Insert Picture Description
we want to know whether a statement is really a good option is mutually exclusive parameters can not be used at the same time it? Here's a simple implementation of it on the line: Here Insert Picture Description
from the above error message we saw argparse give us feedback module is not allowed to use both read and write operations, explained mutually exclusive arguments above we declare that the normal work.

Three modules, practice three kinds of parameters can only be resolved to achieve the purpose of its preliminary understanding, and want to go back to specific projects after a certain understanding and knowledge to believe the effect will be better.

Summary
That's all for this article, I hope the content of this article has some reference value of learning for everyone to learn or work

Published 47 original articles · won praise 53 · views 50000 +

Guess you like

Origin blog.csdn.net/haoxun03/article/details/104270163