65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 Sphinx 进行 Python 文档

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0投票)

2019年9月20日

CPOL

7分钟阅读

viewsIcon

10076

如何使用 Sphinx 进行 Python 文档

引言

作为开发者,我们都知道代码文档的重要性:良好的代码不仅易于理解,而且文档齐全。然而,我们有时也会难以保持文档的最新,尤其是当我们单独维护源代码和文档时。如果我们能够根据源代码生成文档,或者至少根据代码注释生成文档,那么我们就有更大的机会让文档保持最新。

Sphinx 是一个用于从代码构建文档的工具。它支持多种编程语言,但在 Python 项目中被广泛使用,包括官方 Python 网站。Sphinx 官方网站提供了大量有用的信息和参考。然而,对于首次尝试使用 Sphinx 的人来说,官方网站可能会让人感到有些不知所措。至少,这是我第一次尝试使用 Sphinx 时的经历。因此,我写了这篇文章,希望能为 Sphinx 的新手提供一个简单直接的教程。

绘图

本教程将使用一个简单的 Python 项目(示例项目)来演示如何使用 Sphinx 生成基于 HTML 的文档。示例项目 是一个简单的二叉搜索树和二叉树遍历实现。它遵循 NumPy 风格的 docstrings,并做了良好的文档记录。示例项目 的主要目的不仅是作为这个 Sphinx 教程的示例代码,还演示了 NumPy 风格的 docstrings 如何通过 Sphinx 转换为真实的文档。

可以从我的 Github 下载示例项目

$ git clone https://github.com/shunsvineyard/python-sample-code.git 

生成的文档如下图所示

假设和要求

本教程基于以下软件

  • Python 3.7
  • Sphinx 2.2

注意:Sphinx 可以在 Linux 和 Windows 上运行。

如何使用 Sphinx?

Sphinx 使用 reStructuredText 作为其标记语言。Sphinx 生成文档的过程如下:

Project source code (Python or other supported languages) -> 
 reStructuredText files -> documents (HTML or other supported format) 

Sphinx 提供了两个命令行工具:sphinx-quickstartsphinx-apidoc

  • sphinx-quickstart 设置一个源目录,并创建一个默认配置文件 conf.py 和一个主文档文件 index.rst,后者将作为文档的欢迎页面。
  • sphinx-apidoc 为所有找到的模块生成 reStructuredText 文件来记录。

简而言之,我们使用这两个工具来生成 Sphinx 源代码,即 reStructuredText 文件,然后我们修改这些 reStructuredText 文件,最后使用 Sphinx 构建漂亮的文档。

工作流

与需要开发者维护的软件一样,编写软件文档也不是一次性的工作。当软件发生变化时,它需要更新。使用 Sphinx 的工作流程可以视为以下步骤:

上图演示了使用 Sphinx 的基本工作流程,每个步骤的细节将在以下子节中进行说明。

准备

在我们开始使用 Sphinx 之前,我们需要设置我们的工作环境。

在 Linux 上

user@ubuntu:~$ python3 -m venv sphinxvenv
user@ubuntu:~$ source sphinxvenv/bin/activate
(sphinxvenv) user@ubuntu:~$ git clone https://github.com/shunsvineyard/python-sample-code.git
(sphinxvenv) user@ubuntu:~$ cd python-sample-code/
(sphinxvenv) user@ubuntu:~/python-sample-code$ pip install -r requirements.txt

在 Windows 上

c:\Workspace>python -m venv sphinxenv
c:\Workspace>sphinxenv\Scripts\activate
(sphinxenv) c:\Workspace>git clone https://github.com/shunsvineyard/python-sample-code.git
(sphinxenv) c:\Workspace>cd python-sample-code
(sphinxenv) c:\Workspace\python-sample-code>pip install -r requirements.txt

现在,我们有了 示例项目 和 Sphinx 演示的工作环境。因为 示例项目 已经包含了 docs 文件夹,所以我们需要删除它。

删除 docs 文件夹后 示例项目 的布局如下:

python-sample-code
├── LICENSE
├── README.rst
├── binary_trees
│   ├── __init__.py
│   ├── binary_search_tree.py
│   ├── binary_tree.py
│   └── traversal.py
├── pytest.ini
├── requirements.txt
├── setup.py
└── tests
    ├── __init__.py
    ├── conftest.py
    ├── test_binary_search_tree.py
    └── test_traversal.py

步骤 1:使用 sphinx-quickstart 生成包含 conf.py 和 index.rst 的 Sphinx 源目录

假设我们希望将所有与文档相关的文件放在 docs 目录中。因此,我们首先创建一个 Sphinx 文档目录 docs。然后,我们进入 docs 目录并运行 sphinx-quickstart

在 Linux 上

(sphinxvenv) user@ubuntu:~/python-sample-code$ mkdir docs
(sphinxvenv) user@ubuntu:~/python-sample-code$ cd docs/
(sphinxvenv) user@ubuntu:~/python-sample-code/docs$ sphinx-quickstart

在 Windows 上

(sphinxenv) c:\Workspace\python-sample-code>mkdir docs
(sphinxenv) c:\Workspace\python-sample-code>cd docs
(sphinxenv) c:\Workspace\python-sample-code\docs>sphinx-quickstart

运行 sphinx-quickstart 后,它会询问一些关于此项目的问题。以下是这些问题的示例答案:

Welcome to the Sphinx 2.2.0 quickstart utility.

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

Selected root path: .

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

The project name will occur in several places in the built documentation.
> Project name: Sample Project
> Author name(s): Author
> Project release []: 0.1.0

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
https://sphinx-doc.cn/en/master/usage/configuration.html#confval-language.
> Project language [en]:

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.

sphinx-quickstart 的末尾,它会显示如何构建文档。

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.

如果我们在此时运行 make html,Sphinx 将生成包含 示例项目 任何信息的默认文档。输出的预览可以在以下链接查看:

https://htmlpreview.github.io/?https://github.com/shunsvineyard/shunsvineyard/blob/master/use-sphinx-for-python-documentation/step1_output/index.html (上面的预览链接由 https://github.com/htmlpreview/htmlpreview.github.com 提供支持)

注意:Sphinx 不是一个像 Doxygen 那样提供完全自动文档生成功能的工具。sphinx-quickstart 只会生成一些默认文件,例如 index.rstconf.py,其中包含用户提供的基本信息。因此,我们需要做一些工作才能使文档变得实用。

运行 sphinx-quickstart 后,项目的布局如下:

python-sample-code
├── LICENSE
├── README.rst
├── binary_trees
│   ├── __init__.py
│   ├── binary_search_tree.py
│   ├── binary_tree.py
│   └── traversal.py
├── docs
│   ├── Makefile
│   ├── build
│   ├── make.bat
│   └── source
│       ├── _static
│       ├── _templates
│       ├── conf.py
│       └── index.rst
├── pytest.ini
├── requirements.txt
├── setup.py
└── tests
    ├── __init__.py
    ├── conftest.py
    ├── test_binary_search_tree.py
    └── test_traversal.py

请注意,Makefile 适用于 Linux,而 make.bat 适用于 Windows。

步骤 2:配置 conf.py

sphinx-quickstart 生成了几个文件,其中最重要的是 conf.py,它是文档的配置文件。尽管 conf.py 是一个配置文件,但它实际上是一个 Python 文件。conf.py 的内容是 Python 语法。

使用 Sphinx 生成文档是高度可配置的。本节演示了最基本的配置:项目源代码的路径、文档的主题以及添加扩展。

设置项目路径

为了让 Sphinx 能够找到项目,我们需要取消注释这三行:

# import os
# import sys
# sys.path.insert(0, os.path.abspath('.')) 

并更新项目路径:

import os
import sys
sys.path.insert(0, os.path.abspath('../..'))

选择主题

Sphinx 提供了许多内置主题。默认主题是 alabaster

html_theme = 'alabaster'

在本教程中,我们将主题更改为 bizstyle

html_theme = 'bizstyle'

更多主题及其配置可以在 https://sphinx-doc.cn/en/master/usage/theming.html 找到。

添加 NumPy 风格的扩展

示例项目 使用 NumPy 风格的 docstrings。因此,我们需要添加用于解析 NumPy 风格 docstrings 的扩展(napoleon)。

extensions = [
    'sphinx.ext.napoleon'
]

此扩展(napoleon)支持 NumPy 和 Google 风格的 docstrings,并提供了一些可配置的功能。对于示例项目,由于我们使用了 NumPy 风格的 docstrings,我们应该禁用 Google 风格。

napoleon_google_docstring = False

有关 napoleon 的其他设置可以在 https://sphinx-doc.cn/en/master/usage/extensions/napoleon.html#module-sphinx.ext.napoleon 找到。

完整的 conf.py 示例可以在 https://github.com/shunsvineyard/python-sample-code/blob/master/docs/source/conf.py 找到。

此外,Sphinx 还有许多内置扩展,也支持自定义扩展。要了解更多信息,请访问 https://sphinx-doc.cn/en/master/usage/extensions/index.html

现在,我们已经完成了项目的基本配置。接下来,我们将使用 sphinx-apidoc示例项目 源代码生成 reStructuredText 文件。

步骤 3:使用 sphinx-apidoc 从源代码生成 reStructuredText 文件

sphinx-apidoc 是一个用于从源代码(例如 Python 模块)自动生成 reStructuredText 文件的工具。要使用它,请运行:

sphinx-apidoc -f -o <path-to-output> <path-to-module>
  • -f 表示强制覆盖任何已存在的生成文件。
  • -o 表示输出文件的存放路径。

sphinx-apidoc 的完整用法请参见 https://sphinx-doc.cn/en/master/man/sphinx-apidoc.html

在 Linux 上

(sphinxvenv) user@ubuntu:~/python-sample-code/docs$ sphinx-apidoc -f -o source/ ../binary_trees/

在 Windows 上

(sphinxvenv) shunsvineyard@remote-ubuntu:~/python-sample-code/docs$ 
 sphinx-apidoc -f -o source/ ../binary_trees/

示例项目 中,sphinx-apidoc 生成了两个文件:binary_trees.rstmodules.rst。项目的布局如下:

python-sample-code
├── LICENSE
├── README.rst
├── binary_trees
│   ├── __init__.py
│   ├── binary_search_tree.py
│   ├── binary_tree.py
│   └── traversal.py
├── docs
│   ├── Makefile
│   ├── build
│   ├── make.bat
│   └── source
│       ├── _static
│       ├── _templates
│       ├── binary_trees.rst
│       ├── conf.py
│       ├── index.rst
│       └── modules.rst
├── pytest.ini
├── requirements.txt
├── setup.py
└── tests
    ├── __init__.py
    ├── conftest.py
    ├── test_binary_search_tree.py
    └── test_traversal.py

步骤 4:编辑 index.rst 和生成的 reStructuredText 文件

sphinx-quickstart 生成的另一个重要文件是 index.rstindex.rst 是主文档,用作欢迎页面,并包含“目录树”(toctree)的根。在 sphinx-quickstart 创建 index.rst 后,toctree 最初是空的。

.. toctree::
   :maxdepth: 2

将模块添加到 index.rst

生成的 modules.rst 包含所有模块。在此情况下,它只包含 binary_trees。因此,我们需要将 modules.rst 添加到 index.rst 中。

要使文档列表显示在欢迎页面(index.rst)上,请执行以下操作:

.. toctree::
   :maxdepth: 2

   modules

注意:添加另一个 reStructuredText 文件时,请使用不带扩展名的文件名。如果文件存在层级关系,请使用正斜杠“/”作为目录分隔符。

将 README.rst 添加到 index.rst

由于 示例项目 在项目顶层已经有一个 README 文件 README.rst,我们可以将其添加到文档的欢迎页面。

  1. docs/source 下创建一个 readme.rst 文件,并添加行 .. include:: ../../README.rst. (参见 https://github.com/shunsvineyard/python-sample-code/blob/master/docs/source/readme.rst)。
  2. readme 添加到 index.rst 中,以便将其包含在欢迎页面中。

完成这两个步骤后,index.rst 的内容如下:

.. Sample Project documentation master file, created by
   sphinx-quickstart on Sun Sep 15 20:47:59 2019.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to Sample Project's documentation!
==========================================

.. toctree::
   :maxdepth: 2

   readme
   modules

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

完整的示例请参见 https://raw.githubusercontent.com/shunsvineyard/python-sample-code/master/docs/source/index.rst

注意:当我们添加新模块、类、API 或任何影响文档的代码更改时,我们需要重复 步骤 3步骤 4 来更新文档。

步骤 5:构建文档

生成文档的最后一步是发出 make html 命令(如果我们想生成基于 HTML 的文档)。

在 Linux 上

(sphinxvenv) user@ubuntu:~/python-sample-code/docs$ make html

在 Windows 上

(sphinxvenv) shunsvineyard@remote-ubuntu:~/python-sample-code/docs$ make html

运行 make html 命令后,会在 docs 目录下创建一个 build 文件夹。HTML 文档也位于 build/html 目录下。生成的文档如下所示:

预生成的文档也可以在 https://htmlpreview.github.io/?https://github.com/shunsvineyard/shunsvineyard/blob/master/use-sphinx-for-python-documentation/final_output/index.html 查看(请注意,由于 htmlpreview 工具的限制,此预览无法正确渲染页面),或者从 https://github.com/shunsvineyard/shunsvineyard 下载 HTML 文件(位于 shunsvineyard/use-sphinx-for-python-documentation/final_output/)。

结论

尽管我们仍然需要手动编辑生成的 reStructuredText 文件,但 Sphinx 提供了一种更简单的方式来构建漂亮的文档。它还通过 conf.py 和扩展提供了可配置和可扩展的功能。要了解更多关于 Sphinx 的信息,您可以查阅以下在线资源:

历史

  • 2019年9月20日:初始版本
© . All rights reserved.