Search code examples
pythondocopt

Docopt only proceedes when an optional part is given


I'm trying to learn pythons docopt module and have the following simple script:

""" Usage:
rsnapshot-once [-c CFGFILE] (sync|hourly|daily|monthly)

    -c CFGFILE  specify the configfile that rsnapshot should use
"""

import logging
import sys

from docopt import docopt

args = docopt(__doc__, version='0.0.1-alpha')

logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, formatter=logging.BASIC_FORMAT)
logging.debug("Parsed arguments:\n" + str(args));

if not args.get("-c"):
    args['CFGFILE'] = "/etc/rsnapshot.conf"

When invoked from the command line with the -c option:

% ./rsnapshot-once.py -c someconfigfile sync                                                                
DEBUG:root:Parsed arguments:
{'-c': True,
 'CFGFILE': 'someconfigfile',
 'daily': False,
 'hourly': False,
 'monthly': False,
 'sync': True}

When only the command is passed:

% ./rsnapshot-once.py daily                                                                               
Usage:
        rsnapshot-once [-c CFGFILE] (sync|hourly|daily|monthly)

It seems, that I am misunderstanding something. Could anyone give me a hint, what I'm doing wrong?

Thanks


Solution

  • I got it working. Finally the problem was that I used tabs to format my usage docstring:

    """
    \t\t\tUsage:
    \t\t\trsnapshot-once [-c CFGFILE] (sync|hourly|daily|monthly)
    
    \t\t\tOptions:
    \t\t\t-c CFGFILE        specify the configfile that rsnapshot should use
    """
    

    When I change this to be:

    """
                Usage:
                rsnapshot-once [-c CFGFILE] (sync|hourly|daily|monthly)
    
                Options:
                -c CFGFILE      specify the configfile that rsnapshot should use
    """
    

    It works fine...

    There is a similar issue I found after I figured out what the problem was: https://github.com/docopt/docopt/issues/368

    EDIT: While from a functional point of view, the arguments are parsed correctly when no tabs are used. But in case the call is wrong, only the "Usage:"-Part of the docstring is printed. The "Options:"-Part is not. Can any of you confirm that?

    For example, compare those variants:

    1a. Valid call

    1b. Invalid call(option part is not printed)

    2a. Valid call (but not working)

    2b. Invalid call (Text is printed as expected)