【发布时间】: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')) -
我不知道,我希望能够将
s或l传递给参数。但如果用户只传递没有值的'-j`,则默认使用s。 -
如果您不使用
-j运行命令,它将按预期工作并默认使用s。也许你可以检查-j是否为None并将其设置为s然后 -
啊那是我的误解。如果 -j 不带参数传递,有没有办法让 -j 使用
s? -
从 CLI 设计的角度来看,在您的代码中进行这样的论证是没有意义的。也许您应该做的是添加
--output-type和choices=['json-s', 'json-l', 'normal']并将默认设置为'normal'