自定义操作 argparse Python
我想对 2 个不同的参数使用相同的自定义操作:
class TestAction(Action):
def __call__(self, parser, namespace, values, option_string=None):
car, color, state, code = values
namespace.car = car
namespace.color = color
namespace.state = state
namespace.code = code
当我定义参数时,我想按如下方式定义它们:
parser.add_argument('--vehicle', nargs="2", action=TestAction, metavar=('car', 'color'), required=True)
parser.add_argument('--country', nargs="2", type=tuple(str, int), action=TestAction,metavar=('state', 'code'), required=True)
如果我按照编写的方式使用自定义操作,则会收到以下错误:
ValueError: not enough values to unpack (expected 4, got 2)
I一直试图定义一些虚拟的“_”并在解包时用“_”填充空值,但没有成功。 第二个问题是我想强制代码为整数,但语法 tuple(str, int)
不正确。 有什么想法可以解决这两个问题吗? 谢谢。
I would like to use the same custom action for 2 different arguments:
class TestAction(Action):
def __call__(self, parser, namespace, values, option_string=None):
car, color, state, code = values
namespace.car = car
namespace.color = color
namespace.state = state
namespace.code = code
When I am defining the arguments, I would like to define them as follows:
parser.add_argument('--vehicle', nargs="2", action=TestAction, metavar=('car', 'color'), required=True)
parser.add_argument('--country', nargs="2", type=tuple(str, int), action=TestAction,metavar=('state', 'code'), required=True)
If I am using the custom action as it is written, I am getting the following error:
ValueError: not enough values to unpack (expected 4, got 2)
I've been trying to define some dummy '_' and fill the empty values with "_" when unpacking, but it didn't worked.
The second issue is that I would like to force the code to be integer and the syntax tuple(str, int)
is not correct.
Any ideas how can I correct these 2 issues?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为更简单的方法是使用这样的东西(没有
argparse.Action
):输出:
I think the easier way is to use something like this (without
argparse.Action
):The output: