【问题标题】:python: argparse with optional command-line argumentspython:带有可选命令行参数的argparse
【发布时间】:2020-05-04 13:19:15
【问题描述】:

我想实现参数解析。

./app.py -E [optional arg] -T [optional arg]

脚本至少需要以下参数之一:-E-T

我应该在parser.add_argument 中传递什么来获得这样的功能?

更新 由于某些原因,当我添加了nargs='?'const= 属性时,add_mutually_exclusive_group 的建议解决方案不起作用:

parser = argparse.ArgumentParser(prog='PROG')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-F', '--foo', nargs='?', const='/tmp')
group.add_argument('-B', '--bar', nargs='?', const='/tmp')
parser.parse_args([])

script.py -F 运行仍然会抛出错误:

PROG: error: one of the arguments -F/--foo -B/--bar is required

但是,以下解决方法帮助了我:

parser = argparse.ArgumentParser(prog='PROG')
parser.add_argument('-F', '--foo', nargs='?', const='/tmp')
parser.add_argument('-B', '--bar', nargs='?', const='/tmp')
args = parser.parse_args()

if (not args.foo and not args.bar) or (args.foo and args.bar):
   print('Must specify one of -F/-B options.')
   sys.exit(1)

if args.foo:
   foo_func(arg.foo)
elif args.bar:
   bar_func(args.bar)
...

【问题讨论】:

标签: python argparse


【解决方案1】:

您可以将它们设为可选,如果已设置,请检查您的代码。

parser = argparse.ArgumentParser()
parser.add_argument('--foo')
parser.add_argument('--bar')

args = parser.parse_args()

if args.foo is None and args.bar is None:
   parser.error("please specify at least one of --foo or --bar")

如果您只想显示两个参数之一,请参阅 [add_mutually_exclusive_group] (https://docs.python.org/2/library/argparse.html#mutual-exclusion) 和 required=True

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> group = parser.add_mutually_exclusive_group(required=True)
>>> group.add_argument('--foo', action='store_true')
>>> group.add_argument('--bar', action='store_false')
>>> parser.parse_args([])
usage: PROG [-h] (--foo | --bar)
PROG: error: one of the arguments --foo --bar is required

【讨论】:

  • OP 声明“至少一个”,这听起来像是互斥不是他想要的。
  • @MaxNow,是的,你是对的。更新了答案以包含至少一个。
  • @ShashankV,感谢您的回答。 argparse 是否支持检查参数后面的可选参数?例如,script.py --foo FOO_BAR 和 FOO_BAR 是可选的。
  • nargs="?' 使参数可选。最好与defaultconst 参数一起使用。请参阅文档。
猜你喜欢
  • 2018-08-11
  • 1970-01-01
  • 1970-01-01
  • 2012-01-05
  • 1970-01-01
  • 2013-07-10
  • 2018-10-14
  • 2023-03-13
相关资源
最近更新 更多