Pages

Jul 19, 2015

Use Sphinx to automatically create Python documents

Creating program documents is a tedious task. However, with the assistance of automatic tools for creating program documents, we can produce the documents in a very easy and quick way. (We still have to write the comments of program functions.)

Here are the steps of that I used Sphinx to create documents for my python project.

1. Install Sphinx
$ pip install sphinx 


2. Create a directory (folder) for documents
Create a directory named "docs", and the structure of the "docs" and "src" directories is shown below:

Python Project/
  |--------docs/
  |--------src/(source code)


3. Create a Sphinx project
In the docs/ directory, perform the following command:
$ sphinx-quickstart docs


During the process, you will be asked several questions. The following are my answers to some of the questions (empty answer means using the default setting):

Separate source and build directories (y/n) [n]: y
autodoc: automatically insert docstrings from modules (y/n) [n]: y
intersphinx: link between Sphinx documentation of different projects (y/n) [n]: y
ifconfig: conditional inclusion of content based on config values (y/n) [n]: y
viewcode: include links to the source code of documented Python objects (y/n) [n]: y

After step 3 is finished, the structure of the Sphinx project will be that as follows:
Python Project/
  |--------docs/
  |             |----- build
  |             |----- source
  |--------src/(source code)


4. Modify docs/source/conf.py
In the conf.py file created in step 3, find the following comments.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.

Add a setting under the above comments so that Sphinx can find the source code.
sys.path.insert(0, os.path.abspath('../../src/'))


5. Use sphinx-apidoc to create module_name.rst files
$ sphinx-apidoc -o docs/source src


6. Create html files
In the docs directory, perform the following command to create the documents' html files.
$ make html

If the documents are successfully created, you can open the docs/build/html/index.html to read it.


Reference:
http://chimerhapsody.blogspot.com/2014/07/python.html
http://sphinx-doc.org/invocation.html#invocation-of-sphinx-apidoc




No comments:

Post a Comment