Explanation on the usage of python argparse library

巴扎黑
Release: 2017-07-22 11:35:21
Original
4155 people have browsed it

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
Copy after login
#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))
Copy after login

 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
Copy after login
$ 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)
Copy after login

 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'  
Copy after login

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)')
Copy after login

  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=<built-in function sum>, integers=[7, 10, 99])
Copy after login

 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=&#39;-&#39;, fromfile_prefix_chars=None, argument_default=None, conflict_handler=&#39;error&#39;, add_help=True, allow_abbrev=True)
Copy after login

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

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


    • 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:

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

      例如,假如一个叫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(&#39;--foo&#39;,help=&#39;foo help&#39;)
    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
    Copy after login

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

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

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

    In [3]: parser.add_argument(&#39;--foo&#39;,help=&#39;foo of the %(prog)s program&#39;)
    Out[3]: _StoreAction(option_strings=[&#39;--foo&#39;], dest=&#39;foo&#39;, nargs=None, const=None, default=None, type=None, choices=None, help=&#39;foo of the %(prog)s program&#39;, 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
    Copy after login

         或者使用usage=这种方法

    In [2]: parser = argparse.ArgumentParser(prog=&#39;PROG&#39;,usage=&#39;%(prog)s [options]&#39;)
    
    In [3]: parser.add_argument(&#39;--foo&#39;,nargs=&#39;?&#39;,help=&#39;foo help&#39;)
    Out[3]: _StoreAction(option_strings=[&#39;--foo&#39;], dest=&#39;foo&#39;, nargs=&#39;?&#39;, const=None, default=None, type=None, choices=None, help=&#39;foo help&#39;, metavar=None)
    
    In [4]: parser.add_argument(&#39;bar&#39;,nargs=&#39;+&#39;,help=&#39;bar help&#39;)
    Out[4]: _StoreAction(option_strings=[], dest=&#39;bar&#39;, nargs=&#39;+&#39;, const=None, default=None, type=None, choices=None, help=&#39;bar help&#39;, 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
    Copy after login

      description

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

    In [1]: import argparse
    
    In [2]: parser = argparse.ArgumentParser(description=&#39; example &#39;)
    
    In [3]: parser.print_help()
    usage: ipython [-h]
    
    example
    
    optional arguments:
      -h, --help  show this help message and exit
    Copy after login

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

      

     epilog

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

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

          如果想修改,需要调整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(&#39;--parent&#39;,type=int)
    Out[7]: _StoreAction(option_strings=[&#39;--parent&#39;], dest=&#39;parent&#39;, nargs=None, const=None, default=None, type=<class &#39;int&#39;>, choices=None, help=None, metavar=None)
    
    In [8]: foo_parser = argparse.ArgumentParser(parents=[parent_parser])
    
    In [9]: foo_parser.add_argument(&#39;foo&#39;)
    Out[9]: _StoreAction(option_strings=[], dest=&#39;foo&#39;, nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
    
    In [10]: foo_parser.parse_args([&#39;--parent&#39;,&#39;2&#39;,&#39;xx&#39;])
    Out[10]: Namespace(foo=&#39;xx&#39;, parent=2)
    
    In [11]: bar_parser = argparse.ArgumentParser(parents=[parent_parser])
    
    In [12]: bar_parser.add_argument(&#39;--bar&#39;)
    Out[12]: _StoreAction(option_strings=[&#39;--bar&#39;], dest=&#39;bar&#39;, nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
    
    In [13]: bar_parser.parse_args([&#39;--bar&#39;,&#39;yy&#39;])
    Out[13]: Namespace(bar=&#39;yy&#39;, parent=None)
    Copy after login
    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
    Copy after login

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

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

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

     

      formatter_class

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

    •       class <span class="highlighted">argparse.</span>RawDescriptionHelpFormatter

    •       class <span class="highlighted">argparse.</span>RawTextHelpFormatter

    •       class <span class="highlighted">argparse.</span>ArgumentDefaultsHelpFormatter

    •       class <span class="highlighted">argparse.</span>MetavarTypeHelpFormatter

        <span style="font-size: 12px">其中,<code class="xref py py-class docutils literal"><span class="pre">RawDescriptionHelpFormatter</span> and <span class="pre">RawTextHelpFormatter</span> 这两个类会对文本显示格式有更多的限定,在默认情况下,ArgumentParser会在显示命令行帮助信息中对description= 和 epilog= 自动换行。

    In [1]: import argparse
    
    In [2]: parser = argparse.ArgumentParser(
       ...:     prog=&#39;PROG&#39;,
       ...:     description=&#39;&#39;&#39; that
       ...:         is
       ...:         a description &#39;&#39;&#39;,
       ...:     epilog=&#39;&#39;&#39; that
       ...:         is
       ...:         a epilog &#39;&#39;&#39;)
       ...:
    
    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        #可以看到自动换行
    Copy after login

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

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

        <span style="font-size: 12px"><code class="xref py py-class docutils literal"><span class="pre">RawTextHelpFormatter 为各种帮助信息保留了空白,包括参数描述信息</span>       

        <span class="pre">ArgumentDefaultsHelpFormatter这个类会自动为每个参数的帮助信息添加默认值</span>

    In [9]: parser = argparse.ArgumentParser(
       ...:     prog=&#39;hey&#39;,
       ...:     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
       ...:
    
    In [10]: parser.add_argument(&#39;--foo&#39;,type=int,default=42,help=&#39;foo!&#39;)
    Out[10]: _StoreAction(option_strings=[&#39;--foo&#39;], dest=&#39;foo&#39;, nargs=None, const=None, default=42, type=<class &#39;int&#39;>, choices=None, help=&#39;foo!&#39;, metavar=None)
    
    In [11]: parser.add_argument(&#39;bar&#39;,nargs=&#39;*&#39;,default=[1,2,3,4],help=&#39;bar!&#39;)
    Out[11]: _StoreAction(option_strings=[], dest=&#39;bar&#39;, nargs=&#39;*&#39;, const=None, default=[1, 2, 3, 4], type=None, choices=None, help=&#39;bar!&#39;, 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)
    Copy after login

        <span class="pre">MetavarTypeHelpFormatter 为每个参数以 参数的类型作为显示,摒弃了常规使用dest的模式</span>

    In [13]: parser = argparse.ArgumentParser(
        ...:     prog=&#39;HELP&#39;,
        ...:     formatter_class=argparse.MetavarTypeHelpFormatter)
        ...:
    
    In [14]: parser.add_argument(&#39;--foo&#39;,type=int)
    Out[14]: _StoreAction(option_strings=[&#39;--foo&#39;], dest=&#39;foo&#39;, nargs=None, const=None, default=None, type=<class &#39;int&#39;>, choices=None, help=None, metavar=None)
    
    In [15]: parser.add_argument(&#39;bar&#39;,type=float)
    Out[15]: _StoreAction(option_strings=[], dest=&#39;bar&#39;, nargs=None, const=None, default=None, type=<class &#39;float&#39;>, 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 
    Copy after login
    <span class="n">prefix_chars<br/>    许多命令行选项都用"-" 当前缀,比如 -h 或者 --help,Parser可以通过prefix_chars来设置不同的前缀符号<br/>    你可以用"+" 或者使用"/"<br/>    </span>
    Copy after login
     1 In [1]: import argparse 2  3 In [2]: parser = argparse.ArgumentParser(prog=&#39;PROG&#39;,prefix_chars="-+") 4  5 In [3]: parser.add_argument(&#39;+f&#39;) 6 Out[3]: _StoreAction(option_strings=[&#39;+f&#39;], dest=&#39;f&#39;, nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None) 7  8 In [4]: parser.add_argument(&#39;++bar&#39;) 9 Out[4]: _StoreAction(option_strings=[&#39;++bar&#39;], dest=&#39;bar&#39;, 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
    Copy after login

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

      fromfile_prefix_chars

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

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

      argument_default

    <span class="n">    一般来说,参数都通过add_argument()来指定或者通过调用setdefaults()传递name-value的方法<br/>    有时候,需要为参数指定一个单独的默认值,通过给ArgumentParser指定argument_default关键字参数即可<br/>    比如,可以通过argument_default=SUPPERSS来阻止在parse_args()中全局创建属性<br/>  <br/> conflict_handler<br/><br/>    ArgumentParser 对象不允许使用同一个选项字串来表示两个操作,若尝试在 已经使用的选项新建一个参数的话,就说引发异常<br/></span>
    Copy after login
    1 In [7]: parser = argparse.ArgumentParser(prog=&#39;PROG&#39;)2 3 In [8]: parser.add_argument(&#39;-f&#39;,&#39;--foo&#39;,help=&#39;old foo help&#39;)4 Out[8]: _StoreAction(option_strings=[&#39;-f&#39;, &#39;--foo&#39;], dest=&#39;foo&#39;, nargs=None, const=None, default=None, type=None, choices=None, help=&#39;old foo help&#39;, metavar=None)5 6 In [9]: parser.add_argument(&#39;--foo&#39;,help=&#39;new foo help&#39;)7 ---------------------------------------------------------------------------8 ArgumentError                             Traceback (most recent call last)
    Copy after login

          可以使用选项 conflict_handler='resolve'

     1 In [10]: parser = argparse.ArgumentParser(prog=&#39;PROG&#39;,conflict_handler=&#39;resolve&#39; 2     ...: ) 3  4 In [11]: parser.add_argument(&#39;-f&#39;,&#39;--foo&#39;,help=&#39;old foo help&#39;) 5 Out[11]: _StoreAction(option_strings=[&#39;-f&#39;, &#39;--foo&#39;], dest=&#39;foo&#39;, nargs=None, const=None, default=None, type=None, choices=None, help=&#39;old foo help&#39;, metavar=None) 6  7 In [12]: parser.add_argument(&#39;--foo&#39;,help=&#39;new foo help&#39;) 8 Out[12]: _StoreAction(option_strings=[&#39;--foo&#39;], dest=&#39;foo&#39;, nargs=None, const=None, default=None, type=None, choices=None, help=&#39;new foo help&#39;, 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
    Copy after login

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

    <span class="n">  add_help<br/>      默认情况下,ArgumentParser对象在创建选项会带着parser的帮助信息<br/>   <br/><span style="font-size: 18px">下一篇介绍ArgumentParser<br/>The add_argument() 方法</span><br/>  <br/></span>
    Copy after login

      

     

    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!

    Related labels:
    source:php.cn
    Statement of this Website
    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
    Popular Recommendations
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template