[置顶] Sphinx-doc编写文档

时间:2022-10-19 06:09:09

sphinx-doc是一种基于python的文档编写工具。python的官方帮助文档就是使用它编写的。sphinx-doc是reStructuredText,即使用带有简单语法的文本文件来编写文件,然后通过编译,可以生成html,epub,man,pdf等多种格式。


plain text VS. WYSIWYG

使用文本文件编写,再使用工具编译生成文档(tex,docbook,sphinx都可算这个阵营),和所见即所得(微软的word,mac的page等)的编写方式相比有啥优缺点呢?

优点

  • 开源跨平台,文本文件任何平台都可以打开,编译工具也可以在任何平台运行
  • 能产生多种格式的文档,甚至可以简单地转为博客的markdown语法
  • 能够生成html等格式,便于发布交流,如发到网上,大家都可以看到了
  • 由于是文本,方便版本控制,也可以加注释,多人编写、合并文档更方便
  • WYSIWYG的编写,如果加载图片多了,会导致越来越卡,而plain text只是include一个文件,编译后才会加载
  • 基于网页的技术可以方便地调整文档格式,编写时可以更加注重内容
  • 插件较多,如特别适合各种代码的插入、语法高亮等

缺点

  • 没有WYSIWYG直观,只能编译后才能生成实际的文档,才能看到效果
  • 国内用word写文档的人比较多

sphinx-doc的安装

sphinx依赖于python,所以要先安装python环境,并安装pip工具,安装方法见 [ python入门系列(2) – python环境搭建 ]

使用pip安装sphinx:

pip install sphinx

创建工程

使用sphinx-quickstart创建工程

安装完sphinx后,会在python的Scripts目录下(C:\Python27\Scripts)产生sphinx-quickstart。确保该目录已经添加到系统环境变量中,然后启动cmd。进入要创建sphinx文档的目录,如 D:\Learn\python, 然后执行下面过程,创建编写Python学习文档的工程,其实设置工程名、作者名、版本号,其他默认就行。我们这里把source和build两个目录分开,因为这样比较方便。

D:\Learn\python>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: Python
> Author name(s): Vincent Yu

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: 1.0.0
> Project release [1.0.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
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]: y

Please indicate if you want to use one of the following Sphinx extensions:
> autodoc: automatically insert docstrings from modules (y/n) [n]:
> 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]: y
> mathjax: include math, rendered in the browser by MathJax (y/n) [n]:
> 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.

D:\Learn\python>

安装完成后,我们可以看到 D:\Learn\python下的文件结构:

│  make.bat                         # window下编译脚本
│ Makefile # Linux下Makefile文件

├─build # make编译后产生的网页目录在build/html目录下
└─source # 文档源码目录
│ conf.py # 配置文件
│ index.rst # 文档源文件入口
├─_static # 编译过程产生的一些图片之类的
└─_templates # 模板

其中,主要看conf.py和index.rst。可以修改conf.py来修改工程配置。index.rst是文档源文件,内容可以在这里添加。我一般会在source那层目录下加一层images目录放图片,code目录用来放源代码,再在index.rst平级目录下,根据章节新建chapter1.rst, chapter2.rst等源文件,用来在index.rst中包含。添加完后目录结构如下:

D:\Learn\python
│ make.bat
│ Makefile

├─build
├─code
1.1.udp.py # 源码文件

├─images
1.1.png # 第一章第一张图片
3.1.png # 第三章第一张图片

└─source
│ chapter1.rst # 第一章文档源文件
│ chapter2.rst # 第二章文档源文件
│ chapter3.rst # 第三章文档源文件
│ conf.py
│ index.rst # 文档源文件入口

├─_static
└─_templates

修改风格

在 conf.py中可以修改 sphinx的风格,还有文档名、作者等。一般使用过sphinx-quickstart创建一个工程后,以后新建工程,可以直接拷贝文件夹,只修改conf.py就行。这里看下常用的风格,

#html_theme = ‘default’
#html_theme = ‘alabaster’
html_theme = ‘sphinxdoc’

default风格长这样:
[置顶]        Sphinx-doc编写文档
alabaster风格,界面长这样:
[置顶]        Sphinx-doc编写文档
sphinx风格,界面长这样:
[置顶]        Sphinx-doc编写文档

个人比较喜欢sphinx的风格。

修改目录结构

我们刚才在目录下已经添加了chapter1.rst, chapter2.rst和chapter3.rst 三个章节的文档源码,但是初建编译时,并不会被编译进去,还得在index.rst中把这些文件包含进来。在rst中配置如下:

Contents:

.. toctree::
:maxdepth: 2
:numbered:

chapter1
chapter2
chapter3

其中,toctree用来于产生目录表,numbered表示章节带标题,maxdepth表示目录中只显示几层标题

编译

在make.bat目录,执行make html,就会在build下产生html的目录,该目录下的网页就是最后生成的文档,入口在index.html,打开index.html,显示内容如下:
[置顶]        Sphinx-doc编写文档

也可以使用其他的编译选项,如make latex, make epub等,其他make latex产生的tex文件,可以用ctex套件中的pdflatex工具进一步产生pdf文件。


常见语法

上面描述了,sphinx的安装和配置。这里开始讲sphinx的一些常见标记语法。注意标记段一般要与前一段落用空行格开,标记段结束要与下一段落用空行格开,部分标记内的参数要与内容用空行格开(如果未加空行,make时一般也会警告)。

段落

段落(ref)是reST文档中最基本的块。段落是由一个或多个空白行分离的简单的文本块。在Python中,缩进在reST中是具有重要意义,所以同一段落的所有行必须左对齐而且是同一级缩进。

标题

上面,我们把每个章节单放在一个独立的rst文件中了,比如chapter1.rst。章节标题即一级标题,一级标题只要在标题名字下面加====就行了,=号的个数要超过标题的长度,否则会告警。几类标题的符号依次如下,使用的方式与一级标题一样:

一级标题: =
二级标题: -
三级标题: +
四级标题: ^

如下面使用例子:

python语言基础语法
=====================


内置数据类型
----------------------

和大多数动态语言一样,python中的变量是动态变量
numbers(数字)
+++++++++++++++


数字的使用跟数学表达式一样:

string(字符串)
++++++++++++++++++++

python通过单引号、双引号或三重引号引起来的表示字符串。

行内标记

标准的行内标记相当简单:使用

单星号:

 *text* 强调 (斜体)

双星号:

**text** 重点强调 (粗体)

反引号:

``text`` 表示引用示例

如果星号或反引号出​​现在文本会对行内标记分隔符引起混淆,他们必须用一个反斜杠进行转义。

注意行内标记一些限制:

  • 不能嵌套,
  • 文本不能以空格开始或者结束: * text* 是不正确的,
  • 必须由空格从周围的文本中分离出来。可以通过使用转义的空格来规避这个限制

代码片断

在sphinx中引用代码非常简单,如果是python代码,直接段落后面加 ::,并留一空行,被引用的代码,还要以tab或等量的空格进行缩进,如下面例子:

python使用如下语法定义listlist的元素类型可以不一样::

>>> a = ['spam', 'eggs', 100, 1234]
>>> a
['spam', 'eggs', 100, 1234]

如果要插入其他的代码,需要显式指明代码类型,如下面例子,说明使用的代码是scheme。添加linenos后,代码每行会显示行号,emphasize-lines配置要高亮的行。

.. code-block:: scheme
:linenos:
:emphasize-lines: 2

(define (linear-combination a b x y)
(+ (* a x) (* b y)))

代码包含

上述是直接是直接把代码片断写在rst文件中的做法。但是我们经常要引用到外部的源代码文件,而不想把源文件中的代码拷来拷去,这时候就可以用到sphinx的代码包含功能,例子如下:

.. literalinclude:: ../code/threading_1.py
:language: python
:linenos:
:lines: 1,3,5-10,20-

显示代码方面的更详细的资料,可以查看 http://www.pythondoc.com/sphinx/markup/code.html

图片

sphinx显示图片功能,比较弱,无法设置图片居中等样式,只能设置图片宽度,例子如下:

.. image:: ../images/1.2.png
:width: 800

标注

sphinx有类似tip功能。例子如下:

.. note:: 

python的字符串是不可修改的。如修改一个字符,应使用replace,或使用左边字串+新字符+右边字串拼接而成

效果如下:

[置顶]        Sphinx-doc编写文档

此外,还支持脚注,可以参考文末的入门文档。

外部链接

你使用以下方式来实现内嵌的网页链接。

`Link text <http://example.com/>`_ 

如果链接文本是Web地址,你一点都不需要特殊标记,解析器可以识别在普通的文本的链接和邮件地址。

你也可以把链接和目标定义(ref)分开,像这样:

This is a paragraph that contains `a link`_.

.. _a link: http://example.com/

列表

使用*号表示一组列表,#.表示有序列表,例子如下:

* This is a bulleted list.
* It has two items, the second
item uses two lines.

1. This is a numbered list.
2. It has two items too.

#. This is a numbered list.
#. It has two items too.

数学公式

在sphinx中可以使用latex语法的公式。插入公式,需要在sphinx-quickstart时,把包含math选项打开。使用的例子如下,sphinx会把产生的公式变成图片,并包含到网页中:

.. math::
\int_a^{b}f=\left[f(a+\dfrac{dx}{2})+f(a+dx+\dfrac{dx}{2})+(f(a+2dx+\dfrac{dx}{2})+\cdots \right]dx

效果如下:

[置顶]        Sphinx-doc编写文档


sphinx其他使用文档

官方文档: http://sphinx-doc.org/contents.html

中文入门:http://www.pythondoc.com/sphinx/rest.html#id15

中文文档 http://zh-sphinx-doc.readthedocs.org/en/latest/contents.html