python - 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)
...
解决方案
您可以将它们设为可选,如果已设置,请检查您的代码。
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
推荐阅读
- jquery - 等待光标提交 POST 表单
- c# - 为什么使用 Linq Group By Sum 会给我一个转换错误?
- c# - 比较 Form C# Visual Studio 中的两个 Date From Date 和 Database SQL Server 中的 Date
- css - SCSS 可以检测容器的 2 个子元素是放在同一行还是分成 2 行?
- python - 函数未按预期运行 - 2 个参数,检查 bool 是否为 True
- java - JAVA程序计算从0开始可以被3整除的前n个偶数的总和并打印总和
- javascript - 如何修复“无法读取未定义的属性‘setAttribute’”
- google-fabric - 是否可以从 Fabric Api 检索事件信息?
- matlab - 如何使用矩阵在每个元素中存储一个向量
- git - Git squash 特定的提交