Permit argparse global flags after subcommand

前端 未结 3 2353
情话喂你
情话喂你 2021-02-19 18:20

I am using argparse to build a command with subcommands:

mycommand [GLOBAL FLAGS] subcommand [FLAGS]

I would like the global flags to work whether they are befor

3条回答
  •  情话喂你
    2021-02-19 18:59

    You are asking for argparse solution, but as you also call for a Pythonic solution, I will deliberately propose an alternative using package docopt:

    get it:

    $ pip install docopt
    

    Write your code into mycommand file:

    """
    Usage:
        mycommand compile [--disable] ...
        mycommand launch  [--disable] ...
    
    Arguments:
          zone name
    
    Options:
      -h --help
      --disable  disable
    
    """
    from docopt import docopt
    
    if __name__ == "__main__":
        args = docopt(__doc__)
        print args
    

    Then call it from command line:

    basic help (no arguments):

    $ python mycommand
    Usage:
        mycommand compile [--disable] ...
        mycommand launch  [--disable] ...
    

    Asking for a help:

    $ python mycommand -h
    Usage:
        mycommand compile [--disable] ...
        mycommand launch  [--disable] ...
    
    Arguments:
          zone name
    
    Options:
      -h --help
      --disable  disable
    

    Using compile subcommand:

    $ python mycommand compile zoneAlfa zoneBeta
    {'--disable': False,
     '': ['zoneAlfa', 'zoneBeta'],
     'compile': True,
     'launch': False}
    

    add flag --disable:

    $ python mycommand compile --disable zoneAlfa zoneBeta
    {'--disable': True,
     '': ['zoneAlfa', 'zoneBeta'],
     'compile': True,
     'launch': False}
    

    launch subcommand works too:

    $ python mycommand launch --disable zoneAlfa zoneBeta
    {'--disable': True,
     '': ['zoneAlfa', 'zoneBeta'],
     'compile': False,
     'launch': True}
    

    My usage of argument parsers started with argparse too, and I hated the complexity of code, which was needed for doing something.

    Later I turned into plac, which is very efficient way for turning a python function into very usable command for console.

    Still, I was limited by set of rules to follow and understand, which were not very clear to me in many cases. With docopt I appreciate, that I can write the docstring first, following standard rules of POSIX, and then use it in my code. If you would care about validation of arguments, I will direct you to samples of this great package.

提交回复
热议问题