Include spaces in program name in docopt

212 Views Asked by At

How can one include program names with spaces (like git status) in docopt? I have a setup where a Perl script dispatches a Python script. The Perl script can be called in many ways, let's say for simplicity: prog sub1 sub2. So the Perl script is named prog. It now dispatches the Python script called sub2 using sub2 --progName="prog sub1 sub2" [options]. (So the real program name is not sub2 but prog sub1 sub2). I have tried to implement this scheme using docopt, for example:

"""Usage: %progName% [-h]

Options:
  -h --help
"""

from docopt import docopt
import sys

if __name__ == '__main__':
    progName=sys.argv[0]
    for i, arg in enumerate(sys.argv):
        if arg.startswith('--progName='):
            ind=arg.index("=")+1
            progName=arg[ind:]
            del sys.argv[i]
            break
    doc=__doc__.replace('%progName%',progName)
    args = docopt(doc)
    print(args)

However, this does not work with spaces in the command name (prog sub1 sub2)..

1

There are 1 best solutions below

0
On BEST ANSWER

This can be done using the help=False option combined with the DocoptExit exception:

"""Usage: %progName% [-h]

Options:
  -h --help
"""

from docopt import docopt, DocoptExit
import sys

if __name__ == '__main__':
    progName=sys.argv[0]
    for i, arg in enumerate(sys.argv):
        if arg.startswith('--progName='):
            ind=arg.index("=")+1
            progName=arg[ind:]
            del sys.argv[i]
            break

    usage=False
    try:
        args = docopt(__doc__, help=False)
        if args['--help']:
            usage=True
    except DocoptExit as e:
        usage=True
        print ("Bad arguments!")
    if usage:
        print(__doc__.replace('%progName%',progName))
        raise SystemExit
    print(args)