1

在我的应用程序中,我有一个这样的解析器:

description = ("Cluster a matrix using bootstrap resampling or "
               "Bayesian hierarchical clustering.")
sub_description = ("Use these commands to cluster data depending on "
                   "the algorithm.")

parser = argparse.ArgumentParser(description=description, add_help=False)
subparsers = parser.add_subparsers(title="Sub-commands",
                                   description=sub_description)
parser.add_argument("--no-logfile", action="store_true", default=False,
                    help="Don't log to file, use stdout")
parser.add_argument("source", metavar="FILE",
                    help="Source data to cluster")
parser.add_argument("destination", metavar="FILE",
                     help="File name for clustering results")

然后我添加了一系列像这样的子解析器(使用函数,因为它们很长):

setup_pvclust_parser(subparsers, parser)
setup_native_parser(subparsers, parser)

这些调用(以一个为例):

def setup_pvclust_parser(subparser, parent=None):

    pvclust_description = ("Perform multiscale bootstrap resampling "
                           "(Shimodaira et al., 2002)")
    pvclust_commands = subparser.add_parser("bootstrap",
        description=pvclust_description, parents=[parent])
     pvclust_commands.add_argument("-b", "--boot", type=int,
                                   metavar="BOOT",
                                   help="Number of permutations",
                                   default=100)

    # Other long list of options...

    pvclust_commands.set_defaults(func=cluster_pvclust) # The function doing the processing

问题是命令行的解析以某种方式失败,我确定这是我的错,在某个地方。运行时的示例:

  my_program.py bootstrap --boot 10 --no-logfile test.txt test.pdf

  my_program.py bootstrap: error: too few arguments

好像解析有点错误。如果我在 subparser 调用中删除 parents=[] ,这种行为就会消失,但我宁愿避免它,因为它会产生大量重复。

编辑:在呼叫解决部分问题subparsers后移动呼叫。add_argument但是,现在解析器无法正确解析子命令:

my_program.py bootstrap --boot 100 --no-logfile test.txt test.pdf

my_program.py: error: invalid choice: 'test.txt' (choose from 'bootstrap', 'native')
4

1 回答 1

3

根本问题是您将parser应该处理的参数与子解析器应该处理的参数混淆了。事实上,通过将解析器作为父级传递给子解析器,您最终会在两个地方定义这些参数。

此外sourcedestination是位置参数,子解析器也是如此。如果它们都在基本解析器中定义,那么它们的顺序很重要。

我建议定义一个单独的parent解析器

parent = argparse.ArgumentParser(add_help=False)
parent.add_argument("--no-logfile", action="store_true". help="...")
parent.add_argument("source", metavar="FILE", help="...")
parent.add_argument("destination", metavar="FILE", help="...")

parser = argparse.ArgumentParser(description=description)
subparsers = parser.add_subparsers(title="Sub-commands", description=sub_description)
setup_pvclust_parser(subparsers, parent)
setup_native_parser(subparsers, parent)
于 2013-09-25T06:39:05.440 回答