我希望添加一个可选参数,如果用户指定值,则存储用户指定的值,否则将默认为一个指定的值。是否已经有此类操作可用?
例如:
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
我可以创建一个动作,但想知道是否有现成的方法可以实现这个功能。
我希望添加一个可选参数,如果用户指定值,则存储用户指定的值,否则将默认为一个指定的值。是否已经有此类操作可用?
例如:
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
我可以创建一个动作,但想知道是否有现成的方法可以实现这个功能。
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
设定当没有参数时的默认值为1type=int
将参数转换为整数类型如果你想让test.py
在没有指定--example
的情况下,将example
设置为1,请包括default=1
。也就是说,使用:
parser.add_argument('--example', nargs='?', const=1, type=int, default=1)
然后
% test.py
Namespace(example=1)
两者的区别:
parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1, default=7)
andparser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1)
因此:
myscript.py
=> 在第一种情况下,调试值为7(默认值),在第二种情况下为"None"
myscript.py --debug
=> 在每种情况下,调试值都为1
myscript.py --debug 2
=> 在每种情况下,调试值都为2
self.foo = (args.bar or some_else_source).upper()
的代码。如果出现None对象,它将会出错。 - 0andriy