Search code examples
pythondocopt

Behaviour of the docopt module (argument parser)


I currently use the docopt lib for the first time so I surely do something wrong

My script is :

"""prog

Usage:
    prog.py (-h | --help)
    prog.py (--version)
    prog.py -s TAG [-t NB_NUC]

Options:
    -h, --help   help
    --version    version
    -s TAG       Some TAG I want.
    -t NB_NUC    A number of nuc.
"""

If I write: python prog.py -s SMT

I get:

{'--help': False,
    '--version': False,
    '-h': False,
    '-s': True,
    '-t': True,
    'NB_NUC': None,
    'TAG': 'SMT'}

And it seems to be correct, but if I write :

python prog.py -s -t 10 -> TAG contain 10 (instead of None)
python prog.py -t 10 -s SMT -> TAG contain always 10 (instead of SMT) and NB_NUC contain SMT (instead of 10)
python prog.py -s SMT -t -> TAG contain SMT and NB_NUC contain None (and its what I expected on this way)

So, I tried lot a combination, but I don't understand how this is supposed to word...

What I want is TAG always contains the values which correspond with the -s argument, with None or an error if nothing is given after -s, and I don't understand why it's not the case..

Thanks for your help !


Solution

  • The problem came from the fact that previous version of docopt didn't work with tabulated indentation. Actual version does, and the PEP8 recommend usage of spaces anyway.

    And for the formating the easiest way is to only write

    Usage:
        prog.py (-h | --help)
        prog.py (-v | --version)
        prog.py [options] <mandatory_file>
    

    And to put the differents options and their descriptions in the Options part.