Multiple choices command line argument
Asked Answered
V

3

11

How could a multiple choices argument in the command line be implemented? There would be a predefined set of options and the user can choose multiple:

python cli.py --alphabet upper,lower,digits,symbols

or

python cli.py --alphabet upper lower digits symbols
Vera answered 3/6, 2017 at 10:15 Comment(0)
P
21

See:

Example:

>>> import argparse
>>> parser = argparse.ArgumentParser(prog='game.py')
>>> parser.add_argument('--move', choices=['rock', 'paper', 'scissors'], nargs="+")
>>> parser.parse_args(['--move', 'rock', 'paper'])
Namespace(move=['rock', 'paper'])
>>> parser.parse_args(['--move','fire'])
usage: game.py [-h] [--move {rock,paper,scissors} [{rock,paper,scissors} ...]]
game.py: error: argument --move: invalid choice: 'fire' (choose from 'rock', 'paper', 'scissors')
Pinter answered 3/6, 2017 at 10:30 Comment(0)
F
4

From Variable Argument Lists of argparse in Python 3 Module of the Week:

You can configure a single argument definition to consume multiple arguments on the command line being parsed. Set nargs to one of these flag values, based on the number of required or expected arguments:

So in your case you need to supply

parser.add_argument('--alphabet', nargs='+')

Which would stand for All, and at least one, argument

And then call it with:

python cli.py --alphabet upper lower digits symbols
Forebrain answered 3/6, 2017 at 10:28 Comment(0)
Y
0

If you want to use some options parser is the second choice

Ypsilanti answered 3/6, 2017 at 10:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.