subgcassing argparse和覆盖add_argument_group

时间:2014-02-21 15:45:36

标签: python argparse

我想为多个脚本使用通用解析器,因此为了保持代码清洁,我希望有一个地方可以处理所有常见的参数。我可以通过继承ArgumentParser来做到这一点,但我遇到了添加组的问题。当我添加一个组时,他们不再能够访问我编写的自定义方法。为了解决这个问题,我基本上复制了add_argument_group方法并添加了其他功能。我知道这是一个可怕的解决方案,有关如何正确实现这一点的任何建议吗?

class CustomParser(argparse.ArgumentParser):
    def __init__(self, *args, **kwrds):
        super(CustomParser, self).__init__(*args, **kwrds)

    def add_enzyme(self):
        self.add_argument('--enzyme', help="The enzyme to cleave with. Also valid is a"
                                           " cleavage pattern such as [KR]|{P}.",
                          choices=protein_config.ENZYMES.keys(), type=str, default='trypsin')

    def add_fasta(self, help="The fasta file to operate on."):
        self.add_argument('-f', '--fasta', nargs='?', help=help, type=argparse.FileType('r'), default=sys.stdin)

    def add_out(self, help='The file to write results to. Leave blank for stdout,'):
        self.add_argument('-o', '--out', nargs='?', help=help, type=argparse.FileType('w'), default=sys.stdout)

    def add_argument_group(self, *args, **kwargs):
        group = argparse._ArgumentGroup(self, *args, **kwargs)
        self._action_groups.append(group)
        group.add_enzyme = self.add_enzyme
        group.add_fasta = self.add_fasta
        group.add_out = self.add_out
        return group

2 个答案:

答案 0 :(得分:0)

我会像这样动态添加组方法:

from types import MethodType

class CustomParser(argparse.ArgumentParser):
    def __init__(self, *args, **kwrds):
        super(CustomParser, self).__init__(*args, **kwrds)

    def add_argument_group(self, *args, **kwargs):

        def add_enzyme(self):
            self.add_argument(
                 '--enzyme',
                 help="The enzyme to cleave with. Also valid is a"
                 " cleavage pattern such as [KR]|{P}.",
                 choices=protein_config.ENZYMES.keys(), type=str, default='trypsin')

        def add_fasta(self, help="The fasta file to operate on."):
            self.add_argument(
                '-f', '--fasta', nargs='?', help=help, type=argparse.FileType('r'),
                default=sys.stdin)

        def add_out(self, help='The file to write results to. Leave blank for stdout,'):
            self.add_argument(
                '-o', '--out', nargs='?', help=help, type=argparse.FileType('w'),
                default=sys.stdout)

        group = super(CustomParser, self).add_argument_group(*args, **kwargs)
        setattr(group, add_enzyme.__name__, MethodType(add_enzyme, group, type(group)))
        setattr(group, add_fasta.__name__, MethodType(add_fasta, group, type(group)))
        setattr(group, add_out.__name__, MethodType(add_out, group, type(group)))

        #self._action_groups.append(group)

        return group

认为有效,无法真正测试,因为我没有您的依赖项。希望这就是你所需要的。我评论了对self._action_groups.append的呼叫,因为我猜测由于适当的超级呼叫而不需要它。

答案 1 :(得分:0)

您是否尝试使用parents解析器?

import argparse

parent = argparse.ArgumentParser(add_help=False)
group = parent.add_argument_group('standard')
group.add_argument('--enzyme', help="The enzyme to cleave with")
group.add_argument('-f', '--fasta', nargs='?', help='help')
group.add_argument('-o', '--out', nargs='?',type=argparse.FileType('w'))

parser = argparse.ArgumentParser(parents=[parent])
parser.add_argument('--custom')
parser.print_help()

产生

usage: stack21938846.py [-h] [--enzyme ENZYME] [-f [FASTA]] [-o [OUT]]
                        [--custom CUSTOM]

optional arguments:
  -h, --help            show this help message and exit
  --custom CUSTOM

standard:
  --enzyme ENZYME       The enzyme to cleave with
  -f [FASTA], --fasta [FASTA]
                        help
  -o [OUT], --out [OUT]