10

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

3 Answers3

18

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')
Dunes
  • 37,291
  • 7
  • 81
  • 97
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
vishes_shell
  • 22,409
  • 6
  • 71
  • 81
0

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

Ptank
  • 104
  • 6