ArgParse:如何将选择映射到不同的值?
使用ArgParse时,我希望用户从选择中选择
,但是我希望他们选择确定更复杂的值(类似于store_const
的工作方式)。
例如,从吸烟者选择
['Current','','','Never']
的状态时,我希望Current
to映射到“当前每天吸烟者。”
有没有一种优雅的方法来做到这一点?
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--smoker', choices=['current','former','never'])
print(vars(parser.parse_args()))
正常输出:
$ ./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')
When using argparse, I would like a user to select from choices
, but I would like their choice to determine a more complex value (similar to how store_const
works).
For example, when choosing from a smoker
status of ['current', 'former', 'never']
, I would like current
to map to 'Current every day smoker.'
Is there an elegant way to do this?
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--smoker', choices=['current','former','never'])
print(vars(parser.parse_args()))
Normal output:
$ ./script.py --smoker current
{'smoker': 'current'}
Desired:
$ ./script.py --smoker current
{'smoker': 'Current every day smoker.'}
I thought I could do this with a lambda
type argument, but argparse
enforces the list of choices:
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')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尽管我同意0x5452的评论,即最好将这种格式与解析器解),但您可以使用
action
来做您想要的事情:结果是:
Though I agree with 0x5452 comment that it is better to decouple this formatting from the parser, you can use an
Action
to do what you want:The result is: