繁体   English   中英

python:带有可选命令行参数的argparse

[英]python: argparse with optional command-line arguments

我想实现参数解析。

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

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

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

更新出于某种原因,当我添加nargs='?'时,建议的带有add_mutually_exclusive_group解决方案add_mutually_exclusive_group 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)
...

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM