栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python parser参数nargs=‘+‘涵义

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python parser参数nargs=‘+‘涵义

1.nargs=‘+’
    group_gpus.add_argument(
        '--gpu-ids',
        # type=int,
        default=[2],
        nargs='+',
        help='ids of gpus to use '
        '(only applicable to non-distributed training)')

表示设置参数个数
nargs=‘*’: 表示参数可设置零个或多个
nargs=‘+’:表示参数可设置一个或多个
nargs=‘?’: 表示参数可设置零个或一个

2. add_mutually_exclusive_group
group_gpus = parser.add_mutually_exclusive_group()

创建一个互斥组。 argparse 将会确保互斥组中只有一个参数在命令行中可用。

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> group = parser.add_mutually_exclusive_group()
>>> group.add_argument('--foo', action='store_true')
>>> group.add_argument('--bar', action='store_false')
>>> parser.parse_args(['--foo'])
Namespace(bar=True, foo=True)
>>> parser.parse_args(['--bar'])
Namespace(bar=False, foo=False)
>>> parser.parse_args(['--foo', '--bar'])
usage: PROG [-h] [--foo | --bar]
PROG: error: argument --bar: not allowed with argument --foo

add_mutually_exclusive_group() 方法也接受一个 required 参数,表示在互斥组中至少有一个参数是需要的:

>>> 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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/960835.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号