parser.add_argument:action的作用

parser.add_argument('--no-cuda', action='store_true', default=False,
                    help='Disable cuda for training')

有了 action 这一参数,就相当于把 --no-cuda 参数设成了一个“开关”。我们是不需要给这个开关传递具体的值的,只需要“拨一下”这个开关就行了。

比如上面action='store_true',就是说当拨动了这个“开关”,就将参数--no-cuda存储为True,否则参数会存储为False,因为我们设置的 default=False

实例:

# 启动action
python demo.py --no-cuda
>>> --no-cuda=True

这样就相当于我们把 --no-cuda 这个开关拨到了True

# 不启动action
python demo.py
>>> --no-cuda=False

此时没有理 --no-cuda 这个开关,那么程序就会自动给它赋值为 False

`argparse` 是 Python 标准库中用于解析命令行参数的模块。`parser.add_argument` 是 `argparse` 模块中的一个方法,用于定义命令行参数。下面是 `parser.add_argument` 的详细解释: ### `parser.add_argument` 的基本用法 ```python 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)) ``` ### 参数详解 1. **位置参数**: - `integers`:这是位置参数,意味着在命令行中必须提供这个参数。 - `nargs='+'`:表示这个参数可以有多个值,至少一个。 2. **可选参数**: - `--sum`:这是可选参数,可以通过 `--sum` 来指定。 - `dest='accumulate'`:指定解析后的参数存储在 `args` 对象的 `accumulate` 属性中。 - `action='store_const'`:表示当指定 `--sum` 时,`accumulate` 的值将被设置为 `const` 参数的值。 - `const=sum`:当指定 `--sum` 时,`accumulate` 的值将被设置为 `sum` 函数。 - `default=max`:当不指定 `--sum` 时,`accumulate` 的默认值是 `max` 函数。 3. **帮助信息**: - `help='an integer for the accumulator'`:提供帮助信息,当用户使用 `--help` 时显示。 ### 常用参数 - `type`:指定参数的类型,例如 `int`, `float`, `str` 等。 - `default`:指定参数的默认值。 - `choices`:指定参数的可选值,例如 `choices=[1, 2, 3]`。 - `required`:指定参数是否为必填项,默认为 `False`。 - `help`:提供参数的帮助信息。 ### 示例 ```python import argparse parser = argparse.ArgumentParser(description='Example of argparse') parser.add_argument('-o', '--output', type=str, default='output.txt', help='Output file name') parser.add_argument('-n', '--number', type=int, required=True, help='A required integer') parser.add_argument('--verbose', action='store_true', help='Enable verbose output') args = parser.parse_args() print(f'Output file: {args.output}') print(f'Number: {args.number}') print(f'Verbose: {args.verbose}') ``` 在这个示例中,`output` 是一个可选参数,`number` 是一个必填参数,`verbose` 是一个布尔类型的可选参数
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不吃饭就会放大招

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值