Search code examples
pythoncommand-linedocumentation-generation

Module for Python so that you can generate a free-standing, self-documenting command line utility ala Perl's pod2man/pod2usage?


All I can find is this reference:

Is it possible to use POD(plain old documentation) with Python?

which looks like you have to generate a whole separate set of docs to go with code.

I would like to try Python for making cmdline utils, but when I do this with Perl I can embed the docs directly in the source, and use the Pod2Usage module along with Getopt so that any of my scripts can be run like this:

cmd --man

and this triggers the pod system to dump documentation that is embedded in the script in man-page format. It can also generate shorter (synopsis), or medium formats.

It looks like I could use the pydoc code and kind of reverse engineer it to sort-of do the task (at least showing the full documentation), but I am hoping something better already exists.


Solution

  • The python-modargs package lets you create self-documenting command line interfaces. You define a function for each command you want to make available, and the function's docstring becomes the help text for that function. The function's keyword arguments become named arguments and python-modargs will parse inline comments after the keyword arguments to be help text for that argument.

    I use python-modargs to generate the command line interface for dexy, here is the module which defines the commands: https://github.com/ananelson/dexy/blob/027954f9234363d506225d40b675b3d6478994f4/dexy/commands.py#L144

    You need to implement a help_command method to get the generated help, it's a 1-liner.