Reputation: 43
I wrote a python program which accept three optional command line arguments.However i want to restrict combination of args to be entered by user.which are :
python script.py -all
python script.py --country_name
python script.py --country_name --city_name
I any other combination program shouldn't get execute.
Note: I am using argparse python module
Upvotes: 2
Views: 517
Reputation: 531235
I wouldn't use options at all, but rather positional arguments that can be omitted.
p = ArgumentParser()
p.add_argument('country', nargs='?')
p.add_argument('city', nargs='?')
Then
script.py # equiv to old script.py --all
script.py FI # equiv to old script.py --countryname FI
script.py FI Turku # equivalent to old script.py --countryname FI --cityname Turku
Upvotes: 1
Reputation: 7045
Argparse has a mutually exclusive group:
import argparse
def main(parser, args):
if args.country_city is not None:
country, city = args.country_city
print(args)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Hello")
group = parser.add_mutually_exclusive_group()
group.add_argument("-all")
group.add_argument("--country_city", nargs="+")
main(parser, parser.parse_args())
Which results in:
python3 test.py -all A --country_city a b
usage: test.py [-h]
[-all ALL | --country_city COUNTRY_CITY [COUNTRY_CITY ...]]
test.py: error: argument --country_city: not allowed with argument -all
python3 test.py --country_city a b
Namespace(all=None, country_city=['a', 'b'])
python3 test.py -all A
Namespace(all='A', country_city=None)
Upvotes: 1
Reputation: 3385
Might be easier if I could see your code ... but basically, once you've run:
args = parser.parse_args()
Then you can put your own validation in. eg.
if args.all and (args.country_name or args.city_name):
raise MySuitableError
Upvotes: 1