Python argparse:默认值或指定的值
我想有一个可选参数,默认值为一个值,如果只有标志存在没有指定的值,但存储用户指定的值而不是默认值,如果用户指定一个值。 有没有可用的行动?
一个例子:
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
我可以创build一个动作,但想看看是否有现成的方法来做到这一点。
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的参数 - 有0个参数时,
const=1设置默认值 -
type=int将参数转换为int
如果您希望test.py将example设置为1(即使没有指定--example ),则包括default=1 。 也就是说
parser.add_argument('--example', nargs='?', const=1, type=int, default=1)
然后
% test.py Namespace(example=1)