Python argparse:默认值或指定值 [英] Python argparse: default value or specified value

查看:38
本文介绍了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 arguments
    • const=1 sets the default when there are 0 arguments
    • type=int converts the argument to int
    • 如果您希望 test.pyexample 设置为 1,即使没有指定 --example,则包括 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆