Python argparse:默认值或指定值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15301147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:43:25  来源:igfitidea点击:

Python argparse: default value or specified value

pythondefault-valueargparse

提问by Rob

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?

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

An example:

一个例子:

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.

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

采纳答案by unutbu

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='?'means 0-or-1 arguments
  • const=1sets the default when there are 0 arguments
  • type=intconverts the argument to int
  • nargs='?'表示 0 或 1 个参数
  • const=1当有 0 个参数时设置默认值
  • type=int将参数转换为 int


If you want test.pyto set exampleto 1 even if no --exampleis specified, then include default=1. That is, with

如果即使指定no也想test.py设置example为 1 --example,则包含default=1. 也就是说,与

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

then

然后

% test.py 
Namespace(example=1)

回答by Adam Erickson

Actually, you only need to use the defaultargument to add_argumentas in this test.pyscript:

实际上,您只需要在此脚本中使用defaultto add_argumentas参数test.py

import argparse

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument('--example', default=1)
    args = parser.parse_args()
    print(args.example)


test.py --example
% 1
test.py --example 2
% 2

Details are here.

详细信息在这里

回答by Murray

The difference between:

和...之间的不同:

parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1, default=7)

and

parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1)

is thus:

是这样的:

myscript.py=> debug is 7 (from default) in the first case and "None" in the second

myscript.py=> debug 在第一种情况下为 7(从默认值开始),在第二种情况下为“None”

myscript.py --debug=> debug is 1 in each case

myscript.py --debug=> 调试在每种情况下都是 1

myscript.py --debug 2=> debug is 2 in each case

myscript.py --debug 2=> 调试在每种情况下都是 2