2013-03-12 77 views
1

在我的应用程序时,命令,不能正确解析,我有这样一个解析器:Python的argparse - 使用subparsers和家长

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 

问题为t不知何故,解析命令行失败了,我相信这是我的错,在某个地方。运行时的示例:

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

    my_program.py bootstrap: error: too few arguments 

就好像解析是某种错误。如果在子分析器调用中删除父项= [],此行为会消失,但我宁愿避免它,因为它会产生大量重复。

编辑:在add_argument调用后移动subparsers调用修复了部分问题。不过,现在解析器无法正常解析子:

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

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

回答

2

最根本的问题是,你是混乱的论据是,parser应该处理,与那些在subparsers应该处理。实际上,通过将解析器作为父对象传递给子对象,最终在两个位置定义了这些对象。

此外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)