The best way to do this is to add one positional argument, which can have two options. Since you want it to be optional, use nargs='?' that means zero or once:
parser = argparse.ArgumentParser() parser.add_argument('run', help='run or stop', nargs='?', choices=('run', 'stop'))
If run is given, the value will be 'run' . If stop specified, it will be 'stop' . If none of them are specified, it will be None .
If you really want to use a mutually exclusive group, Iām not sure that you can do it exactly as you want. However, you can make them optional arguments by adding a hyphen:
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')
Of course, the problem is that the user also needs to provide a hyphen, but this is the problem you can expect if you limit yourself this way.
source share