ArgParse:如何将选择映射到不同的值?

发布于 2025-02-08 03:20:06 字数 1082 浏览 1 评论 0原文

使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

未蓝澄海的烟 2025-02-15 03:20:06

尽管我同意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')

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:

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()))

The result is:

$ 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')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文