I have a flag in a Python program which can only be certain strings, rock
, paper
, or scissors
. Python argparse has a great way to implement this, using choices
, container of the allowable values for the argument.
Here's an example from the documentation:
import argparse
...
parser = argparse.ArgumentParser(prog='game.py')
parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
parser.parse_args(['rock'])
### Namespace(move='rock')
parser.parse_args(['fire'])
### usage: game.py [-h] {rock,paper,scissors}
### game.py: error: argument move: invalid choice: 'fire' (choose from 'rock','paper', 'scissors')
I would like to implement choices
such that the choices are not case-sensitive, i.e. users could input RoCK
and it would still be valid.
What is the standard way to do this?
To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.
Number of Arguments If you want your parameters to accept a list of items you can specify nargs=n for how many arguments to accept. Note, if you set nargs=1 , it will return as a list not a single value.
Metavar: It provides a different name for optional argument in help messages.
You can set type=str.lower
.
See Case insensitive argparse choices
import argparse
parser = argparse.ArgumentParser(prog='game.py')
parser.add_argument('move', choices=['rock', 'paper', 'scissors'], type=str.lower)
parser.parse_args(['rOCk'])
# Namespace(move='rock')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With