软件_sphinx排坑教程

之前使用sphinx时,并没写文档,因为的确很容易上手,但使用一段时间才发现,sphinx小坑其实蛮多的。重新梳理下把。
sphinx安装和基本初始化,小白入门可参考第一篇参考文献,里面有较完整的步骤描述。基础步骤并非本文重点,所以做了简化处理。

安装

pip install sphinx sphinx-autobuild sphinx_rtd_theme

初始化:

1
2
3
4
5
# 创建文档根目录
mkdir -p /root/work/scrapy-cookbook
cd scrapy-cookbook/
# 可以回车按默认配置来写
sphinx-quickstart

修改index.rst

index.rst 修改如下:

1
2
3
4
5
Contents:
.. toctree::
:maxdepth: 2

hello

对应文档为source/hello.md

更改主题 sphinx_rtd_theme

更改source/conf.py:

1
2
3
import sphinx_rtd_theme
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]

支持markdown编写:通过recommonmark 来支持markdown

1
pip install recommonmark

本地验证

再push到github之前,可以先本机验证
make clean && make html && python -m http.server –directory build/html/
此时特殊留意是否有报错或警告。如果此时有警告或报错,那么push到github在readthedoc编译后依然会有报错,导致生成的网页不正常。

异常或错误

自动生成文件路径不对

初始化sphinx-quickstart后
应该生成目录结构如下 :

1
2
3
4
5
6
7
8
9
.
├── build
├── make.bat
├── Makefile
└── source
├── conf.py
├── index.rst
├── _static
└── _templates

如果生成的目录结构和上面不一样,说明安装的sphinx版本可能是旧的,升级下即可。(上例的是3.4.3,但3.4存在其他问题,目前使用2.0版本,目录结构同上)

本机可生成build/html,但readthebook无法正确生成文档

原因:本机环境安装了相关依赖,但没写入到requirments.txt文件中,readthebook构建时会从requirments.txt读取依赖包列表,如果没配置完整,会导致build过程中断,无法正确生成文档。
解决将依赖的包,写入到requirments.txt,比如本人requirments.txt

1
2
3
4
sphinx-markdown-tables
sphinx_rtd_theme
recommonmark
sphinx==2.0

生成的文档只有{}一组大括号


此时make html步骤应该有警告,比如

1
WARNING: 目录树引用的文档 'xxx' 缺少标题:不会生成链接

但是打开md看,的确是有标题的。
继续向前看就发现还有其他报错。

1
2
/home/john/opt/sphinx/myproject/source/xxx.md:6: WARNING: Inline literal start-string without end-string.
/home/john/opt/sphinx/myproject/source/xxx.md:10: WARNING: Inline literal start-string without end-string.

这些报错阻碍了md的解析,导致md解析失败,所以没有识别出标题。

这是Sphinx3.4的bug(3.2也有),我回退到2.0就ok了。

报错:SyntaxError:Non-ASCII character ‘\xba’ in file …..py

在*.py文件的第一行添加#coding=UTF-8

报错:Encoding error:’utf8’ codec can’t decode byte 0xc0 in position 44:invalid start byte

确保*.py文件的编码格式为utf-8,通过notepad++可以进行查看,如果不是请修改为utf-8格式

报错:Exception occurred ….return translator[‘sphinx’].ugettext(message) KeyError:’sphinx’

添加sphinx.ext.napoleon后报Exception occurred ….return translator[‘sphinx’].ugettext(message) KeyError:’sphinx’
Sphinx1.3,napoleon扩展使用sphinx.ext.napoleon,Sphinx <= 1.2使用sphinxcontrib.napoleon

参考

使用ReadtheDocs托管文档:https://www.xncoding.com/2017/01/22/fullstack/readthedoc.html
Sphinx快速制作代码文档:https://zhuanlan.zhihu.com/p/102208548
使用sphinx快速为你python注释生成API文档:https://blog.csdn.net/sinat_29957455/article/details/83657029
样例API Reference:https://recommonmark.readthedocs.io/en/latest/api_ref.html

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×