23

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.

Rob Bednark
  • 25,981
  • 23
  • 80
  • 125
baldurmen
  • 669
  • 2
  • 7
  • 15
  • 3
    `argparse` is in the default Python package whereas `docopt` is a separate module. –  Dec 15 '13 at 20:42

3 Answers3

20

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.

Vladimir Keleshev
  • 13,753
  • 17
  • 64
  • 93
jcklie
  • 4,054
  • 3
  • 24
  • 42
  • 2
    After maybe a year of use, I think it's worth mentioning that since docopt is pretty recent and not part of python's core, it may not be available on older systems. i.e, it's not on Debian Wheezy (but is on Jessie). – baldurmen Dec 22 '14 at 06:42
10

The Why page for Click:

https://click.palletsprojects.com/en/7.x/why/

has a nice comparison between argparse, docopt and click itself.

Click is another command-line parsing utility for Python.

AnneTheAgile
  • 9,932
  • 6
  • 52
  • 48
CristianCantoro
  • 722
  • 1
  • 7
  • 17
  • 1
    and theres also why you should not use it... http://xion.io/post/programming/python-dont-use-click.html – Asara Jun 10 '20 at 20:41
7

argparse is in the python default library, so this doesn't add any extra dependencies to your program. The differences are mainly the way of writing your code. Using argparse it is possible to add hooks for plugins so they can add their own argumnets to your program. For example flake8 uses this.

docopt is a third party module provides a simple way of parsing arguments. I personally like docopt because of its simplicity, but I'm not saying it is the best to use in all cases. In their documentation they mention that using docopt it is possible to use more combinations of argument passing than when using argparse.

Remco Haszing
  • 7,178
  • 4
  • 40
  • 83