Python argparse子parser从顶级解析器继承选项

Python argparse子parser从顶级解析器继承选项,python,inheritance,argparse,Python,Inheritance,Argparse,我肯定这有答案,但我要么没有正确使用我找到的线程,要么没有找到正确的关键字 我正在试验一个python脚本,我试图为它编写3个子命令,因此我使用了argparse的子parser语法,但我以前没有使用过子parser,我已经用尽了argparse文档中与子命令相关的所有内容。现在,命令都正确注册了,但是,我特别希望传递给顶级解析器的1个必需参数对所有子解析器都可用(每个子命令将作用于相同的输入文件) 这是一个很大的脚本,但这里是argparse部分 def parseArgs(): ""

我肯定这有答案,但我要么没有正确使用我找到的线程,要么没有找到正确的关键字

我正在试验一个python脚本,我试图为它编写3个子命令,因此我使用了
argparse
的子parser语法,但我以前没有使用过子parser,我已经用尽了
argparse
文档中与子命令相关的所有内容。现在,命令都正确注册了,但是,我特别希望传递给顶级解析器的1个必需参数对所有子解析器都可用(每个子命令将作用于相同的输入文件)

这是一个很大的脚本,但这里是argparse部分

def parseArgs():
    """Parse command line arguments. Includes parsing of subcommands."""

    import argparse

    try:
        parser = argparse.ArgumentParser(prog='MSAnalysis',
                                         description="Perform simple tasks with multiple sequence alignments. \n The following subcommands are available:")
        subparsers = parser.add_subparsers(title='Subcommands')
        parser_consensus = subparsers.add_parser('consensus',
                                                 description='Calculate a \'dumb\' consensus via BioPython.',
                                                 help='Computer a consensus sequence from the MSA, at a specifiable threshold.')
        parser_entropy   = subparsers.add_parser('entropy',
                                                 description='Perform calculation of the Shannon entropy per column of an MSA.',
                                                 help='Compute the Shannon entropy, per column of the MSA and return 2 vectors.')
        parser_selection = subparsers.add_parser('selection',
                                                 description='Selection pressure Calculator',
                                                 help='Report dN/dS ratio in either a sliding window or for a whole sequence.')

        # Main parser required options
        parser.add_argument('-a',
                            '--alignment',
                            action='store',
                            required=True,
                            help='The multiple sequence alignment (MSA) in any of the formats supported by Biopython\'s AlignIO.')
        # Main parser options
        parser.add_argument('-f',
                            '--alnformat',
                            action='store',
                            default='fasta',
                            help='Specify the format of the input MSA to be passed in to AlignIO. [Default = fasta].')
        parser.add_argument('-v',
                            '--verbose',
                            action='count',
                            default=1,
                            help='Verbose behaviour, printing parameters of the script and status messages.')
        parser.add_argument('--makeplot',
                            action='store_true',
                            help='Plot the results via Matplotlib.')

        # parser_entropy
        parser_entropy.add_argument('-m',
                                    '--runningmean',
                                    action='store',
                                    type=int,
                                    default=0,
                                    help='Return the running mean (a.k.a moving average) of the MSAs Shannon Entropy. Makes for slightly smoother plots. Providing the number of points to average over switches this on.')

        # parser_consensus
        parser_consensus.add_argument('-c',
                                      '--ambiguous',
                                      action='store',
                                      help='Specify what character default to use for ambiguous characters within alignments.')
        parser_consensus.add_argument('-t',
                                      '--threshold',
                                      action='store',
                                      help='Threshold cut off for the consensus sequence calculation.')

        # parser_dnds options
        parser_selection.add_argument('-p',
                                      '--phylogeny',
                                      action='store',
                                      help='Specify a tree file computed from the supplied alignment for use with PAML.')

    except:
        print "An exception occurred with argument parsing. Check your provided options."
        traceback.print_exc()

    return parser.parse_args()
我希望
共识
选择
能够“继承”
--alignment
变量,因为它是所有变量所必需的输入文件

我尝试将
parents=[parser]
添加到每个子parser,但这似乎破坏了更多东西,我开始得到:

ArgumentError:argument-h/--help:冲突的选项字符串:-h,--help

我猜子parser也继承了父级的
-h
,并导致了问题

根据评论编辑: 我移动了子解析器,但仍然得到一个错误,即需要
-a |--alignment
,即使在指定命令时调用该命令也是如此

def parseArgs():
    """Parse command line arguments. Includes parsing of subcommands."""

    import argparse

    try:
        parser = argparse.ArgumentParser(prog='MSAnalysis',
                                         description="Perform simple tasks with multiple sequence alignments. \n The following subcommands are available:")
        subparsers = parser.add_subparsers(title='Subcommands')

        # Main parser required options
        parser.add_argument('-a',
                            '--alignment',
                            action='store',
                            required=True,
                            help='The multiple sequence alignment (MSA) in any of the formats supported by Biopython\'s AlignIO.')
        # Main parser options
        parser.add_argument('-f',
                            '--alnformat',
                            action='store',
                            default='fasta',
                            help='Specify the format of the input MSA to be passed in to AlignIO. [Default = fasta].')
        parser.add_argument('-v',
                            '--verbose',
                            action='count',
                            default=1,
                            help='Verbose behaviour, printing parameters of the script and status messages.')
        parser.add_argument('--makeplot',
                            action='store_true',
                            help='Plot the results via Matplotlib.')

        # parser_entropy
        parser_entropy   = subparsers.add_parser('entropy',
                                                 description='Perform calculation of the Shannon entropy per column of an MSA.',
                                                 help='Compute the Shannon entropy, per column of the MSA and return 2 vectors.')

        parser_entropy.add_argument('-m',
                                    '--runningmean',
                                    action='store',
                                    type=int,
                                    default=0,
                                    help='Return the running mean (a.k.a moving average) of the MSAs Shannon Entropy. Makes for slightly smoother plots. Providing the number of points to average over switches this on.')

        # parser_consensus
        parser_consensus = subparsers.add_parser('consensus',
                                                 description='Calculate a \'dumb\' consensus via BioPython.',
                                                 help='Computer a consensus sequence from the MSA, at a specifiable threshold.')
        parser_consensus.add_argument('-c',
                                      '--ambiguous',
                                      action='store',
                                      help='Specify what character default to use for ambiguous characters within alignments.')
        parser_consensus.add_argument('-t',
                                      '--threshold',
                                      action='store',
                                      help='Threshold cut off for the consensus sequence calculation.')

        # parser_dnds options
        parser_selection = subparsers.add_parser('selection',
                                                 description='Selection pressure Calculator',
                                                 help='Report dN/dS ratio in either a sliding window or for a whole sequence.')
        parser_selection.add_argument('-p',
                                      '--phylogeny',
                                      action='store',
                                      help='Specify a tree file computed from the supplied alignment for use with PAML.')

    except:
        print "An exception occurred with argument parsing. Check your provided options."
        traceback.print_exc()

    return parser.parse_args()

此外,移动
subparsers=parser.add_subparsers(title='Subcommands')
行到顶级解析器的选项之后(在
--makeplot
参数之后)会导致相同的错误。

我不明白为什么需要将
--alignment
添加到子parsers。无论使用哪个解析器,您提供给主解析器的值都是可用的。通常在使用
parents
时,您必须将
add_help=False
设置为parent或child,因为默认情况下,解析器以
-h
参数开始生命(重复定义是冲突)。一般来说,最好只为这个继承角色定义一个
父级
,而不打算将其用于任何独立角色。在这种情况下,我一定是无意中问了一个XY问题。这就是我认为会发生的事情,但是当我运行代码时,比如:
python MSAnalysis.py entropy-a~/path/to/alignment
我不断得到一个错误,即参数是必需的,即使我已经提供了它。主解析器执行其所有解析,并将其余字符串传递给子解析器。
python stack44812791.py-a test entropy-m 123
适用于最新代码。结果
参数
名称空间(alignment='test',alnformat='fasta',makeplot=False,runningmean=123,verbose=1)
我不明白为什么需要将
--alignment
添加到子parser。无论使用哪个解析器,您提供给主解析器的值都是可用的。通常在使用
parents
时,您必须将
add_help=False
设置为parent或child,因为默认情况下,解析器以
-h
参数开始生命(重复定义是冲突)。一般来说,最好只为这个继承角色定义一个
父级
,而不打算将其用于任何独立角色。在这种情况下,我一定是无意中问了一个XY问题。这就是我认为会发生的事情,但是当我运行代码时,比如:
python MSAnalysis.py entropy-a~/path/to/alignment
我不断得到一个错误,即参数是必需的,即使我已经提供了它。主解析器执行其所有解析,并将其余字符串传递给子解析器。
python stack44812791.py-a test entropy-m 123
适用于最新代码。结果
参数
名称空间(alignment='test',alnformat='fasta',makeplot=False,runningmean=123,verbose=1)