Search code examples
pythonargumentsdocopt

Is it possible to redirect docopt --help options to less?


Usually, long documentation available with man are not printed directly on the screen but redirected to less (like man ls for example).

Is it a way to do that with the docopt module in python?


Solution

  • There isn't an official way, but you can do this:

    """
    Usage:
        docopt_hack.py
    """
    
    import docopt, sys, pydoc
    
    def extras(help, version, options, doc):
        if help and any((o.name in ('-h', '--help')) and o.value for o in options):
            pydoc.pager(doc.strip("\n"))
            sys.exit()
        if version and any(o.name == '--version' and o.value for o in options):
            print(version)
            sys.exit()
    
    docopt.extras = extras
    
    # Do your normal call here, but make sure it is after the previous lines
    docopt.docopt(__doc__, version="0.1")
    

    What we do is override the extras function, which handles the printing of the help in normal docopt (https://github.com/docopt/docopt/blob/master/docopt.py#L476-L482). We then use pydoc to push the input into a pager (https://stackoverflow.com/a/18234081/3946766). Note that using pydoc is a non-safe shortcut, as the method is not documented and could be removed. The same goes for extras. YMMV.