How to parse multiple nested sub-commands using python argparse?

后端 未结 11 1102
执念已碎
执念已碎 2020-11-28 20:52

I am implementing a command line program which has interface like this:

cmd [GLOBAL_OPTIONS] {command [COMMAND_OPTS]} [{command [COMMAND_OPTS]} ...]
<         


        
11条回答
  •  一整个雨季
    2020-11-28 21:29

    You can always split up the command-line yourself (split sys.argv on your command names), and then only pass the portion corresponding to the particular command to parse_args -- You can even use the same Namespace using the namespace keyword if you want.

    Grouping the commandline is easy with itertools.groupby:

    import sys
    import itertools
    import argparse    
    
    mycommands=['cmd1','cmd2','cmd3']
    
    def groupargs(arg,currentarg=[None]):
        if(arg in mycommands):currentarg[0]=arg
        return currentarg[0]
    
    commandlines=[list(args) for cmd,args in intertools.groupby(sys.argv,groupargs)]
    
    #setup parser here...
    parser=argparse.ArgumentParser()
    #...
    
    namespace=argparse.Namespace()
    for cmdline in commandlines:
        parser.parse_args(cmdline,namespace=namespace)
    
    #Now do something with namespace...
    

    untested

提交回复
热议问题