草庐IT

Python argparse : default value or specified value

coder 2023-04-29 原文

我希望有一个可选参数,如果仅存在未指定值的标志,它将默认为一个值,但如果用户指定一个值,则存储用户指定的值而不是默认值。是否已有可用的操作?

一个例子:

python script.py --example
# args.example would equal a default value of 1
python script.py --example 2
# args.example would equal a default value of 2

我可以创建一个 Action ,但想看看是否有现有的方法可以做到这一点。

最佳答案

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--example', nargs='?', const=1, type=int)
args = parser.parse_args()
print(args)

% test.py 
Namespace(example=None)
% test.py --example
Namespace(example=1)
% test.py --example 2
Namespace(example=2)

  • nargs='?' 表示 0 或 1 个参数
  • const=1 当有 0 个参数时设置默认值
  • type=int 将参数转换为 int

如果您希望 test.pyexample 设置为 1,即使没有指定 --example,则包含 default =1。也就是说,与

parser.add_argument('--example', nargs='?', const=1, type=int, default=1)

然后

% test.py 
Namespace(example=1)

关于Python argparse : default value or specified value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15301147/

有关Python argparse : default value or specified value的更多相关文章

随机推荐