[英]argparse: How to map choices to different values?
使用 argparse 時,我希望用戶從choices
到 select,但我希望他們的選擇確定更復雜的值(類似於store_const
的工作方式)。
例如,當從['current', 'former', 'never']
的smoker
狀態中進行選擇時,我希望current
到 map 到'Current every day smoker.'
有沒有一種優雅的方法可以做到這一點?
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--smoker', choices=['current','former','never'])
print(vars(parser.parse_args()))
正常output:
$ ./script.py --smoker current
{'smoker': 'current'}
期望:
$ ./script.py --smoker current
{'smoker': 'Current every day smoker.'}
我以為我可以用lambda
類型參數來做到這一點,但argparse
強制執行選擇列表:
choice_dict = {'current': 'Current everyday...'}
parser.add_argument('--smoker', type=lambda x: choice_dict[x], choices=choice_dict.keys())
print(vars(parser.parse_args()))
./script.py --smoker current
usage: script.py [-h] [--smoker {current}]
script.py: error: argument --smoker: invalid choice: 'Current everyday...' (choose from 'current')
雖然我同意 0x5452 的評論,即最好將此格式與解析器分離,但您可以使用Action
來執行您想要的操作:
import argparse
CONVERSION_TABLE = {'current': 'Currently smokes',
'former': 'Used to smoke',
'never': 'Never smoke'}
class RenameOption(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, CONVERSION_TABLE[values])
parser = argparse.ArgumentParser()
parser.add_argument('--smoker', action=RenameOption, choices=CONVERSION_TABLE)
print(vars(parser.parse_args()))
結果是:
$ python test.py --smoker current
{'smoker': 'Currently smokes'}
$ python test.py --smoker no
usage: test.py [-h] [--smoker {current,former,never}]
test.py: error: argument --smoker: invalid choice: 'no' (choose from 'current', 'former', 'never')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.