Search code examples
pythondocopt

Why does docopt exits the script after parsing the parameters?


I use docopt for some time now and on a new script I cannot manage to pass through the argument parsing:

# coding=utf-8
"""
API server for the infoscreen frontends

Usage:
    python3 webserver.py [options]

Options:
    --bind ADDRESS  address to bind to  [default: 0.0.0.0]
    --galarmclock URL  URL for the galarmclock API [default: http://10.100.10.202:8082]
    --loglevel LOG  logging level   [default: logging.DEBUG]
    --console   log to console [default: False]
    --syslog    log to syslog [default: False]

"""

import docopt

# process arguments
args = docopt.docopt(__doc__)
print(args)

All paramters (arguments) are optional and have a default so why does the script stops?

C:\Python3\python.exe C:/tst.py
Usage:
    python3 webserver.py [options]

Process finished with exit code 1

Solution

  • The problem lies in the usage part:

    Usage:
        python3 webserver.py [options]
    

    Docopt expects the first string in the usage part to be your program, and not python. So docopt will interpret this as python3 being your program, and that it always takes a command that is called webserver.py. If you remove the python3 part it should work fine like this:

    Usage:
        webserver.py [options]
    

    From docopt's documentation we have:

    Text occuring between keyword usage: (case-insensitive) and a visibly empty line is interpreted as list of usage patterns. The first word after usage: is interpreted as the program's name.