argparse optional subparser (for --version)

前端 未结 7 1383
长情又很酷
长情又很酷 2020-12-09 03:38

I have the following code (using Python 2.7):

# shared command line options, like --version or --verbose
parser_shared = argparse.ArgumentParser(add_help=Fal         


        
7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-09 04:23

    This seems to implement the basic idea of an optional subparser. We parse the standard arguments that apply to all subcommands. Then, if anything is left, we invoke the parser on the rest. The primary arguments are a parent of the subcommand so the -h appears correctly. I plan to enter an interactive prompt if no subcommands are present.

    import argparse
    
    p1 = argparse.ArgumentParser( add_help = False )    
    p1.add_argument( ‘–flag1′ )
    
    p2 = argparse.ArgumentParser( parents = [ p1 ] )
    s = p2.add_subparsers()
    p = s.add_parser( ‘group’ )
    p.set_defaults( group=True )
    
    ( init_ns, remaining ) = p1.parse_known_args( )
    
    if remaining:
        p2.parse_args( args = remaining, namespace=init_ns )
    else:
        print( ‘Enter interactive loop’ )
    
    print( init_ns )
    

提交回复
热议问题