'Python argparse prevent long and short flags at same time
I have this code:
parser = argparse.ArgumentParser()
parser.add_argument('-L', '--list', action='store_true', help='list options')
args = parser.parse_args()
I want this:
$./example.py --list
or
$./example.py -L
but not:
$./example -L --list # or --list -L
Is there an elegant way to avoid that both flags being used at the same time?
Solution 1:[1]
You can form a mutually exclusive group. That isn't ideal, since you'll end up repeating arguments to each, but that can be wrapped up into a helper function if need be.
parser = argparse.ArgumentParser()
arg_group = parser.add_mutually_exclusive_group()
arg_group.add_argument('-L', action='store_true', help='list options')
arg_group.add_argument('--list', action='store_true', help='list options')
args = parser.parse_args()
If you wanted to pretty this up a bit (to avoid repeating yourself), you could do something like:
class MutexArgParser(argparse.ArgumentParser):
def add_mutex_arguments(self, flags, *args, **kwargs):
arg_group = self.add_mutually_exclusive_group()
for flag in flags:
arg_group.add_argument(flag, *args, **kwargs)
parser = MutexArgParser()
parser.add_mutex_arguments(['-L', '--list'], action='store_true', help='list options')
args = parser.parse_args()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Dillon Davis |