【问题标题】:ArgParse: Check if argument value present or not, else use defaultArgParse:检查参数值是否存在,否则使用默认值
【发布时间】:2021-07-27 11:24:18
【问题描述】:

我想在命令行中传递参数时存储 TRUE/FALSE。但如果参数名称后没有任何内容或未指定参数,则应存储 TRUE。 下面的代码大部分都是这样做的,除了它在简单地指定 --stoplogging 时存储 NONE (如在第二个所需的输出中)

import argparse
parser=argparse.ArgumentParser()
parser.add_argument('--stoplogging', action='store', default="True", nargs='?')
args=parser.parse_args()
print(args)

实际输出:

>>>python test.py
>>>Namespace(stoplogging='True')

>>>python test.py  --stoplogging
>>>Namespace(stoplogging='None')

>>>python test.py  --stoplogging=True
>>>Namespace(stoplogging='True')

>>>python test.py  --stoplogging=False
>>>Namespace(stoplogging='False')

期望的输出:

>>>python test.py
>>>Namespace(stoplogging='True')

>>>python test.py  --stoplogging
>>>Namespace(stoplogging='True')

>>>python test.py  --stoplogging=True
>>>Namespace(stoplogging='True')

>>>python test.py  --stoplogging=False
>>>Namespace(stoplogging='False')

【问题讨论】:

  • 你的代码有什么输出?将其编辑到问题中。
  • 您可能正在寻找action="store_true" - 这意味着,如果指定了选项,则分配值True。否则设置为False
  • 当我使用action="store_true" 时,我得到以下信息: 用法:test.py [-h] [--stoplogging] test.py:错误:参数 --stoplogging:忽略显式参数 'False'

标签: python argparse


【解决方案1】:

我找到了适合我所需输出的解决方案:

import argparse
parser=argparse.ArgumentParser()
parser.add_argument('--stoplogging', action='store', default="True", const="True", nargs="?")
args=parser.parse_args()
print(args)
  • nargs='?' 表示 0 或 1 个参数
  • const="True" 当有 0 个参数时将默认设置为 True

【讨论】:

    猜你喜欢
    • 2023-01-11
    • 2019-04-06
    • 2015-09-28
    • 2016-08-14
    • 1970-01-01
    • 2013-12-14
    • 2018-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多