4

I'm trying to display all the help message with docopt, without adding the --help argument.

For example this is from the official doc :

"""
Naval Fate.

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

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

from docopt import docopt
arguments = docopt(__doc__, version=1)

If I call the script without argument, docopt displays the usage part :

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

And I must explicitly set the --help argument to see the full help :

$ python foo.py --help
Naval Fate.

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

Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine. 
ncrocfer
  • 2,542
  • 4
  • 33
  • 38

3 Answers3

3

Catching the DocoptExit should work. Like this:

"""
Naval Fate.

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

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

from docopt import docopt, DocoptExit
try:
    arguments = docopt(__doc__, version=1)
except DocoptExit:
    print __doc__
J. P. Petersen
  • 4,871
  • 4
  • 33
  • 33
1

Another option that works just as well as the one shown in J. P. Petersen's answer is this:

import sys

# ...

if len(sys.argv) == 1: # i.e just the program name
    sys.argv.append('-h')

arguments = docopt(__doc__, version=1)

Now, when you run python foo.py, you get the full help screen.

Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88
0

I always scratched my head wondering why this isn't the default behavior and finally opened a bug for this question:

https://github.com/docopt/docopt/issues/410

Let see what appends...

Bruno Duyé
  • 1,014
  • 11
  • 13