Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allowing specific values for an Argparse argument [duplicate]

People also ask

How do you make Argparse argument optional?

To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.

What does Nargs do in Argparse?

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.

What is Metavar in Argparse?

Metavar: It provides a different name for optional argument in help messages.


An argparse argument can be limited to specific values with the choices parameter:

...
parser.add_argument('--val',
                    choices=['a', 'b', 'c'],
                    help='Special testing value')

args = parser.parse_args(sys.argv[1:])

See the docs for more details.