學習python argparse庫

1. 生成parser

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

2. 添加參數設置

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

3. 解析參數

args = parser.parse_args()
# args is the populated namespace.
print(args.accumulate(args.integers))

注意: 參考官網html

  • action 可取'store'(默認), 'store_const' , 'store_true' and 'store_false', 'append', 'append_const', 'count', 'help', 'version'
  • nargs 可取N (an integer), '?', '+', '*', argparse.REMAINDER
  • type 指定對應參數值的類型
  • choices 指定可供選擇的範圍
  • required 指定是否必須提供
  • metavar 用於參數提示
  • dest 指定命名空間中參數對應的key

即:
python

ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
Define how a single command-line argument should be parsed. Each parameter has its own more detailed description below, but in short they are:app

name or flags - Either a name or a list of option strings, e.g. foo or -f, --foo.ui

action - The basic type of action to be taken when this argument is encountered at the command line.this

nargs - The number of command-line arguments that should be consumed.spa

const - A constant value required by some action and nargs selections.code

default - The value produced if the argument is absent from the command line.htm

type - The type to which the command-line argument should be converted.ip

choices - A container of the allowable values for the argument.get

required - Whether or not the command-line option may be omitted (optionals only).

help - A brief description of what the argument does.

metavar - A name for the argument in usage messages.

dest - The name of the attribute to be added to the object returned by parse_args().

相關文章
相關標籤/搜索