如何用Sphinx自动生成Python示例脚本的叙事式文档?
解决方案:用Sphinx生成带叙事注释的可执行示例文档
针对你需要保留可执行脚本、用#:注释生成叙事文档且避免代码重复的需求,以下是几种实用的自动化方法:
1. 用Sphinx原生literalinclude指令(零额外依赖)
Sphinx的literalinclude支持精准提取脚本内容,并配合注释生成叙事结构:
- 示例脚本写法(保留可执行性):
#: 步骤1:初始化库核心对象 from my_lib import CoreClass core = CoreClass() #: 步骤2:调用核心方法处理测试数据 result = core.process_data({"sample": "data"}) #: 步骤3:验证输出格式合法性 assert isinstance(result, dict), "输出格式错误" - 在Sphinx的
.rst文档中,按步骤拆分渲染:
这种方式直接引用仓库脚本,完全避免代码重复,且# 示例:核心功能使用流程 .. note:: 以下代码均来自仓库中可直接执行的脚本文件 #: 步骤1:初始化库核心对象 .. literalinclude:: ../scripts/core_example.py :start-at: from my_lib import CoreClass :end-at: core = CoreClass() :dedent: 0 #: 步骤2:调用核心方法处理测试数据 .. literalinclude:: ../scripts/core_example.py :start-at: result = core.process_data :end-at: result = core.process_data({"sample": "data"}) :dedent: 0 #: 步骤3:验证输出格式合法性 .. literalinclude:: ../scripts/core_example.py :start-at: assert isinstance(result, dict) :end-at: assert isinstance(result, dict), "输出格式错误" :dedent: 0#:注释作为文档叙事节点,代码块自动对应。
2. 使用sphinx-examples扩展(专为示例文档设计)
这个扩展专门处理可执行示例,能自动解析脚本中的#:注释为文档段落,自动生成“说明+代码”的叙事结构:
- 配置:在
conf.py中添加扩展:extensions = [ # 其他扩展 "sphinx_examples" ] - 脚本写法和之前一致,无需修改;在
.rst文档中仅需一行指令:
扩展会自动提取所有.. example:: ../scripts/core_example.py#:注释作为段落,后续代码块紧跟对应说明,生成连贯的叙事文档,同时保留脚本的可执行性。
3. 自定义预处理脚本(完全可控)
如果需要更灵活的格式控制,可以写一个简单的Python脚本,批量提取#:注释和对应代码,生成Sphinx可识别的.rst片段:
- 预处理脚本示例:
def script_to_rst(script_path, rst_output_path): with open(script_path, "r", encoding="utf-8") as f: lines = f.readlines() rst_sections = [] current_code = [] for line in lines: stripped_line = line.strip() if stripped_line.startswith("#:"): # 先输出之前积累的代码块 if current_code: code_block = ".. code-block:: python\n " + " ".join(current_code) rst_sections.append(code_block) current_code = [] # 添加注释作为文档段落 rst_sections.append(stripped_line[2:].strip()) elif stripped_line and not stripped_line.startswith("#"): # 积累非注释、非空的代码行 current_code.append(line) # 处理最后一段代码 if current_code: code_block = ".. code-block:: python\n " + " ".join(current_code) rst_sections.append(code_block) # 写入rst文件 with open(rst_output_path, "w", encoding="utf-8") as f: f.write("\n\n".join(rst_sections)) # 调用示例 script_to_rst("../scripts/core_example.py", "../docs/source/core_example.rst") - 在Sphinx主文档中引入生成的片段:
每次构建文档前运行该预处理脚本即可,完全自定义输出格式。.. include:: core_example.rst
关键优势
- 所有方法均保留脚本的可执行性,无需修改脚本结构。
- 完全避免代码重复,所有代码内容直接引用仓库中的原始脚本。
- 把
#:注释转化为可读的叙事文档,替代viewcode仅展示代码的局限。
内容的提问来源于stack exchange,提问作者Joce
相关产品推荐
相关产品推荐

