【问题标题】:python argparse default with nargs wont work带有 nargs 的 python argparse 默认值不会工作
【发布时间】:2023-01-22 12:12:40
【问题描述】:

这是我的代码:

from argparse import ArgumentParser, RawTextHelpFormatter 

example_text = "test"

parser = ArgumentParser(description='my script.',
                        epilog=example_text,
                        formatter_class=RawTextHelpFormatter)
parser.add_argument('host', type=str, default="10.10.10.10",
                    help="Device IP address or Hostname.")
parser.add_argument('-j','--json_output', type=str, default="s", nargs='?',choices=["s", "l"],
                    help="Print GET statement in json form.")
#mutally exclusive required settings supplying the key
settingsgroup = parser.add_mutually_exclusive_group(required=True)
settingsgroup.add_argument('-k', '--key', type=str, 
                    help="the api-key to use. WARNING take care when using this, the key specified will be in the user's history.")
settingsgroup.add_argument('--config', type=str, 
                    help="yaml config file. All parameters can be placed in the yaml file. Parameters provided from form command line will take priority.")

args = parser.parse_args()

print(args.json_output)

我的输出:

None

我在网上阅读的所有内容都说这应该有效,但事实并非如此。为什么?

【问题讨论】:

  • 我相信你真的想要一面旗帜(add_argument('-j', '--json_output', action='store_true')
  • 我不知道,我希望能够将 sl 传递给参数。但如果用户只传递没有值的'-j`,则默认使用s
  • 如果您不使用 -j 运行命令,它将按预期工作并默认使用 s。也许你可以检查-j是否为None并将其设置为s然后
  • 啊那是我的误解。如果 -j 不带参数传递,有没有办法让 -j 使用 s
  • 从 CLI 设计的角度来看,在您的代码中进行这样的论证是没有意义的。也许您应该做的是添加 --output-typechoices=['json-s', 'json-l', 'normal'] 并将默认设置为 'normal'

标签: python argparse default


【解决方案1】:

您可以执行以下操作:

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('-j', '--json-output', nargs='?', choices=['s', 'l'], default='d')

args = parser.parse_args()

if args.json_output is None:
    args.json_output = 's'

if args.json_output == 'd':
    args.json_output = None

无论设计如何明智,使用以下内容可能会更好:

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('-o', '--output-type', choices=['json-s', 'json-l', 'normal'], default='normal')

args = parser.parse_args()

【讨论】:

    猜你喜欢
    • 2018-06-29
    • 1970-01-01
    • 2022-08-19
    • 2013-10-14
    • 2014-10-11
    • 2017-03-12
    • 1970-01-01
    • 2017-08-20
    • 2022-08-05
    相关资源
    最近更新 更多