首页 > 数据库 > > Sphinx快速制作代码文档
Sphinx 是一种文档工具,它可以令人轻松的撰写出清晰且优美的文档, 由 Georg Brandl 在BSD 许可证下开发. 新版的Python文档就是由Sphinx生成的, 并且它已成为Python项目首选的文档工具,同时它对 C/C++ 项目也有很好的支持; 并计划对其它开发语言添加特殊支持. 本站当然也是使用 Sphinx 生成的,它采用reStructuredText! Sphinx还在继续开发. 下面列出了其良好特性,这些特性在Python官方文档中均有体现:
Sphinx 使用 reStructuredText 作为标记语言, 可以享有 Docutils 为reStructuredText提供的分析,转换等多种工具.
Sphinx为Python语言的一个第三方库。我们需要在终端中输入下列命令进行安装:
pip install sphinx
pip install sphinx_rtd_theme
pip install sphinx-autobuild
pip install recommonmark第一个包是sphinx,第二个包是sphinx的主题包,非常好看。
Sphinx可以嵌入到已有的python项目中,假设现在有一个Python项目名为learn_sphinx,其中源代码均放置于src文件夹. 然后在项目中创建doc文件夹,用于存放文档,然后在该文件夹路径下运行下列命令快速生成Sphinx项目:
cd ./doc
sphinx-quickstart接下来会让你选择一些配置:
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]: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: Sphinx-test
> Author name(s): testSphinx 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]: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]: y
> intersphinx: link between Sphinx documentation of different projects (y/n) [n]: y
> todo: write "todo" entries that can be shown or hidden on build (y/n) [n]: y
> coverage: checks for documentation coverage (y/n) [n]: y
> imgmath: include math, rendered as PNG or SVG images (y/n) [n]: y
> mathjax: include math, rendered in the browser by MathJax (y/n) [n]: y
Note: imgmath and mathjax cannot be enabled at the same time.
imgmath has been deselected.
> 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
> githubpages: create .nojekyll file to publish the document on GitHub pages (y/n) [n]: nA 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]: y
> Create Windows command file? (y/n) [y]: y
Creating file ./conf.py.
Creating file ./index.rst,.md.
Creating file ./Makefile.
Creating file ./make.bat.
Finished: An initial directory structure has been created.
You should now populate your master file ./index.rst,.md 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.项目创建以后, doc的目录结构如下所示:
├── build
├── make.bat
├── Makefile
└── source
├── conf.py
├── index.rst
├── _static
└── _templates其中:
build:用来存放通过make html生成文档网页文件的目录
source:存放用于生成文档的源文件
conf.py: Sphinx的配置文件
index.rst: 主文档主文档index.rst的主要功能是被转换成欢迎页, 它包含一个目录表( “table of contents tree”或者 toctree ). Sphinx 主要功能是使用 reStructuredText 将许多文件组织成一份结构合理的文档.
toctree指令初始值如下:
.. toctree::
:maxdepth: 2你可以在 content 的位置添加文档列表:
.. toctree::
:maxdepth: 2
tutorial.md
...注:tutorial.md 文档文件放在与index.rst同级目录下。
Spinx本身不支持.md文件生成文档,需要我们使用第三方库recommonmark进行转换。 首先分别运行下列命令安装recommonmark与sphinx_rtd_theme库。
pip install recommonmark
pip install sphinx_rtd_theme创建好之后需要对source/conf.py进行配置,使sphinx支持markdown,指定python代码的路径,并添加插件支持生成文档和公式渲染
from recommonmark.parser import CommonMarkParser
source_parsers = {
'.md': CommonMarkParser,
}
source_suffix = ['.rst', '.md']import os
import sys
from recommonmark.parser import CommonMarkParser
sys.path.insert(0, os.path.abspath('../../src'))注意:将path中的src替换你目标文件的名字,例如dmmo文件夹下有所有代码文件,则修改src为dmmo
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.mathjax',
'sphinx.ext.ifconfig',
'sphinx.ext.viewcode',
'sphinx.ext.githubpages',
'sphinxcontrib.fulltoc',
]Sphinx 提供很多主题,去官网选择,你会发现很多主题都是很熟悉,如果你用Python的话。默认是使用Flask一样的主题,找到 html_theme,将参数修改为:
html_theme = 'sphinx_rtd_theme'首先需要在src/文件夹的代码中按照规范添加注释
对于类:注意介绍和参数中间的空行
class Cat:
"""
Cat class A animal #intro
:cvar str name: the cat's name
:cvar int size: the cat's size
:cvar int age: the cat's age
"""
def __init__(self, name, size, age):
"""
class init function
:param str name: cat's name
:param int size: cat's size
:param int age: cat's age
"""
self.name = name
self.size = size
self.age = age对于函数:
def dummy_print(something):
"""
a print function which is the same as the original func
:param str something: a str you want to print
:return: no return
这是一个简单的例子:
Example
-------
>>> dummy_print("hello")
hello
"""
print(something)之后在doc路径下执行:
sphinx-apidoc -f -o ./source ../src/就可以看到在doc/source中得到了对应的.rst文件. (-f 表示是如果已经有之前生成的.rst文件,则会删除重新生成)
在doc文件夹下执行
make clean
make html即可在build/html中得到生成的静态网页文件,默认首页是index.html。 浏览器打开index.html即可看到生成后的文档
你也可以自己编辑一份 markdown页面,然后指定发布。对于没有数学公式和表格的markdown可以直接使用Sphinx对md文件发布。 - 首先编辑一份markdown文档,保存在source文件夹中,命名为newpage.md。 - 然后在index.rst文档中添加该md文档,注意前面的空格数量是3个。
Welcome to learn_sphinx's documentation!
========================================
.. toctree::
:maxdepth: 2
:caption: Contents:
newpage.md
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`然后 make html, 在build/html 页面可以看到newpage.html 的网页,使用浏览器打开即可看到 newpage.md 的网页版。
安装pandoc,在 github 上下载 deb 安装包,然后sudo dpkg -i $DEB安装.
用pandoc手动转换为rst
pandoc -s -t rst --toc newpage.md -o newpage.rst指定sphinx显示rst文件
更改index.rst的内容
Welcome to learn_sphinx's documentation!
========================================
.. toctree::
:maxdepth: 2
:caption: Contents:
newpage.rst然后创建make html, 再访问, 就可以正常显示公式和图表了。
首先在markdown中正常插入图片,不过注意图片的路径需要以source文件夹为基准,例如在source中创建imgs文件夹专门存放图片。
之后正常使用pandoc转换和sphinx发布即可。
来源 https://zhuanlan.zhihu.com/p/102208548
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69999831/viewspace-3125095/ ,如需转载,请注明出处,否则将追究法律责任。