Python command-line parsing library--argarse, docopt, click, invoke

Source: Internet
Author: User

Command-line Example:

Basic usage

$ python [file].py hello Kylehello, kyle!$ python [file].py goodbye Kylegoodbye, kyle!

w/option usage (flags)

$ python [file].py Hello--greeting=wazzup kylewhazzup, kyle!$ python [file].py goodbye--greeting=later Kylelater, Kyle!$ Python [file].py Hello--caps kylehello, kyle!$ python [file].py hello--greeting=wazzup--caps kylewazzup, kyle!

Argarse: Standard Library

Def greet (args):    output =  ' {0}, {1}! '. Format (args.greeting, args.name)     if args.caps:         output = output.upper ()     print (output) parser =  Argparse. Argumentparser () parser.add_argument ('--version ',  action= ' version ',  version= ' 1.0.0 ') subparsers =  parser.add_subparsers () hello_parser = subparsers.add_parser (' Hello ') hello_parser.add_argument ( ' Name ',  help= ' Name of the person to greet ') hello_parser.add_argument ('-- Greeting ',  default= ' Hello ',  help= ' word to use for the greeting ') hello_ Parser.add_argument ('--caps ',  action= ' store_true ',  help= ' uppercase the output ') hello_ Parser.set_defaults (Func=greet) Goodbye_parser = subparsers.add_parser (' Goodbye ') goodbye_parser.add_ Argument (' name ',  help= ' Name of the&nbsP;person to greet ') goodbye_parser.add_argument ('--greeting ',  default= ' Hello ',  help= ' word  to use for the greeting ') goodbye_parser.add_argument ('--caps ',  action= ' store_ True ',  help= ' Uppercase the output ') goodbye_parser.set_defaults (func=greet) if __name__  ==  ' __main__ ':     args = parser.parse_args ()      Args.func (args)

Docopt

"" "USAGE:&NBSP;GREET&NBSP;[--HELP]&NBSP;&LT;COMMAND&GT;&NBSP;[&LT;ARGS&GT; options:  -h --help         show this  screen.  --version         show the  version.commands:   hello       say hello    goodbye     say goodbye "" "From docopt import docoptfrom  schema import Schema, SchemaError, OptionalHELLO =  "" "usage: basic.py  hello [options] [<name>]  -h --help          Show this screen.  --caps             Uppercase the output.  --greeting=<str>   Greeting to use [default: hello]. "" " goodbye =  "" "usage: basic.py goodbye [options] [<name>]  -h --help          Show this screen.  --caps             uppercase the output.  -- Greeting=<str>  greeting to use [default: goodbye]. "" " Def greet (args):    output =  ' {0}, {1}! '. Format (args['--greeting '],                                  args[' <name> ')     if args['--caps ']:         output = output.upper ()     print (output) if __name__ ==  ' __ Main__ ':     arguments = docopt (__DOC__,&NBsp;options_first=true, version= ' 1.0.0 ')     schema = schema ({         optional (' Hello '): bool,         optional (' goodbye '): bool,         ' <name> ':  str,         optional ('--caps '): bool,         optional ('--help '):  bool,        optional ('-- Greeting '):  str    })     def validate (args):         try:             args = schema.validate (args)              return args        except schemaerror as e:              exit (e)     if arguments[' <command> ']  ==  ' Hello ':         greet (Validate (docopt (hello))      elif arguments[' <command> '] ==  ' Goodbye ':         greet (Validate (Docopt (GOODBYE))     else:         exit ("{0} is not a command. see  ' options.py --help '."). Format (arguments[' <command> '))

Click

Import clickcontext_settings = dict (help_option_names=['-h ',  '--help ']) def greeter (* * Kwargs):    output =  ' {0}, {1}! '. Format (kwargs[' greeting '],                                  kwargs[' name '])     if kwargs[' caps ']:         Output = output.upper ()     print (output) @click. Group (Context_settings=context_ SETTINGS) @click. Version_option (version= ' 1.0.0 ') Def greet ():     pass@greet.command () @ Click.argument (' name ') @click. Option ('--greeting ',  default= ' Hello ',  help= ' word to use  For the greeting ') @click. Option ('--caps ',  is_flag=true, help= ' uppercase the  Output ') Def hello (**kwargs):     greeter (**kwargs) @greet. Command () @click. argument (' name ') @click. Option ('--greeting ',  default= ' Goodbye ',  help= ' word to use for the greeting ') @click. Option ('--caps ', is_flag=true,  help= ' Uppercase the output ') Def goodbye (**kwargs):     greeter (**kwargs) if  __name__ ==  ' __main__ ':     greet ()

Invoke

From invoke import taskdef greet (name, greeting, caps):     output =  ' {0}, {1}! '. Format (greeting, name)     if caps:         output = output.upper ()     print (output) help = {      ' name ':  ' name of the person to greet ',     ' Greeting ':  ' word to use for the greeting ',     ' caps ':  ' Uppercase the output '}def print_version ():     print (' 1.0.0 ')      exit (0) @task (help=help) Def hello (name= ",  greeting= ' Hello ', caps=false,  Version=false):     "" "    Say hello.    " ""     if version:        print_version ()     greet (name, greeting, caps) @task (help=help) Def goodbye (name= ",  greeting = ' Goodbye ',  caps=false, version=false):     "" "    Say  goodbye.     "" "    if version:         print_version ()     greet (name, greeting, caps)

There are three common cases of error handling:

1, insufficient parameters.

2. Invalid option/flag.

3, need to flag to a value.

Argparse

$ python argparse/final.py hellousage:final.py Hello [-h] [--greeting greeting] [--caps] namefinal.py hello:error:the F ollowing arguments is required:name$ python argparse/final.py--badoption Hello Kyleusage:final.py [-h] [--version] {He Llo,goodbye} ... final.py:error:unrecognized arguments:--badoption$ python argparse/final.py Hello--caps=notanoption  Kyleusage:final.py Hello [-h] [--greeting greeting] [--caps] namefinal.py hello:error:argument--caps:ignored Explicit Argument ' notanoption '

Docopt, need to use scheme

... from schema import schema, schemaerror, optional...    schema  = schema ({        optional (' hello '): bool,         optional (' Goodbye '): bool,          ' <name> ':  str,        optional ('--caps '):  bool,         optional ('--help '): bool,         optional ('--greeting '):  str    })     def  Validate (args):        try:             args = schema.validate (args)              return args        except  Schemaerror as&nBsp;e:            exit (e)      if arguments[' <command> '] ==  ' Hello ':         Greet (Validate (Docopt (HELLO))     elif arguments[' <command> '] ==  ' Goodbye ':         greet (Validate (Docopt (Goodbye))) ... $ python  docopt/validation.py helloNone should be instance of <class  ' str ' >$ python docopt/validation.py hello --greeting KyleNone should be  instance of <class  ' str ' >$ python docopt/validation.py hello --caps= Notanoption kyle--caps must not have an argumentusage: basic.py hello  [options] [<name>]

Click

$ python click/final.py helloUsage:final.py hello [OPTIONS] nameerror:missing argument "name". $ python click/final.py He Llo--badoption kyleerror:no Such option:--badoption$ python click/final.py Hello--caps=notanoption kyleerror:--caps o Ption does not take a value

Packaged

Entry_point is essentially a mapping to a single function of code, and the system path will give you a command. Entry_point is in the form of command = Package.module:function

Package Click Command

greeter/├──greet│├──__init__.py│└──cli.py <--the same as our final.py└──setup.py
entry_points={' console_scripts ': [' Greet=greet.cli:greet ', # Command=package.module:function],},

When a user installs a package created by Entry_point, Setuptools creates the following executable script (called greet) and places it on the user's system path.

#!/usr/bin/pythonif __name__ = = ' __main__ ': Import sys from GREET.CLI import greet Sys.exit (greet ())

Packing Argparse Command

Code:

if __name__ = = ' __main__ ': args = Parser.parse_args () args.func (args)

Become:

def greet (): args = Parser.parse_args () args.func (args) if __name__ = = ' __main__ ': Greet ()

For Entry_point, we can now use the same pattern as defined in click.


Packing docopt Command

Code:

if __name__ = = ' __main__ ': arguments = docopt (__doc__, options_first=true, version= ' 1.0.0 ') if arguments[' <comman d> ' = = ' Hello ': Greet (docopt (hello)) elif arguments[' <command> '] = = ' goodbye ': Greet (docopt (GOO Dbye)) Else:exit ("{0} is not a command. See ' options.py--help '. Format (arguments[' <command> '))

Become:

def greet (): arguments = docopt (__doc__, options_first=true, version= ' 1.0.0 ') if arguments[' <command> ' = = ' He Llo ': Greet (docopt (HELLO)) elif arguments[' <command> '] = = ' goodbye ': Greet (docopt (Goodbye)) Else : Exit ("{0} is not a command. See ' options.py--help '. Format (arguments[' <command> '])) if __name__ = = ' __main__ ': Greet ()


Python command-line parsing library--argarse, docopt, click, invoke

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.