Python: How to create mutual exclusive command line arguments

When we create command line tools there are cases that we need to insert a certain combination of command line arguments but also to…

Python: How to create mutual exclusive command line arguments
thonPhoto by David Clode on Unsplash

When we create command line tools there are cases that we need to insert a certain combination of command line arguments but also to exclude some combinations in order to allow only one argument to exist from a group of arguments, lets see how we can achieve this in Python using the argparse module

Save the following as example1.py

#!/usr/bin/env python3 
import argparse 
 
parser = argparse.ArgumentParser(description="Mutually Exclusive Arguments Example") 
exclusive_group = parser.add_mutually_exclusive_group() 
 
exclusive_group.add_argument("--option1", help="option 1", required = False) 
exclusive_group.add_argument("--option2", help="option 2", required = False) 
 
parser.add_argument("--common_option", action="store_true", help="Common option that can be used with or without other options") 
 
args = parser.parse_args()

Lets do some tests now! using only one of option1 and option2 arguments on each time no errors occur!

python3 ./example1.py --option1 blahblah            
python3 ./example1.py --option2 blahblah

Also no errors occur of we try to run the script with either option1 and option2 with the common_option argument!

python3 ./example1.py --option2 blahblah --common_option          
python3 ./example1.py --option1 blahblah --common_option

But when we try to combine option2 and option1 we will get an error message!

python3 ./example1.py --option1 blahblah --option2 blahblah 
usage: example1.py [-h] [--option1 OPTION1 | --option2 OPTION2] [--common_option] 
example1.py: error: argument --option2: not allowed with argument --option1

Lets explain how this works

We have asked argparse to create a mutual_exclusive_group() , then we add arguments that we want to be part of this group using the add_argument() method of the group! then exception throwing will be automatically take care in the parser.parse_args() line!

exclusive_group = parser.add_mutually_exclusive_group() 
 
exclusive_group.add_argument("--option1", help="option 1", required = False) 
exclusive_group.add_argument("--option2", help="option 2", required = False)

Conclusion

Mutual exclusive groups in argparse are a very simple but yet powerful functionality which allows you to do such combinations without making your script complex! i hope you enjoyed this article!

In Plain English 🚀

Thank you for being a part of the In Plain English community! Before you go: