importargparseparser=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()printargs.accumulate(args.integers)
$ python prog.py -h
usage: prog.py [-h] [--sum] N [N ...]
Process some integers.
positional arguments:
N an integer for the accumulator
optional arguments:
-h, --help show this help message and exit
--sum sum the integers (default: find the max)
>>> 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)')
$ python myprogram.py --help
usage: myprogram.py [-h] [--foo FOO]
optional arguments:
-h, --help show this help message and exit
--foo FOO foo help
$ cd ..
$ python subdir\myprogram.py --help
usage: myprogram.py [-h] [--foo FOO]
optional arguments:
-h, --help show this help message and exit
--foo FOO foo help
>>> parser=argparse.ArgumentParser(prog='myprogram')>>> parser.print_help()usage: myprogram [-h]optional arguments: -h, --help show this help message and exit
>>> parser=argparse.ArgumentParser(prog='myprogram')>>> parser.add_argument('--foo',help='foo of the %(prog)s program')>>> parser.print_help()usage: myprogram [-h] [--foo FOO]optional arguments: -h, --help show this help message and exit --foo FOO foo of the myprogram program
>>> parser=argparse.ArgumentParser(prog='PROG')>>> parser.add_argument('--foo',nargs='?',help='foo help')>>> parser.add_argument('bar',nargs='+',help='bar help')>>> parser.print_help()usage: PROG [-h] [--foo [FOO]] bar [bar ...]positional arguments: bar bar helpoptional arguments: -h, --help show this help message and exit --foo [FOO] foo help
可以通过关键字参数usage=覆盖默认的信息:
>>>
>>> parser=argparse.ArgumentParser(prog='PROG',usage='%(prog)s [options]')>>> parser.add_argument('--foo',nargs='?',help='foo help')>>> parser.add_argument('bar',nargs='+',help='bar help')>>> parser.print_help()usage: PROG [options]positional arguments: bar bar helpoptional arguments: -h, --help show this help message and exit --foo [FOO] foo help
>>> parser=argparse.ArgumentParser(description='A foo that bars')>>> parser.print_help()usage: argparse.py [-h]A foo that barsoptional arguments: -h, --help show this help message and exit
>>> parser=argparse.ArgumentParser(... description='A foo that bars',... epilog="And that's how you'd foo a bar")>>> parser.print_help()usage: argparse.py [-h]A foo that barsoptional arguments: -h, --help show this help message and exitAnd that's how you'd foo a bar
>>> parser=argparse.ArgumentParser(... prog='PROG',... description='''this description... was indented weird... but that is okay''',... epilog='''... likewise for this epilog whose whitespace will... be cleaned up and whose words will be wrapped... across a couple lines''')>>> parser.print_help()usage: PROG [-h]this description was indented weird but that is okayoptional arguments: -h, --help show this help message and exitlikewise for this epilog whose whitespace will be cleaned up and whose wordswill be wrapped across a couple lines
>>> parser=argparse.ArgumentParser(... prog='PROG',... formatter_class=argparse.RawDescriptionHelpFormatter,... description=textwrap.dedent('''\... Please do not mess up this text!... --------------------------------... I have indented it... exactly the way... I want it... '''))>>> parser.print_help()usage: PROG [-h]Please do not mess up this text!-------------------------------- I have indented it exactly the way I want itoptional arguments: -h, --help show this help message and exit
>>> parser=argparse.ArgumentParser(prog='PROG',conflict_handler='resolve')>>> parser.add_argument('-f','--foo',help='old foo help')>>> parser.add_argument('--foo',help='new foo help')>>> parser.print_help()usage: PROG [-h] [-f FOO] [--foo FOO]optional arguments: -h, --help show this help message and exit -f FOO old foo help --foo FOO new foo help
>>> parser=argparse.ArgumentParser(prog='PROG',prefix_chars='+/')>>> parser.print_help()usage: PROG [+h]optional arguments: +h, ++help show this help message and exit
15.4.3. add_argument() 方法
ArgumentParser.add_argument
(
name or flags...[,
action][,
nargs][,
const][,
default][,
type][,
choices][,
required][,
help][,
metavar][,
dest]
)
>>> parser=argparse.ArgumentParser()>>> parser.add_argument('bar',type=argparse.FileType('w'))>>> parser.parse_args(['out.txt'])Namespace(bar=<open file 'out.txt', mode 'w' at 0x...>)
type=可以接受任何可调用类型,只要该类型以一个字符串为参数并且返回转换后的类型:
>>>
>>> defperfect_square(string):... value=int(string)... sqrt=math.sqrt(value)... ifsqrt!=int(sqrt):... msg="%r is not a perfect square"%string... raiseargparse.ArgumentTypeError(msg)... returnvalue...>>> parser=argparse.ArgumentParser(prog='PROG')>>> parser.add_argument('foo',type=perfect_square)>>> parser.parse_args('9'.split())Namespace(foo=9)>>> parser.parse_args('7'.split())usage: PROG [-h] fooPROG: error: argument foo: '7' is not a perfect square
help的值是一个包含参数简短描述的字符串。当用户要求帮助时(通常通过使用-h或者--help at the command line),这些help的描述将随每个参数一起显示出来:
>>>
>>> parser=argparse.ArgumentParser(prog='frobble')>>> parser.add_argument('--foo',action='store_true',... help='foo the bars before frobbling')>>> parser.add_argument('bar',nargs='+',... help='one of the bars to be frobbled')>>> parser.parse_args('-h'.split())usage: frobble [-h] [--foo] bar [bar ...]positional arguments: bar one of the bars to be frobbledoptional arguments: -h, --help show this help message and exit --foo foo the bars before frobbling
>>> parser=argparse.ArgumentParser(prog='frobble')>>> parser.add_argument('bar',nargs='?',type=int,default=42,... help='the bar to %(prog)s (default: %(default)s)')>>> parser.print_help()usage: frobble [-h] [bar]positional arguments: bar the bar to frobble (default: 42)optional arguments: -h, --help show this help message and exit
>>> parser=argparse.ArgumentParser(prog='frobble')>>> parser.add_argument('--foo',help=argparse.SUPPRESS)>>> parser.print_help()usage: frobble [-h]optional arguments: -h, --help show this help message and exit
>>> 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
>>> parser=argparse.ArgumentParser(prog='PROG')>>> parser.add_argument('-x')>>> parser.add_argument('foo',nargs='?')>>> # no negative number options, so -1 is a positional argument>>> parser.parse_args(['-x','-1'])Namespace(foo=None, x='-1')>>> # no negative number options, so -1 and -5 are positional arguments>>> parser.parse_args(['-x','-1','-5'])Namespace(foo='-5', x='-1')>>> parser=argparse.ArgumentParser(prog='PROG')>>> parser.add_argument('-1',dest='one')>>> parser.add_argument('foo',nargs='?')>>> # negative number options present, so -1 is an option>>> parser.parse_args(['-1','X'])Namespace(foo=None, one='X')>>> # negative number options present, so -2 is an option>>> parser.parse_args(['-2'])usage: PROG [-h] [-1 ONE] [foo]PROG: error: no such option: -2>>> # negative number options present, so both -1s are options>>> parser.parse_args(['-1','-1'])usage: PROG [-h] [-1 ONE] [foo]PROG: error: argument -1: expected one argument
>>> # create the top-level parser>>> parser=argparse.ArgumentParser(prog='PROG')>>> parser.add_argument('--foo',action='store_true',help='foo help')>>> subparsers=parser.add_subparsers(help='sub-command help')>>>>>> # create the parser for the "a" command>>> parser_a=subparsers.add_parser('a',help='a help')>>> parser_a.add_argument('bar',type=int,help='bar help')>>>>>> # create the parser for the "b" command>>> parser_b=subparsers.add_parser('b',help='b help')>>> parser_b.add_argument('--baz',choices='XYZ',help='baz help')>>>>>> # parse some argument lists>>> parser.parse_args(['a','12'])Namespace(bar=12, foo=False)>>> parser.parse_args(['--foo','b','--baz','Z'])Namespace(baz='Z', foo=True)
>>> parser.parse_args(['--help'])usage: PROG [-h] [--foo] {a,b} ...positional arguments: {a,b} sub-command help a a help b b helpoptional arguments: -h, --help show this help message and exit --foo foo help>>> parser.parse_args(['a','--help'])usage: PROG a [-h] barpositional arguments: bar bar helpoptional arguments: -h, --help show this help message and exit>>> parser.parse_args(['b','--help'])usage: PROG b [-h] [--baz {X,Y,Z}]optional arguments: -h, --help show this help message and exit --baz {X,Y,Z} baz help
>>> # sub-command functions>>> deffoo(args):... printargs.x*args.y...>>> defbar(args):... print'((%s))'%args.z...>>> # create the top-level parser>>> parser=argparse.ArgumentParser()>>> subparsers=parser.add_subparsers()>>>>>> # create the parser for the "foo" command>>> parser_foo=subparsers.add_parser('foo')>>> parser_foo.add_argument('-x',type=int,default=1)>>> parser_foo.add_argument('y',type=float)>>> parser_foo.set_defaults(func=foo)>>>>>> # create the parser for the "bar" command>>> parser_bar=subparsers.add_parser('bar')>>> parser_bar.add_argument('z')>>> parser_bar.set_defaults(func=bar)>>>>>> # parse the args and call whatever function was selected>>> args=parser.parse_args('foo 1 -x 2'.split())>>> args.func(args)2.0>>>>>> # parse the args and call whatever function was selected>>> args=parser.parse_args('bar XYZYX'.split())>>> args.func(args)((XYZYX))
>>> parser=argparse.ArgumentParser(prog='PROG',add_help=False)>>> group=parser.add_argument_group('group')>>> group.add_argument('--foo',help='foo help')>>> group.add_argument('bar',help='bar help')>>> parser.print_help()usage: PROG [--foo FOO] bargroup: bar bar help --foo FOO foo help
>>> parser=argparse.ArgumentParser(prog='PROG')>>> group=parser.add_mutually_exclusive_group(required=True)>>> group.add_argument('--foo',action='store_true')>>> group.add_argument('--bar',action='store_false')>>> parser.parse_args([])usage: PROG [-h] (--foo | --bar)PROG: error: one of the arguments --foo --bar is required