4

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 Answer 1

10
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

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you! What is the '-m' part doing here?
I would also add type=int in the name of 'fail early' principle (and so you don't have to do it yourself). Maybe also choices=[1,2,3,4] ?
just a optional shorthand so you can write python main.py -m 2
This answer doesn't actually answer the question of how to limit to four choices. To be complete, this needs to include the comment from @MaLiN2223.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.