001.[精华]如何用Sphinx 、GitHub 、ReadtheDocs、搭建写书环境
简介
用 Sphinx 生成文档,GitHub 托管文档,再导入到 ReadtheDocs。
Sphinx 是一个基于 Python 的文档生成工具,最早只是用来生成 Python 官方文档,随着工具的完善,越来越多的知名的项目也用他来生成文档,甚至完全可以用他来写书
引用几点 Sphinx 的优势:* 丰富的输出格式: 支持 HTML (包括 Windows 帮助文档), LaTeX (可以打印 PDF 版本), manual pages(man 文档), 纯文本
完备的交叉引用: 语义化的标签,并可以自动化链接函数,类,引文,术语及相似的片段信息
明晰的分层结构: 可以轻松的定义文档树,并自动化链接同级/父级/下级文章
美观的自动索引: 可自动生成美观的模块索引
精确的语法高亮: 基于 Pygments 自动生成语法高亮
https://zh-sphinx-doc.readthedocs.io/en/latest/contents.html
一个 github 库可以存放多个 Sphinx 工程,在 readthedocs 里,管理-高级设置填写哪个文档下的 conf.py 的路径就可以读哪个文档,也就是说可以在 readthedocs 建立多个项目,每个项目可以填写同一个 github 库,只是每个项目有不同的 conf.py 的路径
详细步骤
搭建环境
bash
mkdir -p /Users/terwer/Documents/mydocs/my-books/introduction-to-liner-algebra-6th-edtion
然后用 pycharm 打开这个目录,设置虚拟 python 环境,我这里选择的 python3。
步骤
bash
Settings -> Project -> Python Interpreter Add Interpreter
然后安装 sphinx
bash
## pip install pipreqs -i https://pypi.tuna.tsinghua.edu.cn/simple ## pipreqs --force pip install -i https://pypi.tuna.tsinghua.edu.cn/simple sphinx pip freeze > requirements.txt ## 更清爽的模式是 pipreqs --force
使用 sphinx-quickstart 创建工程
bash
sphinx-quickstart
记录如下:
(venv) ➜ introduction-to-liner-algebra-6th-edtion sphinx-quickstart 欢迎使用 Sphinx 7.1.0 快速配置工具。 请输入接下来各项设定的值(如果方括号中指定了默认值,直接 按回车即可使用默认值)。 已选择根路径:. 有两种方式来设置用于放置 Sphinx 输出的构建目录: 一是在根路径下创建“_build”目录,二是在根路径下创建“source” 和“build”两个独立的目录。 > 独立的源文件和构建目录(y/n) [n]: y 项目名称将会出现在文档的许多地方。 > 项目名称: introduction-to-liner-algebra-6th-edtion > 作者名称: terwer > 项目发行版本 []: 0.0.1 如果用英语以外的语言编写文档, 你可以在此按语言代码选择语种。 Sphinx 会把内置文本翻译成相应语言的版本。 支持的语言代码列表见: https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-language。 > 项目语种 [en]: zh 正在创建文件 /Users/terwer/Documents/mydocs/my-books/introduction-to-liner-algebra-6th-edtion/source/conf.py。 正在创建文件 /Users/terwer/Documents/mydocs/my-books/introduction-to-liner-algebra-6th-edtion/source/index.rst。 正在创建文件 /Users/terwer/Documents/mydocs/my-books/introduction-to-liner-algebra-6th-edtion/Makefile。 正在创建文件 /Users/terwer/Documents/mydocs/my-books/introduction-to-liner-algebra-6th-edtion/make.bat。 完成:已创建初始目录结构。 你现在可以填写主文档文件 /Users/terwer/Documents/mydocs/my-books/introduction-to-liner-algebra-6th-edtion/source/index.rst 然后创建其他文档源文件了。 像这样用 Makefile 构建文档:   make builder 此处的“builder”代指支持的构建器名称,比如 html、latex 或 linkcheck。
安装后会生成 build 和 source 两个目录
主要看 source 下面的 conf.py 和 index.rst
运行
make html
安装sphinx_rtd_theme主题
bash
pip install sphinx_rtd_theme
调整主题宽度
pip install sphinx-rtd-size
然后
extensions = [ 'sphinx_rtd_size', ] sphinx_rtd_size_width = "100%"
集成Markdown支持
https://www.sphinx-doc.org/en/master/usage/markdown.html
https://myst-parser.readthedocs.io/en/latest/faq/index.html#include-markdown-files-into-an-rst-file