2013-03-12 22 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)