ARGPARSE Newbie question

paulclarke345 at gmail.com paulclarke345 at gmail.com
Tue Apr 17 21:08:37 EDT 2018


On Tuesday, April 17, 2018 at 7:09:45 PM UTC-5, TUA wrote:
> I'd like to create a script that handles a number of verbs with mandatory and /or optional parameters like listed in the table below.
> 
> Can ARGPARSE do this and how?
> 
> Thanks for all help!
> 
> 
> 
> 
> 
> Script      Verb        Mandatory parameters                         Optional parameters 
> ------------------------------------------------------------------------------
> myprog.py   list        ---                                          verbose 
> 
> myprog.py   add         sid(string), type (string), memory (int)     comment (string), autostart (bool, default=TRUE)
> 
> myprog.py   memory      sid (string), memory (integer)
> 
> myprog.py   comment     sid(string), comment (string)
> 
> myprog.py   restore     sid(string), srcpath (string)
> 
> myprog.py   backup      sid(string), dstpath(string) 
> 
> myprog.py   remove      sid (string)

you can use subparsers for this. The syntax goes something like this:

    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers(dest='subparser_name')
    list_parser = subparsers.add_parser("list", help="help for list")
    list_parse.add_argument("-v", "--verbose", help="show verbose output",
                          action="store_true")
    add_parser = subparsers.add_parser("add", help="help for add")
    add.add_argument("sid", type=str, help="help for sid")
...
etc. see the documentation on argparse for more on this.



More information about the Python-list mailing list