首页 > 解决方案 > python:带有可选命令行参数的argparse

问题描述

我想实现参数解析。

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

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

我应该传递什么parser.add_argument才能拥有这样的功能?

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

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)
...

标签: pythonargparse

解决方案


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

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

推荐阅读