Using pydoc for documentation

We use the library module, pydoc, to produce HTML documentation from Python code. It turns out that we're using it when we evaluate help() in interactive Python. This function produces the text mode documentation with no markup.

When we use pydoc to produce the documentation, we'll use it in one of the following ways:

  • Prepare text-mode documentation files and view them with command-line tools such as more or less.
  • Run an HTTP server and browse the documentation directly.

We can run the following command-line tool to prepare the text-based documentation for a module:

pydoc somemodule 

We can also use the following code:

python3 -m pydoc somemodule 

Either command will create text documentation based on the Python code. The output will be displayed with programs such as less (on Linux or macOS) or more (on Windows), which paginate the long stream of output.

Ordinarily, pydoc presumes that we're providing a module name to import. This means that the module must be on the Python path for ordinary import. As an alternative, we can specify a physical filename. Something along the lines of pydoc ./mymodule.py will work to pick a file instead of a module.

The program can also start a special-purpose web server to browse a package or module's documentation. In addition to simply starting the server, we can combine starting the server and launching our default browser. The -b option starts a browser. Here's a way to simply start a server and also launch a browser at the same time:

python3 -m pydoc -b 

This will locate an unused port, start a server, and then launch your default browser to point at the server. 

It's not easy to customize the output from pydoc. The various styles and colors are effectively hardcoded into the class definitions. Revising and expanding pydoc to use the external CSS styles would be an interesting exercise.

The following screenshot shows the default styling:

Now, let's see how to obtain a better output using RST markup.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset