Skip to content
This repository has been archived by the owner on Aug 13, 2020. It is now read-only.

Cómo crear documentación con Sphinx y Read the Docs

Juan Luis Cano Rodríguez edited this page Jan 17, 2016 · 4 revisions

Introducción

Sphinx es una herramienta para crear documentación bonita, navegable y que da gusto usar. El lenguaje en el que normalmente se escribe la documentación para Sphinx es reStructuredText, un lenguaje de marcado potente pero menos popular que Markdown y con una curva de aprendizaje más pronunciada.

El servicio Read the Docs provee alojamiento de documentación hecha con Sphinx de forma gratuita, y será el que usaremos puesto que se puede navegar entre versiones (es por tanto mejor que usar GitHub Pages).

Primeros pasos

Para crear documentación con Sphinx a partir de un proyecto en blanco es necesario instalar el paquete correspondiente y llamar al comando sphinx-quickstart, contestando a algunas preguntas. La mayoría se pueden dejar en blanco, salvo:

  • Separar los directorios source y build: y
  • Usar autodoc: y
  • Usar MathJax: y
$ conda install sphinx -y
$ cd PyFME/docs
$ sphinx-quickstart 
Welcome to the Sphinx 1.3.1 quickstart utility.

Please enter values for the following settings (just press Enter to
accept a default value, if one is given in brackets).

Enter the root path for documentation.
> Root path for the documentation [.]: 

You have two options for placing the build directory for Sphinx output.
Either, you use a directory "_build" within the root path, or you separate
"source" and "build" directories within the root path.
> Separate source and build directories (y/n) [n]: y

Inside the root directory, two more directories will be created; "_templates"
for custom HTML templates and "_static" for custom stylesheets and other static
files. You can enter another prefix (such as ".") to replace the underscore.
> Name prefix for templates and static dir [_]: 

The project name will occur in several places in the built documentation.
> Project name: PyFME
> Author name(s): AeroPython Team

Sphinx has the notion of a "version" and a "release" for the
software. Each version can have multiple releases. For example, for
Python the version is something like 2.5 or 3.0, while the release is
something like 2.5.1 or 3.0a1.  If you don't need this dual structure,
just set both to the same value.
> Project version: 0.1
> Project release [0.1]: 0.1.dev0

If the documents are to be written in a language other than English,
you can select a language here by its language code. Sphinx will then
translate text that it generates into that language.

For a list of supported codes, see
http://sphinx-doc.org/config.html#confval-language.
> Project language [en]: 

The file name suffix for source files. Commonly, this is either ".txt"
or ".rst".  Only files with this suffix are considered documents.
> Source file suffix [.rst]: 

One document is special in that it is considered the top node of the
"contents tree", that is, it is the root of the hierarchical structure
of the documents. Normally, this is "index", but if your "index"
document is a custom template, you can also set this to another filename.
> Name of your master document (without suffix) [index]: 

Sphinx can also add configuration for epub output:
> Do you want to use the epub builder (y/n) [n]: 

Please indicate if you want to use one of the following Sphinx extensions:
> autodoc: automatically insert docstrings from modules (y/n) [n]: y
> doctest: automatically test code snippets in doctest blocks (y/n) [n]: 
> intersphinx: link between Sphinx documentation of different projects (y/n) [n]: 
> todo: write "todo" entries that can be shown or hidden on build (y/n) [n]: 
> coverage: checks for documentation coverage (y/n) [n]: 
> pngmath: include math, rendered as PNG images (y/n) [n]: 
> mathjax: include math, rendered in the browser by MathJax (y/n) [n]: y
> ifconfig: conditional inclusion of content based on config values (y/n) [n]: 
> viewcode: include links to the source code of documented Python objects (y/n) [n]: 

A Makefile and a Windows command file can be generated for you so that you
only have to run e.g. `make html' instead of invoking sphinx-build
directly.
> Create Makefile? (y/n) [y]: 
> Create Windows command file? (y/n) [y]: 

Creating file ./source/conf.py.
Creating file ./source/index.rst.
Creating file ./Makefile.
Creating file ./make.bat.

Finished: An initial directory structure has been created.

You should now populate your master file ./source/index.rst and create other documentation
source files. Use the Makefile to build the docs, like so:
   make builder
where "builder" is one of the supported builders, e.g. html, latex or linkcheck.

Además, con Sphinx viene también un paquete llamado sphinx_rtd_theme, que hace que la documentación coincida con la apariencia de Read the Docs. Para usar este tema hay que cambiar algunas cosas en conf.py:

diff --git a/docs/source/conf.py b/docs/source/conf.py
index 80dddd8..67893f7 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -112,7 +112,8 @@ todo_include_todos = False
 
 # The theme to use for HTML and HTML Help pages.  See the documentation for
 # a list of builtin themes.
-html_theme = 'alabaster'
+import sphinx_rtd_theme
+html_theme = "sphinx_rtd_theme"
 
 # Theme options are theme-specific and customize the look and feel of a theme
 # further.  For a list of options available for each theme, see the

Por último, para que funcione la generación automática con Read the Docs hay que añadir un archivo readthedocs.yml al directorio raíz con la configuración necesaria. Desde enero de 2016 RTD soporta conda, así que lo usaremos también a través de un archivo environment.yml donde estén todas las dependencias:

$ cd PyFME
$ cat readthedocs.yml 
python:
   setup_py_install: true
conda:
    file: environment.yml
$ cat environment.yml 
name: pyfme
dependencies:
  - numpy >=1.7

Creación del contenido

El archivo clave es index.rst, que es el índice de nuestra documentación. El contenido que coloquemos ahí será el que se vea en la página principal. Lo normal es poner una introducción y un índice. Por defecto, index.rst incluye un par de encabezados, un índice vacío, un glosario y otros.

Para añadir secciones al índice, simplemente hay que crear nuevos archivos .rst y listarlos. En general, hay dos tipos de contenido que uno esperaría encontrar en una documentación:

  • Documentación narrativa: guías de instalación, manuales de usuario, tutoriales. Predomina el texto sobre el código y están pensadas para ser leídas de principio a fin e instruir a los usuarios.
  • Referencia: un listado de las funciones y objetos disponibles con una descripción asociada. No aporta información sobre cómo utilizar el software pero sirve para hacer consultas concretas sobre cómo funciona un determinado elemento.

Creando la referencia con autodoc

El código en sí contiene documentación en forma de de docstrings. Para incluir esa información, utilizamos sphinx.ext.autodoc, que hemos activado al crear la configuración. Gracias a esta extensión no tenemos que repetir la información en dos sitios distintos.

Nota: Otra opción es usar la extensión sphinx.ext.autosummary, que simplifica todavía más el proceso. Recomendable cuando el número de objetos es muy grande y el enfoque manual es demasiado lento (no es nuestro caso).

Vamos a añadir una sección llamada api.rst que contenga un apartado por cada paquete de PyFME y una directiva automodule para incluir la documentación de sus módulos y objetos.

Nota: Para que esto funcione, PyFME tiene que estar instalado (por ejemplo haciendo pip install -e PyFME/).

$ cat docs/source/api.rst 
API Reference
=============

`pyfme.environment` package
---------------------------

.. automodule:: pyfme.environment

.. automodule:: pyfme.environment.isa
   :members:

`pyfme.models` package
----------------------

.. automodule:: pyfme.models

.. automodule:: pyfme.models.euler_flat_earth
   :members:

.. automodule:: pyfme.models.system
   :members:

`pyfme.utils` package
---------------------

.. automodule:: pyfme.utils

.. automodule:: pyfme.utils.coordinates
   :members:

Y lo incluimos en el índice:

$ cat docs/source/index.rst
[...]

Contents
--------

.. toctree::
   :maxdepth: 2

   api

[...]

Generar la documentación

Para generar la documentación en formato HTML utilizamos el Makefile que se creó al principio:

$ cd PyFME/docs
$ make html
sphinx-build -b html -d build/doctrees   source build/html
Running Sphinx v1.3.1
making output directory...
loading pickled environment... not yet created
building [mo]: targets for 0 po files that are out of date
building [html]: targets for 2 source files that are out of date
updating environment: 2 added, 0 changed, 0 removed
reading sources... [100%] index                                                 
looking for now-outdated files... none found
pickling environment... done
checking consistency... done
preparing documents... done
writing output... [100%] index                                                  
generating indices... genindex py-modindex
writing additional pages... search
copying static files... done
copying extra files... done
dumping search index in English (code: en) ... done
dumping object inventory... done
build succeeded.

Y si queremos visualizarla podemos lanzar el servidor HTTP de desarrollo que viene con Python:

$ cd build/html
$ python -m http.server &
[1] 8892
Serving HTTP on 0.0.0.0 port 8000 ...
$ 

Y ahora abrimos http://0.0.0.0:8000/ y voilà!