Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Difference between docopt and argparse

Tags:

I have to write a command-line interface and I've seen I can use docopt and argparse.

I would like to know what are the main differences between the two so that I can make an enlightened choice.

Please stick to the facts. I don't want Wow. docopt. So beautiful. Very useful.

like image 746
baldurmen Avatar asked Dec 15 '13 20:12

baldurmen


People also ask

What is Docopt in Python?

Docopt is a command line interface description module. It helps you define a interface for a command-line application and generates parser for it. The interface message in docopt is a formalized help message.

What is the difference between Optparse and Argparse?

One area in which argparse differs from optparse is the treatment of non-optional argument values. While optparse sticks to option parsing, argparse is a full command-line argument parser tool, and handles non-optional arguments as well.

What is Argparse in Python used for?

Python's argparse standard library module is a tool that helps you write command-line interfaces (CLI) over your Python code. You may already be familiar with CLIs: programs like git , ls , grep , and find all expose command-line interfaces that allow you to call an underlying program with specific inputs and options.

Why click instead of Argparse?

Click actually implements its own parsing of arguments and does not use optparse or argparse following the optparse parsing behavior. The reason it's not based on argparse is that argparse does not allow proper nesting of commands by design and has some deficiencies when it comes to POSIX compliant argument handling.


1 Answers

Docopt parses a doc string, whereas argparse constructs its parsing by creating an object instance and adding behaviour to it by function calls.

Example for argparse:

parser = argparse.ArgumentParser() parser.add_argument("operation", help="mathematical operation that will be performed",      choices=['add', 'subtract', 'multiply', 'divide']) parser.add_argument("num1", help="the first number", type=int) parser.add_argument("num2", help="the second number", type=int) args = parser.parse_args() 

Example for docopt:

"""Calculator using docopt  Usage:   calc_docopt.py <operation> <num1> <num2>   calc_docopt.py (-h | --help)  Arguments:   <operation>  Math Operation   <num1>       First Number   <num2>       Second Number  Options:   -h, --help     Show this screen.  """ from docopt import docopt  if __name__ == '__main__':     arguments = docopt(__doc__, version='Calculator with docopt')     print(arguments) 

Note, that docopt uses Usage: and Options: sections for parsing. Here Arguments: is provided only for end-user convenience.

like image 175
jcklie Avatar answered Oct 19 '22 04:10

jcklie