我想像这样使用我的脚本:
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/