Home  >  Article  >  Backend Development  >  Explanation on the usage of python argparse library

Explanation on the usage of python argparse library

巴扎黑
巴扎黑Original
2017-07-22 11:35:214022browse

argparse is a library used to parse command line options, parameters and subcommands

Source code comes from Lib/argparse.py

Main functions:

1. Make it easy for users to write command lines

2. For the parameters required by the program, argparse knows how to parse these parameters from sys.argv

3. For invalid parameters given to the program by the user, argparse can automatically generate help usage

Example 1: Write a python file or function. This python program accepts a list of integers and generates their sum or the largest number among them

$ cat prog.py
#coding:utf-8
import argparse

parser = argparse.ArgumentParser(description='some integers')

parser.add_argument('integers', metavar='N', type=int, nargs='+',help='an integer for accumulator')
parser.add_argument('--sum', dest='accumulate', action= 'store_const', const=sum, default=max,help='sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))

 Then provide parameters for this file, or provide option -h

$ python prog.py 2 3 4 5
5
$ python prog.py --sum 1 5 67
73
$ python prog.py --help
usage: prog.py [-h] [--sum] N [N ...]

some integers

positional arguments:
  N           an integer for accumulator

optional arguments:
  -h, --help  show this help message and exit
  --sum       sum the integers (default: find the max)

$ python prog.py -h
usage: prog.py [-h] [--sum] N [N ...]

some integers

positional arguments:
  N           an integer for accumulator

optional arguments:
  -h, --help  show this help message and exit
  --sum       sum the integers (default: find the max)

 When trying to pass a character into the program, an error will be reported

$ python prog.py a vb c
usage: prog.py [-h] [--sum] N [N ...]
prog.py: error: argument N: invalid int value: 'a'  

1. Create a command line option, etc. The parser

argparse.ArgumentParser creates an object that contains all the information needed to parse the command line into Python data types

argparse

Method 1: add_argument()

Use this method to fill in the object generated by ArgumentParser, which contains program parameter information. Generally speaking, these calls can tell ArgumentParser how to use the cmd command line Accepts strings

and turns them into objects. When parse_args() is called, the information will be stored and used.

For example:

parser.add_argument('integers', metavar='N', type=int, nargs='+',help='an integer for accumulator')
parser.add_argument('--sum', dest='accumulate', action= 'store_const', const=sum, default=max,help='sum the integers (default: find the max)')

  When parse_args() is called, two attributes will be returned, the integers and accumulator attributes. The integers attribute accepts a number or multiple numbers,

The accumulator attribute can accept a --sum option. When the --sum option is included in the command line, it represents the function of the system's sum() function. Without --sum The option represents the max() function function

  

 Parsing the command line parameters:

  ArgumentParser parses these parameters through the parse_args() method, which It will detect the command line and convert different parameters into the appropriate format to call different processing methods. In most cases, when parsing parameters from the command line, a simple namespace will be constructed.

In [7]: parser.parse_args(['--sum','7','10','99'])
Out[7]: Namespace(accumulate=, integers=[7, 10, 99])

 In a script, parse_args() is usually called without parameters. ArgumentParser will automatically match the parameters in the command line from sys.argv

ArgumentParser method Analysis

class argparse.ArgumentParser(prog=None, usage=None, 
description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, 
prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True)

  所有参数都需要以关键字参数来传递。

  下面是每个参数的详细解释:


    • prog => sys.argv[0] 这个脚本(程序)自身

    • usage => 来描述脚本(程序)的详细信息(默认会从创建ArgumentParser的usage读取)

    • description => 参数前显示的帮助信息(默认为None)

    • epilog => 参数后显示的帮助信息(默认为None)

    • parents => ArgumentParser方法包含的参数列表

    • formatter_class => 可定制的类来帮助输出信息

    • prefix_chars  => 可选参数的前缀(默认是'-')

    • fromfile_prefix_chars  => 前缀文件的字符(默认是None)

    • argument_default  => 全局缺省的值(默认是None)

    • conflict_handler => 解决有冲突的选项(通常不需要)

    • add_help  => 默认解析器会添加 -h 或者 --help选项(默认就含有)

    • allow_abbrev  => 允许长选项使用缩写


      下面是示例:

       prog:

        默认情况下,ArgumentParser这个对象使用sys.argv[0]决定展示帮助页面,当你在命令行 调用这个程序自身,它会显示帮助信息

      例如,假如一个叫myprog.py的脚本

    $ vim myprog.py#!/usr/local/Cellar/pyenv/versions/3.6.1/bin/python3#coding:utf-8import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument('--foo',help='foo help')
    args = parser.parse_args()
    
    
    $ python myprog.py --help
    usage: myprog.py [-h] [--foo FOO]
    
    optional arguments:  -h, --help  show this help message and exit  --foo FOO   foo help

        另一种方法,ArgumentParser 支持prog=的参数也可以达到同样效果,代码如下: 

    In [1]: import argparseIn [2]: parser = argparse.ArgumentParser(prog='myprog')
    
    In [3]: parser.print_help()
    usage: myprog [-h]
    
    optional arguments:  -h, --help  show this help message and exit#这里要注意,执行当前shell的目录里要有myprog.py这个文件

        注意这个程序名称,不管是使用sys.argv[0]还是prog=这种方法,都等价于使用%(prog)s 这个格式化方法

    In [3]: parser.add_argument('--foo',help='foo of the %(prog)s program')
    Out[3]: _StoreAction(option_strings=['--foo'], dest='foo', nargs=None, const=None, default=None, type=None, choices=None, help='foo of the %(prog)s program', metavar=None)
    
    In [4]: parser.print_help()
    usage: myprog [-h] [--foo FOO]
    
    optional arguments:  -h, --help  show this help message and exit  --foo FOO   foo of the myprog program

         或者使用usage=这种方法

    In [2]: parser = argparse.ArgumentParser(prog='PROG',usage='%(prog)s [options]')
    
    In [3]: parser.add_argument('--foo',nargs='?',help='foo help')
    Out[3]: _StoreAction(option_strings=['--foo'], dest='foo', nargs='?', const=None, default=None, type=None, choices=None, help='foo help', metavar=None)
    
    In [4]: parser.add_argument('bar',nargs='+',help='bar help')
    Out[4]: _StoreAction(option_strings=[], dest='bar', nargs='+', const=None, default=None, type=None, choices=None, help='bar help', metavar=None)
    
    In [5]: parser.print_help()
    usage: PROG [options]
    
    positional arguments:
      bar          bar help
    
    optional arguments:
      -h, --help   show this help message and exit
      --foo [FOO]  foo help

      description

         大多ArgumentParser实例在构造的时候都会使用description=这个参数,这个参数会告诉你程序是如何工作的,描述信息会显示在usage和参数之间

    In [1]: import argparse
    
    In [2]: parser = argparse.ArgumentParser(description=' example ')
    
    In [3]: parser.print_help()
    usage: ipython [-h]
    
    example
    
    optional arguments:
      -h, --help  show this help message and exit

         默认情况下,description的就会显示在这行里,可以通过formatter_class参数来修改

      

        epilog

          主要针对有一些程序会在参数描述附加程序描述, 默认是显示在optional argument描述以后

    In [4]: parser = argparse.ArgumentParser(description=' example ',epilog=' haha that is the end' )
    
    In [5]: parser.print_help()
    usage: ipython [-h]
    
    example
    
    optional arguments:
      -h, --help  show this help message and exit
    
    haha that is the end

     

          如果想修改,需要调整formatter_class argument修改    

      parents

          有时候,几个parser需要共享常见的参数。 这时候,与其重复的定义这些参数,不如使用一个包含所有参数的parser,然后再通过parents= 这个参数传递这些参数. parets= 参数可以接受一个ArgumentParser对象的列表,收集所有 位置的和可选的操作,将这些操作加入一个正在构造的ArgumentParser 中

    In [6]: parent_parser = argparse.ArgumentParser(add_help=False)
    
    In [7]: parent_parser.add_argument('--parent',type=int)
    Out[7]: _StoreAction(option_strings=['--parent'], dest='parent', nargs=None, const=None, default=None, type=, choices=None, help=None, metavar=None)
    
    In [8]: foo_parser = argparse.ArgumentParser(parents=[parent_parser])
    
    In [9]: foo_parser.add_argument('foo')
    Out[9]: _StoreAction(option_strings=[], dest='foo', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
    
    In [10]: foo_parser.parse_args(['--parent','2','xx'])
    Out[10]: Namespace(foo='xx', parent=2)
    
    In [11]: bar_parser = argparse.ArgumentParser(parents=[parent_parser])
    
    In [12]: bar_parser.add_argument('--bar')
    Out[12]: _StoreAction(option_strings=['--bar'], dest='bar', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
    
    In [13]: bar_parser.parse_args(['--bar','yy'])
    Out[13]: Namespace(bar='yy', parent=None)
    In [14]: parent_parser.print_help()
    usage: ipython [--parent PARENT]
    
    optional arguments:
      --parent PARENT
    
    In [15]: foo_parser.print_help()
    usage: ipython [-h] [--parent PARENT] foo
    
    positional arguments:
      foo
    
    optional arguments:
      -h, --help       show this help message and exit
      --parent PARENT
    
    In [16]: bar_parser.print_help()
    usage: ipython [-h] [--parent PARENT] [--bar BAR]
    
    optional arguments:
      -h, --help       show this help message and exit
      --parent PARENT
      --bar BAR

          这里,我定义了一个父类parent_parser 以及两个子类foo_parser 和bar_parser,这两个子类明确指定了parents=[parent_parser]

            注意,这里很多父类在初始化的时候都指定了 add_help=False, 如果不指定的话,当使用-h,或者--help的时候会看到两个选项并且引发error 

          还要注意,父类parser必须完全初始化才能通过 parents=传给子类,如果你没有这样做的话,后面对于父类parser做的修改都不会反应在子类parser中

         

      formatter_class

        ArgumentParser对象允许一个可以定制化的类来被格式化, 目前,支持这4个类   

    •       class argparse.RawDescriptionHelpFormatter

    •       class argparse.RawTextHelpFormatter

    •       class argparse.ArgumentDefaultsHelpFormatter

    •       class argparse.MetavarTypeHelpFormatter

        其中,RawDescriptionHelpFormatter and RawTextHelpFormatter 这两个类会对文本显示格式有更多的限定,在默认情况下,ArgumentParser会在显示命令行帮助信息中对description= 和 epilog= 自动换行。

    In [1]: import argparse
    
    In [2]: parser = argparse.ArgumentParser(
       ...:     prog='PROG',
       ...:     description=''' that
       ...:         is
       ...:         a description ''',
       ...:     epilog=''' that
       ...:         is
       ...:         a epilog ''')
       ...:
    
    In [3]: parser.print_help()
    usage: PROG [-h]
    
    that is a description     #可以看到自动换行
    
    optional arguments:
      -h, --help  show this help message and exit
    
    that is a epilog        #可以看到自动换行

        通过传递formatter_class= 说明 description= 和 epilog= 已经被格式化并且不应该换行了

    In [4]: parser = argparse.ArgumentParser(prog='hey!',
       ...:         formatter_class=argparse.RawDescriptionHelpFormatter,
       ...:         description=''' let
       ...:             us
       ...:             do it''')
       ...:
    
    In [5]: parser.print_help()
    usage: hey! [-h]
    
     let
                us
                do it
    
    optional arguments:
      -h, --help  show this help message and exit

        RawTextHelpFormatter 为各种帮助信息保留了空白,包括参数描述信息       

        ArgumentDefaultsHelpFormatter这个类会自动为每个参数的帮助信息添加默认值

    In [9]: parser = argparse.ArgumentParser(
       ...:     prog='hey',
       ...:     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
       ...:
    
    In [10]: parser.add_argument('--foo',type=int,default=42,help='foo!')
    Out[10]: _StoreAction(option_strings=['--foo'], dest='foo', nargs=None, const=None, default=42, type=, choices=None, help='foo!', metavar=None)
    
    In [11]: parser.add_argument('bar',nargs='*',default=[1,2,3,4],help='bar!')
    Out[11]: _StoreAction(option_strings=[], dest='bar', nargs='*', const=None, default=[1, 2, 3, 4], type=None, choices=None, help='bar!', metavar=None)
    
    In [12]: parser.print_help()
    usage: hey [-h] [--foo FOO] [bar [bar ...]]
    
    positional arguments:
      bar         bar! (default: [1, 2, 3, 4])
    
    optional arguments:
      -h, --help  show this help message and exit
      --foo FOO   foo! (default: 42)

        MetavarTypeHelpFormatter 为每个参数以 参数的类型作为显示,摒弃了常规使用dest的模式

    In [13]: parser = argparse.ArgumentParser(
        ...:     prog='HELP',
        ...:     formatter_class=argparse.MetavarTypeHelpFormatter)
        ...:
    
    In [14]: parser.add_argument('--foo',type=int)
    Out[14]: _StoreAction(option_strings=['--foo'], dest='foo', nargs=None, const=None, default=None, type=fef5044cb148d720181de1eedd501dcf, choices=None, help=None, metavar=None)
    
    In [15]: parser.add_argument('bar',type=float)
    Out[15]: _StoreAction(option_strings=[], dest='bar', nargs=None, const=None, default=None, type=ee7711ebb77ecaed27f55b7992b532fc, choices=None, help=None, metavar=None)
    
    In [16]: parser.print_help()
    usage: HELP [-h] [--foo int] float
    
    positional arguments:
      float
    
    optional arguments:  -h, --help  show this help message and exit  --foo int 
    prefix_chars
        许多命令行选项都用"-" 当前缀,比如 -h 或者 --help,Parser可以通过prefix_chars来设置不同的前缀符号
        你可以用"+" 或者使用"/"
        
     1 In [1]: import argparse 2  3 In [2]: parser = argparse.ArgumentParser(prog='PROG',prefix_chars="-+") 4  5 In [3]: parser.add_argument('+f') 6 Out[3]: _StoreAction(option_strings=['+f'], dest='f', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None) 7  8 In [4]: parser.add_argument('++bar') 9 Out[4]: _StoreAction(option_strings=['++bar'], dest='bar', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)10 In [5]: parser.print_help()11 12 13 14 In [5]: parser.print_help()15 usage: PROG [-h] [+f F] [++bar BAR]16 17 optional arguments:18   -h, --help  show this help message and exit19   +f F20   ++bar BAR

        prefix_chars= 默认的参数是'-'.

      fromfile_prefix_chars

        有的情况下,当处理特别长的参数列表,将这个参数列表保存在文件中,也可以支持

          这个需要在构建ArgumentParser的时候加入 fromfile_prefix_chars= 选项

     

      argument_default

        一般来说,参数都通过add_argument()来指定或者通过调用setdefaults()传递name-value的方法
        有时候,需要为参数指定一个单独的默认值,通过给ArgumentParser指定argument_default关键字参数即可
        比如,可以通过argument_default=SUPPERSS来阻止在parse_args()中全局创建属性
      
     conflict_handler

        ArgumentParser 对象不允许使用同一个选项字串来表示两个操作,若尝试在 已经使用的选项新建一个参数的话,就说引发异常
    1 In [7]: parser = argparse.ArgumentParser(prog='PROG')2 3 In [8]: parser.add_argument('-f','--foo',help='old foo help')4 Out[8]: _StoreAction(option_strings=['-f', '--foo'], dest='foo', nargs=None, const=None, default=None, type=None, choices=None, help='old foo help', metavar=None)5 6 In [9]: parser.add_argument('--foo',help='new foo help')7 ---------------------------------------------------------------------------8 ArgumentError                             Traceback (most recent call last)

          可以使用选项 conflict_handler='resolve'

     1 In [10]: parser = argparse.ArgumentParser(prog='PROG',conflict_handler='resolve' 2     ...: ) 3  4 In [11]: parser.add_argument('-f','--foo',help='old foo help') 5 Out[11]: _StoreAction(option_strings=['-f', '--foo'], dest='foo', nargs=None, const=None, default=None, type=None, choices=None, help='old foo help', metavar=None) 6  7 In [12]: parser.add_argument('--foo',help='new foo help') 8 Out[12]: _StoreAction(option_strings=['--foo'], dest='foo', nargs=None, const=None, default=None, type=None, choices=None, help='new foo help', metavar=None) 9 10 In [13]: parser.print_help()11 usage: PROG [-h] [-f FOO] [--foo FOO]12 13 optional arguments:14   -h, --help  show this help message and exit15   -f FOO      old foo help16   --foo FOO   new foo help

          ArgumentParser 仅移除这个动作,假如所有的选项字符串都被覆盖了

      add_help
          默认情况下,ArgumentParser对象在创建选项会带着parser的帮助信息
       
    下一篇介绍ArgumentParser
    The add_argument() 方法

      

      

     

    The above is the detailed content of Explanation on the usage of python argparse library. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn