如何在 Python argparse 中接受`choices`而不考虑大小写?
How to accept `choices` in Python argparse irrespective of case?
我在 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')
我在 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')