1.安裝
pip install Sphinx
2.使用
2.1文檔手冊(cè)
Sphinx 1.3.1 中文手冊(cè) (推薦查看)教程https://fengxc.me/基于python注釋使用sphinx自動(dòng)化生成API文檔.html
2.2創(chuàng)建工程
新建一個(gè)文件夾sphinx_test, 并創(chuàng)建兩個(gè)子文件夾code, doc。目錄結(jié)構(gòu)如下:
進(jìn)去到doc目錄, 打開powershell, 執(zhí)行下邊命令創(chuàng)建工程sphinx-quickstart
輸入y,回車
在這里設(shè)置工程名稱、作者、版本信息、語(yǔ)言(中文用zh_CN表示)等
2.3修改配置
打開doc/source/conf.py, 修改一些內(nèi)容
// 如果需要自動(dòng)生成API文檔,sphinx.ext.autodoc這個(gè)很關(guān)鍵
extensions = [
'sphinx.ext.autodoc',
]
// 配置項(xiàng)目路徑:
import os
import sys
sys.path.insert(0, os.path.abspath('../../code')) // 這里的地址是代碼路徑地址 如果code下面有__init__.py文件,則可以路徑為../../。
2.4生成rst文件
在code文件夾中編寫自己的python代碼
使用sphinx-apidoc生成rst文件,-o 后面跟的是保存rst文件的路徑,你的index.rst文件在哪個(gè)目錄,就指定哪個(gè)目錄,然后最后面是代碼路徑
sphinx-apidoc -o ./source ../code
2.5生成html
在doc目錄下,使用make命令生成html文件
使用前,先清除一下之前的生成文件 .\make.bat clean
生成html, (也可以生成pdf和其他的文檔類型) .\make.bat html
這塊有個(gè)紅色的warning,我們后面再來解決這個(gè)問題,先暫且放著。
2.6效果展示
現(xiàn)在我們用瀏覽器打開doc/build/html/index.html,顯示如下:
這是不是和我們平時(shí)看到的python文檔不太一樣,那是因?yàn)槲覀兊闹黝}沒有選對(duì)
2,7改變sphinx主題
安裝主題pip install sphinx_rtd_theme
導(dǎo)入模塊:修改source/conf.py文件
# 導(dǎo)入模塊
import sphinx_rtd_theme
# html_theme = "alabaster"修改如下,加上html_theme_path
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
重新生成html
// 在doc目錄下執(zhí)行
.\make.bat clean
.\make.bat html
效果展示
問題修復(fù)
不知道大家有沒有發(fā)現(xiàn),上面生成的文檔左邊導(dǎo)航欄下面是沒有內(nèi)容CONTENTS的,本來應(yīng)該是像下面這樣的:
還記得上面提到的在make html時(shí)的那個(gè)Warning么,這就是那個(gè)導(dǎo)致的
那個(gè)warning的意思是說,modules.rst沒有被包含,沒有被什么包含呢,是沒有在index.rst里面包含,畢竟我們顯示是用的index.rst。
所以我們需要在index.rst里面加上modules,不知道是不是這個(gè)版本的問題,我在好多教程里面都沒有提到這個(gè),所以踩了個(gè)坑。
修改后如下(source/index.rst):文章來源:http://www.zghlxwxcb.cn/news/detail-817116.html
.. SphinxTest documentation master file, created by
sphinx-quickstart on Mon Jan 8 16:51:13 2024.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to SphinxTest's documentation!
======================================
.. toctree::
:maxdepth: 2
:caption: Contents:
modules
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
之后,再運(yùn)行make clean和make html,則warning消失,頁(yè)面上會(huì)顯示CONTENTS文章來源地址http://www.zghlxwxcb.cn/news/detail-817116.html
到了這里,關(guān)于API文檔生成(sphinx)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!