Sphinx扩展获取文件路径时的docutils错误解决方法
解决Sphinx自定义TestDirective路径获取及错误处理问题
核心问题
- 使用
self.state.document.current_source获取文件路径时,处理rst_epilog片段会返回<rst_epilog>而非真实路径 - 直接参考Include类逻辑未做边界判断,触发
IndexError: list index out of range
正确实现代码
from docutils.parsers.rst import Directive from os.path import basename, dirname class TestDirective(Directive): def run(self): # 获取当前源文件路径 source_path = self.state.document.current_source # 处理<rst_epilog>特殊情况,回退到父文档路径 if source_path == '<rst_epilog>': source_path = self.state.parent.document.current_source # 安全提取路径最后两部分,避免索引越界 path_parts = [] current_path = source_path # 循环最多取两级目录/文件名 for _ in range(2): if not current_path: break path_parts.insert(0, basename(current_path)) current_path = dirname(current_path) # 拼接成目标格式的路径片段 display_path = '/'.join(path_parts) # 生成文档节点(示例为添加文本段落) from docutils.nodes import Text, paragraph para_node = paragraph() para_node += Text(f"文档路径片段:{display_path}") return [para_node]
关键逻辑说明
- 特殊路径处理:直接判断路径是否为
<rst_epilog>,切换到父文档的current_source获取真实路径 - 安全路径提取:通过循环逐步向上解析路径,最多取两级,避免直接使用列表切片(如
parts[-2:])在路径过短时触发索引错误 - 兼容短路径场景:如果路径不足两级(比如根目录下的单文件),自动返回现有可用的路径部分,不会报错
验证步骤
- 确认
conf.py中已加载扩展:extensions = ['testdirective'] - 在
source/guides下的rst文件中添加.. test::指令 - 执行Sphinx构建命令后,每个页面会显示路径的最后两级(例如
guides/file1.rst)
内容的提问来源于stack exchange,提问作者lino
相关产品推荐
相关产品推荐

