Skip to main content
 首页 » 编程设计

python之如何通过分解两个非常相似的类来在 Argparse 的类中传递参数

2024年10月17日8pander-it

我有以下代码:

def main(args): 
    """ 
    Description of main 
    """ 
    print args 
 
 
if __name__ == '__main__': 
    class DefaultListAction(argparse.Action): 
        CHOICES = ['ann','netmhcpan','comblib_sidney2008','consensus','smm','smmpmbec','netmhccons'] 
        def __call__(self, parser, namespace, values, option_string=None): 
            if values: 
                for value in values: 
                    if value not in self.CHOICES: 
                        message = ("invalid choice: {0!r} (choose from {1})" 
                                .format(value, 
                                        ', '.join([repr(action) 
                                                    for action in self.CHOICES]))) 
 
                        raise argparse.ArgumentError(self, message) 
                setattr(namespace, self.dest, values) 
 
    class DefaultListAction_Frames(argparse.Action): 
        CHOICES = ['R','F','6'] 
        def __call__(self, parser, namespace, values, option_string=None): 
            if values: 
                for value in values: 
                    if value not in self.CHOICES: 
                        message = ("invalid choice: {0!r} (choose from {1})" 
                                .format(value, 
                                        ', '.join([repr(action) 
                                                    for action in self.CHOICES]))) 
 
                        raise argparse.ArgumentError(self, message) 
                setattr(namespace, self.dest, values) 
 
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter) 
    parser.add_argument("-iedb",help="IEDB tools options: ann, comblib_sydney2008, consensus, netmhcpan, smm, smmpmbec, netmhccons", \ 
              action=DefaultListAction, nargs='*', default=[''], \ 
              metavar='iedb_tools') 
    parser.add_argument("-f",help="Frame to translate insert: (F)orward three frames, (R)everse three frames or (6) frames F + B.  Default F.", \ 
              action=DefaultListAction_Frames, nargs=1, default=['F'], \ 
              metavar='frames') 
    args = parser.parse_args() 
    main(args) 

基本上,有两个 argparse.ArgumentParser.add_argument() ,每个都将其中一个类作为 action 中的参数。

我的问题是如何分解 class DefaultListAction(argparse.Action) 和 class DefaultListAction_Frames(argparse.Action),因为两者之间的唯一区别是 CHOICES 参数。

我如何将这些 CHOICES 作为参数传递给 argparse.ArgumentParser.add_argument()

请您参考如下方法:

add_argument choices 参数可用作 self.choices。它没有在任何现有的 Action 子类中使用,但没有理由不使用它。

在将值传递给 Action.__call__ 之前,解析器将使用它来测试这些值。在这个测试中似乎与您自己的使用没有冲突,但我不能排除这种可能性。

action.choices 也用于帮助格式化,尽管 metavar 参数覆盖了它。

class ListAction(argparse.Action): 
    # change self.CHOICES to self.choices 
    def __call__(self, parser, namespace, values, option_string=None): 
        if values: 
            for value in values: 
                if value not in self.choices: 
                    message = ("invalid choice: {0!r} (choose from {1})" 
                            .format(value, 
                                    ', '.join([repr(action) 
                                                for action in self.choices]))) 
 
                    raise argparse.ArgumentError(self, message) 
            setattr(namespace, self.dest, values) 
 
# should behave just like the -f argument 
parser.add_argument("-g",help="Frame to translate insert: (F)orward three frames, (R)everse three frames or (6) frames F + B.  Default F.", \ 
          action=ListAction, nargs=1, default=['F'], \ 
          choices=['R','F','6']) 

帮助允许选择作为元变量(用于说明目的)

2304:~/mypy$ python stack41562756.py -h 
usage: stack41562756.py [-h] [-iedb [iedb_tools [iedb_tools ...]]] [-f frames] 
                        [-g {R,F,6}] 
 
optional arguments: 
  -h, --help            show this help message and exit 
  -iedb [iedb_tools [iedb_tools ...]] 
                        IEDB tools options: ann, comblib_sydney2008, consensus, netmhcpan, smm, smmpmbec, netmhccons 
  -f frames             Frame to translate insert: (F)orward three frames, (R)everse three frames or (6) frames F + B.  Default F. 
  -g {R,F,6}            Frame to translate insert: (F)orward three frames, (R)everse three frames or (6) frames F + B.  Default F. 

解析action.choices时只用在_check_value中,由_get_values调用。

def _check_value(self, action, value): 
    # converted value must be one of the choices (if specified) 
    if action.choices is not None and value not in action.choices: 
        args = {'value': value, 
                'choices': ', '.join(map(repr, action.choices))} 
        msg = _('invalid choice: %(value)r (choose from %(choices)s)') 
        raise ArgumentError(action, msg % args) 

看起来你可以使用默认的 store 操作和 choices:

parser.add_argument("-e",help="Frame to translate insert: (F)orward three frames, (R)everse three frames or (6) frames F + B.  Default F.", \ 
          nargs=1, default=['F'], choices=['R','F','6']) 

我在您的自定义操作中没有发现任何不同之处。但我还没有详细研究或测试它们。

=================

另一种方法是仅对您的一个新 Action 进行子类化:

class DefaultListAction_Frames(DefaultListAction): 
    CHOICES = ['R','F','6','X'] 

如果__call__方法相同,则不必重复。

另一种方法是使用工厂函数为每个 DefaultListAction 操作赋予其自己的 CHOICES 属性。 FileType 就是这样一个类 - 它创建了一个自定义的 type 函数。

type 函数是另一个您可以自定义值检查的地方。 type 用于值转换和测试,而如果您想以某种特殊方式保存值,则自定义 Action 类最有用。