argparse——python命令行解析

在編寫控制檯程序時,經常被命令行解析困擾,getopt用的也不舒服,最後發現argparse挺好的。

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
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)')

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

詳細說說add_argument函數:

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:

  • name or flags - Either a name or a list of option strings, e.g. foo or -f, –foo.
  • action - The basic type of action to be taken when this argument is encountered at the command line.[store,store_const,store_true,store_false,append,append_const,count,help,version]
  • nargs - The number of command-line arguments that should be consumed. 一個選項後跟幾個參數,很棒吧
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs='2')
>>> parser.add_argument('--bar', nargs='2')
>>> parser.add_argument('baz', nargs='2')
>>> parser.parse_args('a b --foo x y --bar 1 2'.split())
Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
  • const - A constant value required by some action and nargs selections.
  • default - The value produced if the argument is absent from the command line.
  • type - The type to which the command-line argument should be converted.
  • choices - A container of the allowable values for the argument.
  • 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. 顯示此選項的幫助信息是什麼,當多個參數時,使用metavar=(‘file1’,’file2’),元組形式。
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-x', nargs=2)
>>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
>>> parser.print_help()
usage: PROG [-h] [-x X X] [--foo bar baz]

optional arguments:
 -h, --help     show this help message and exit
 -x X X
 --foo bar baz
  • dest - The name of the attribute to be added to the object returned by parse_args(). 將參數內容存放到哪個變量,當多個時保存成列表。
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', dest='bar')
>>> parser.parse_args('--foo XXX'.split())
Namespace(bar='XXX')
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章