多项选择命令行参数
Multiple choices command line argument
如何实现命令行中的多项选择参数?会有一组预定义的选项,用户可以选择多个:
python cli.py --alphabet upper,lower,digits,symbols
或
python cli.py --alphabet upper lower digits symbols
如果要使用一些选项解析器是第二选择
来自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:
所以在你的情况下你需要提供
parser.add_argument('--alphabet', nargs='+')
这将代表 所有且至少一个参数
然后调用它:
python cli.py --alphabet upper lower digits symbols
参见:
- https://docs.python.org/3/library/argparse.html#choices
- https://docs.python.org/3/library/argparse.html#nargs
示例:
>>> 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')
如何实现命令行中的多项选择参数?会有一组预定义的选项,用户可以选择多个:
python cli.py --alphabet upper,lower,digits,symbols
或
python cli.py --alphabet upper lower digits symbols
如果要使用一些选项解析器是第二选择
来自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:
所以在你的情况下你需要提供
parser.add_argument('--alphabet', nargs='+')
这将代表 所有且至少一个参数
然后调用它:
python cli.py --alphabet upper lower digits symbols
参见:
- https://docs.python.org/3/library/argparse.html#choices
- https://docs.python.org/3/library/argparse.html#nargs
示例:
>>> 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')