传递附加参数的 Python argparse 自定义操作

问题描述 投票:0回答:2
import argparse

class customAction(argparse.Action):
    def __call__(self, parser, args, values, option_string=None):
       setattr(args, self.dest, values)

parser = argparse.ArgumentParser()
parser.add_argument('-e', '--example', action=customAction)

我想在触发选项 -e 时将附加参数传递给 customAction,例如另一个类的实例。我怎样才能做到这一点?我尝试过的一切都出错了。

python action argparse
2个回答
49
投票
def make_action(additional_arg):
    class customAction(argparse.Action):
        def __call__(self, parser, args, values, option_string=None):
            print(additional_arg)
            setattr(args, self.dest, values)
    return customAction
#...
parser.add_argument('-e', '--example', action=make_action('your arg'))

21
投票

另一种解决方案是派生基类

argparse.Action
,如下所示:

class CustomAction(argparse.Action):
    def __init__(self,option_strings,
                 additional_arg1,additional_arg2,
                 dest=None,
                 nargs=0,
                 default=None,
                 required=False,
                 type=None,
                 metavar=None,
                 help=None):
        self._a1=additional_arg1
        self._a2=additional_arg2
        super(CustomAction, self).__init__(
            option_strings=option_strings,
            dest=dest,
            nargs=nargs,
            default=default,
            required=required,
            metavar=metavar,
            type=type,
            help=help)
    def __call__(self, parser, namespace, values, option_string=None):
        print(self._a1)
        print(self._a2)
        setattr(namespace, self.dest, values)

#........
parser.add_argument('-e', '--example', action=CustomAction, additional_arg1='your arg', additional_arg2=42)

或者,提供

*args
**kwargs
将任何其他参数传递给父构造函数。

class CustomAction(argparse.Action):
    def __init__(self, option_strings, additional_arg1, additional_arg2,
                 *args, **kwargs):
        self._a1 = additional_arg1
        self._a2 = additional_arg2
        super(CustomAction, self).__init__(option_strings=option_strings,
                                           *args, **kwargs)
    def __call__(self, parser, namespace, values, option_string=None):
        print(self._a1)
        print(self._a2)
        setattr(namespace, self.dest, values)

#........
parser.add_argument('-e', '--example', action=CustomAction, additional_arg1='your arg', additional_arg2=42)
© www.soinside.com 2019 - 2024. All rights reserved.