python argparse bool_如何使用Python Argparse生成所需参数的短版本和长版本?

对于标志(以-或--开头的选项),传入带有标志的选项。可以指定多个选项:parser.add_argument('-i', '--inputdir', help="Specify the input directory")The add_argument() method must know whether an optional argument, like -f or --foo, or a positional argument, like a list of filenames, is expected. The first arguments passed to add_argument() must therefore be either a series of flags, or a simple argument name.

演示:>>> import argparse

>>> parser = argparse.ArgumentParser()

>>> parser.add_argument('-i', '--inputdir', help="Specify the input directory")

_StoreAction(option_strings=['-i', '--inputdir'], dest='inputdir', nargs=None, const=None, default=None, type=None, choices=None, help='Specify the input directory', metavar=None)

>>> parser.print_help()

usage: [-h] [-i INPUTDIR]

optional arguments:

-h, --help show this help message and exit

-i INPUTDIR, --inputdir INPUTDIR

Specify the input directory

>>> parser.parse_args(['-i', '/some/dir'])

Namespace(inputdir='/some/dir')

>>> parser.parse_args(['--inputdir', '/some/dir'])

Namespace(inputdir='/some/dir')

但是,required参数的第一个元素只是一个占位符。-和--选项始终是可选的(这是命令行约定),所需的参数从不使用此类开关指定。相反,命令行帮助将根据传递给add_argument()的第一个参数(传递时不带破折号)显示在何处放置带有占位符的必需参数。

如果您必须打破这个约定,并使用以-或--开头的参数(无论如何都是必需的),那么您必须自己检查:args = parser.parse_args()

if not args.inputdir:

parser.error('Please specify an inputdir with the -i or --inputdir option')

这里^{} method将打印帮助信息和错误消息,然后退出。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值