baldurmen baldurmen - 11 days ago 5
Python Question

Python - Difference between docopt and argparse

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


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.


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: <operation> <num1> <num2> (-h | --help)

  <operation>  Math Operation
  <num1>       First Number
  <num2>       Second Number

  -h, --help     Show this screen.

from docopt import docopt

if __name__ == '__main__':
    arguments = docopt(__doc__, version='Calculator with docopt')

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