Python argparse:默认值或指定值 [英] Python argparse: default value or specified value
本文介绍了Python argparse:默认值或指定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想有一个可选参数,如果仅存在未指定值的标志,则默认为一个值,但是存储用户指定的值,而不是如果用户指定一个值,则存储默认值.
I would like to have a optional argument that will default to a value if only the flag is present with no value specified, but store a user-specified value instead of the default if the user specifies a value. Is there already an action available for this?
一个例子:
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
我可以创建一个动作,但想查看是否存在执行此操作的方式.
I can create an action, but wanted to see if there was an existing way to do this.
推荐答案
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 nargs='?'
means 0-or-1 argumentsconst=1
sets the default when there are 0 argumentstype=int
converts the argument to int
如果即使未指定--example
,也希望test.py
将example
设置为1,则包括default=1
.也就是说,
If you want test.py
to set example
to 1 even if no --example
is specified, then include default=1
. That is, with
parser.add_argument('--example', nargs='?', const=1, type=int, default=1)
然后
% test.py
Namespace(example=1)
这篇关于Python argparse:默认值或指定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文