python - 参数解析 : How to make mutually exclusive arguments optional?

标签 python python-2.7

我想像这样使用我的脚本:

python test.py run
python test.py stop

我的代码是这样的:

parser = argparse.ArgumentParser()
command_group = parser.add_mutually_exclusive_group(required=True)
command_group.add_argument('run', help='run it', action='store_true')
command_group.add_argument('stop', help='stop it', action='store_true')

当我执行它时,引发了一个异常:

ValueError: mutually exclusive arguments must be optional

所以我尝试在添加每个参数时添加 required=False。然后我得到另一个异常:

TypeError: 'required' is an invalid argument for positionals

我很困惑。

最佳答案

一个更好的方法是添加一个可以有两个选择的位置参数。由于您希望它是可选的,因此使用 nargs='?',这意味着零次或一次:

parser = argparse.ArgumentParser()
parser.add_argument('run', help='run or stop', nargs='?', choices=('run', 'stop'))

如果给出run,则值为'run'。如果给出了 stop,它将是 'stop'。如果两者都没有给出,它将是 None


如果你真的想使用互斥组,我不确定你是否能完全按照你的意愿去做。但是,您可以通过添加连字符使它们成为可选参数:

import argparse

parser = argparse.ArgumentParser()
command_group = parser.add_mutually_exclusive_group()
command_group.add_argument('-run', help='run it', action='store_true')
command_group.add_argument('-stop', help='stop it', action='store_true')

当然,问题是用户还需要提供连字符,但如果您这样限制自己,就会遇到这种问题。

关于python - 参数解析 : How to make mutually exclusive arguments optional?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39092149/

相关文章:

python - 是否可以从python中的函数返回两个列表

python - 在Python中,如何设计复杂的列表理解的样式

python - 如何添加每列均值的额外卷?

python - Pyparsing - 递归返回意外结果

python - PyCharm 无法识别我的 Python 安装路径

python - 在对象定义中使用 "()"和不使用它有什么区别?

python - 实现 Every-to-Every 交互的有效方法?

python - 函数速度提升 : Convert ints to list of 32bit ints

python - 如何将自定义函数应用于 xarray.DataArray.coarsen.reduce()?

python - 没有 float64 转换的两个具有缺失值的 uint64 系列的最小值