【Python】Sphinx 文档生成器

目录

1. Sphinx 介绍

2. Sphinx 实战

2.1. 初始化 Sphinx 工程

2.2. 编译项目

2.3. Sphinx 主题

2.4. 增加 Sphinx 文档


1. Sphinx 介绍

Sphinx是一个Python文档生成器,它基于reStructuredText标记语言,可自动根据项目生成HTML,PDF等格式的文档。Sphinx可以令人轻松的撰写出清晰且优美的文档,除了天然支持Python项目以外,Sphinx对C/C++项目也有很好的支持,并在不断增加对其它开发语言的支持 。

如果您需要编写技术文档,可以用reStructuredText或Markdown格式编辑文件,然后使用Sphinx工具转换成html、PDF、ePub等格式,或者托管到GitHub并导入ReadtheDocs网站 。

2. Sphinx 实战

2.1. 初始化 Sphinx 工程

  • 创建项目目录
mkdir sphinx-doc
cd sphinx-doc
  • 初始化命令
sphinx-quickstart
  • 命令输出结果

  • 项目文件结构
│  make.bat
│  Makefile
├─build
└─source
    │  conf.py
    │  index.rst
    ├─_static
    └─_templates

2.2. 编译项目

  • 编译为本地文件
make html

build 目录下生成如下文件

│  make.bat
│  Makefile
├─build
│  ├─doctrees
│  │      environment.pickle
│  │      index.doctree
│  └─html
│      │  .buildinfo
│      │  genindex.html
│      │  index.html  # 这个文件可直接用浏览器打开
│      │  objects.inv
│      │  search.html
│      │  searchindex.js
│      │
│      ├─_sources
│      │      index.rst.txt
│      │
│      └─_static
│              alabaster.css
│              basic.css
│              custom.css
│              doctools.js
│              documentation_options.js
│              file.png
│              jquery-3.5.1.js
│              jquery.js
│              language_data.js
│              minus.png
│              plus.png
│              pygments.css
│              searchtools.js
│              translations.js
│              underscore-1.13.1.js
│              underscore.js
└─source
    │  conf.py
    │  index.rst
    ├─_static
    └─_templates

用浏览器打开 build\html\index.rst 可以看到

  • 编译为 HTTP 服务

make html 的编译方式需要打开 html 文件才能查看,使用如下命令则可以使用 HTTP 服务的形式来查看。

sphinx-autobuild source build/html

命令执行结果为

 可以通过 http://127.0.0.1:8000/ 查看。

2.3. Sphinx 主题

Sphinx 模型主题是 alabaster,可以通过 https://sphinx-themes.org/ 查看 sphinx 更多的主题。

 接下来切换一个比较明显的主题 groundwork-sphinx-theme,打开 source/conf.py 做如下修改

# html_theme = 'alabaster'
html_theme = 'groundwork'

2.4. 增加 Sphinx 文档

  • 新的项目文件结构如下
│  make.bat
│  Makefile
└─source
    │  conf.py
    │  index.rst
    ├─_static
    ├─_templates
    └─文章
        │  index.rst
        ├─第一章
        │      index.rst
        └─第二章
                index.rst

预览结果如下:

3. 项目源码

https://gitee.com/hl0929/sphinx-doc.git

猜你喜欢

转载自blog.csdn.net/u014147522/article/details/131518235