Home > python > docopt: a pythonic command line arguments parser that kicks your ass

docopt: a pythonic command line arguments parser that kicks your ass

Docopt is a parser for command line arguments. There are other alternatives like optparse and argparse but docopt is the king. Why? Because it cannot be any simpler :) All you have to do is write an interface description to your script that is well-known from man pages and from the help of other command line applications.

Example (taken from the docopt site):

Naval Fate.

  naval_fate.py ship new <name>...
  naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
  naval_fate.py ship shoot <x> <y>
  naval_fate.py mine (set|remove) <x> <y> [--moored|--drifting]
  naval_fate.py -h | --help
  naval_fate.py --version

  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.

Then you simply pass this string to docopt. When you execute the script, the parameters will be parsed by docopt according to the textual description above. Say you launch this script with the following parameters:

./naval_fate.py ship Guardian move 10 50 --speed=20

Docopt will parse it and return the following dictionary:

{"--drifting": false,
 "--help": false,
 "--moored": false,
 "--speed": "20",
 "--version": false,
 "<name>": ["Guardian"],
 "<x>": "10",
 "<y>": "50",
 "mine": false,
 "move": true,
 "new": false,
 "remove": false,
 "set": false,
 "ship": true,
 "shoot": false}

That’s all. You can try docopt online here.

If you got interested, watch the presentation of its author (you will find it on the top of the home page of the project).

It’s available on GitHub, where you can also check out some more examples.

Usage: either install it via pip, or just simply add the file docopt.py next to your script.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: