Python argparse with choices

Viewed 2691

I want to run my python program from the command line with some options. E.g. say my program has 4 modes, and I want it to use mode 2 by giving it the following arguments:

$ python main.py --mode 2

(And similarly for modes 1, 3, 4). How can I achieve this using argparse?

1 Answers
import argparse


parser = argparse.ArgumentParser(description='PROJECT_NAME')
parser.add_argument(
    '--mode', '-m',
    help='Set mode',
    default=1,
    type=int,
    choices=[1,2,3,4],
)
args = parser.parse_args()

print(args.mode)

For a complete list of the options available visit the docs:

https://docs.python.org/3/library/argparse.html


Update:

Added the suggestions from MaLiN2223's comment

Related