python argparse action,Python argparse:metavar和action = store_true一起

I'm using argparse module in Python to parse parameters typed in a command line interface. I have the following add_argument call to a subparser object:

submit_parser.add_argument('-pv','--provision',metavar='PROVISION', dest='PROVISION',

help='provision system',

action='store_true', default=False, required=False)

I get this error:

Traceback (most recent call last):

File "./scripts/tp4", line 94, in

main()

File "./scripts/tp4", line 74, in main

modloader.loadModules(sub_parsers)

File "/usr/lib/python2.6/site-packages/tp4/cli/Moduleloader.py", line 66, in loadModules

registered_modules[module_name].setSubparserArgs(module_sub_parser)

File "/usr/lib/python2.6/site-packages/tp4/cli/modules/AutotestModule.py", line 135, in setSubparserArgs

action='store_true', default=False, required=False)

File "/usr/share/tp4/cli/zip/argparse.zip/argparse.py", line 1302, in add_argument

TypeError: __init__() got an unexpected keyword argument 'metavar'

If I remove action or metavar parameters, it works. Why both can't be together? There is nothing about this restriction in argparse documentation at http://docs.python.org/dev/library/argparse.html.

Thanks in advance for any help

解决方案

A metavar only makes sense for positional arguments (think filenames at the end of the command line) or for when an argument takes arguments of its own (like --input-files foo.txt bar.txt).

Your --provision argument is a flag because you set the action to store_true. It doesn't take any arguments (i.e., nargs isn't set). As such, it doesn't make sense to have a metavar.

When ArgumentParser generates help messages, it need some way to refer to each expected argument. By default, ArgumentParser objects use the dest value as the “name” of each object. By default, for positional argument actions, the dest value is used directly, and for optional argument actions, the dest value is uppercased. So, a single positional argument with dest='bar' will be referred to as bar. A single optional argument --foo that should be followed by a single command-line argument will be referred to as FOO.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值