Search code examples
pythoncommand-lineargparsemultiple-choice

Multiple choices command line argument


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

Solution

  • 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')