这个问题在这里已有答案:
我在Python程序中有一个标志,它只能是某些字符串,rock
,paper
或scissors
。 Python argparse有一个很好的方法来实现它,使用choices
,容器的参数允许值。
以下是文档中的示例:
import argparse
...
parser = argparse.ArgumentParser(prog='game.py')
parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
parser.parse_args(['rock'])
### Namespace(move='rock')
parser.parse_args(['fire'])
### usage: game.py [-h] {rock,paper,scissors}
### game.py: error: argument move: invalid choice: 'fire' (choose from 'rock','paper', 'scissors')
我想实现choices
,使选择不区分大小写,即用户可以输入RoCK
,它仍然有效。
这样做的标准方法是什么?
你可以设置type=str.lower
。
见Case insensitive argparse choices
import argparse
parser = argparse.ArgumentParser(prog='game.py')
parser.add_argument('move', choices=['rock', 'paper', 'scissors'], type=str.lower)
parser.parse_args(['rOCk'])
# Namespace(move='rock')