访问传递给 argparser 参数的选项? [英] Accessing the choices passed to argument in argparser?

查看:25
本文介绍了访问传递给 argparser 参数的选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以访问传递给参数的选择元组?如果是这样,我该怎么办

例如如果我有

parser = argparse.ArgumentParser(description='选择位置')parser.add_argument("- 地点",选择=('这里','那里','任何地方'))args = parser.parse_args()

我可以访问元组('here', 'there', 'anywhere')吗?

解决方案

事实证明 parser.add_argument 实际上返回了关联的 Action.您可以从中选择:

<预><代码>>>>导入参数解析>>>parser = argparse.ArgumentParser(description='选择位置')>>>action = parser.add_argument(... "- 地点",...选择=('这里','那里','任何地方')……)>>>行动选择('这里','那里','任何地方')

请注意 (AFAIK) 这没有记录在任何地方,可能被视为实施细节",因此可能会随时更改,恕不另行通知等.

也没有任何公开可访问的方式来获取添加后存储在 ArgumentParser 上的操作.我相信它们可以作为 parser._actions 使用,如果您愿意讨论实现细节(并承担与之相关的任何风险)...

<小时>

您最好的办法是为位置选择创建一个常量,然后在您的代码中使用它:

LOCATION_CHOICES = ('这里', '那里', '任何地方')parser = argparse.ArgumentParser(description='选择位置')parser.add_argument("- 地点",选择=LOCATION_CHOICES)args = parser.parse_args()# 在这里使用 LOCATION_CHOICES...

Is it possible to access the tuple of choices passed to an argument? If so, how do I go about it

for example if I have

parser = argparse.ArgumentParser(description='choose location')
parser.add_argument(
    "--location",
    choices=('here', 'there', 'anywhere')
)
args = parser.parse_args()

can I access the tuple ('here', 'there', 'anywhere')?

解决方案

It turns out that parser.add_argument actually returns the associated Action. You can pick the choices off of that:

>>> import argparse
>>> parser = argparse.ArgumentParser(description='choose location')
>>> action = parser.add_argument(
...     "--location",
...     choices=('here', 'there', 'anywhere')
... )
>>> action.choices
('here', 'there', 'anywhere')

Note that (AFAIK) this isn't documented anywhere and may be considered an "implementation detail" and therefore subject to change without notice, etc. etc.

There also isn't any publicly accessible way to get at the actions stored on an ArgumentParser after they've been added. I believe that they are available as parser._actions if you're willing to go mucking about with implementation details (and assume any risks involved with that)...


Your best bet is to probably create a constant for the location choices and then use that in your code:

LOCATION_CHOICES = ('here', 'there', 'anywhere')

parser = argparse.ArgumentParser(description='choose location')
parser.add_argument(
    "--location",
    choices=LOCATION_CHOICES
)
args = parser.parse_args()

# Use LOCATION_CHOICES down here...

这篇关于访问传递给 argparser 参数的选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆