1. 程式人生 > >Sphinx-doc編寫文件

Sphinx-doc編寫文件

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.

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風格長這樣:
這裡寫圖片描述
alabaster風格,介面長這樣:
這裡寫圖片描述
sphinx風格,介面長這樣:
這裡寫圖片描述

個人比較喜歡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,顯示內容如下:
這裡寫圖片描述

也可以使用其他的編譯選項,如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-

圖片

sphinx顯示圖片功能,比較弱,無法設定圖片居中等樣式,只能設定圖片寬度,例子如下:

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

標註

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

.. note:: 

    python的字串是不可修改的。如修改一個字元,應使用replace,或使用左邊字串+新字元+右邊字串拼接而成

效果如下:

這裡寫圖片描述

此外,還支援腳註,可以參考文末的入門文件。

外部連結

你使用以下方式來實現內嵌的網頁連結。

`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其他使用文件