如何修复Sphinx中“Unexpected section title”报错?
解决Sphinx识别自定义文档章节标题或屏蔽报错的问题
问题场景
文档字符串示例
""" Returns ------- out: int Output. Bad title --------- Text. """
构建报错信息
C:\module.py:docstring of my_pkg.module.func:5: CRITICAL: Unexpected section title. Bad title ---------
环境说明
仅启用sphinx.ext.autodoc扩展,未使用numpydoc或Napoleon扩展,执行命令sphinx-build -a -E . build构建文档时触发上述报错,需求为:让Sphinx识别自定义章节标题“Bad title”,或屏蔽该报错。
解决方案
方案1:让Sphinx识别自定义章节标题
Sphinx默认仅支持预设的文档章节标题(如Returns、Parameters),要让它识别自定义标题,需修改Sphinx配置文件conf.py,通过自定义事件处理器处理自定义章节:
在conf.py中添加以下代码:
def setup(app): app.connect('autodoc-process-docstring', process_custom_sections) def process_custom_sections(app, what, name, obj, options, lines): custom_sections = ["Bad title"] i = 0 while i < len(lines): line = lines[i].strip() if line in custom_sections and i + 1 < len(lines): if lines[i+1].strip() == "-" * len(line): # 将自定义标题转为Sphinx支持的rubric小标题格式 lines[i] = f".. rubric:: {line}" del lines[i+1] i -= 1 # 删除行后调整索引 i += 1
这段代码会把自定义章节标题转换为Sphinx可识别的格式,同时保留章节内容,不会触发报错。
方案2:屏蔽“Unexpected section title”报错
若无需渲染自定义章节,仅需屏蔽报错,可采用以下两种精准方式:
方法A:过滤特定报错日志
在conf.py中添加自定义日志过滤器,仅屏蔽目标报错:
import logging from sphinx.util import logging as sphinx_logging class CustomErrorFilter(logging.Filter): def filter(self, record): # 过滤包含指定内容的CRITICAL级日志 return not (record.levelno == logging.CRITICAL and "Unexpected section title" in record.getMessage()) # 给Sphinx日志器添加过滤器 sphinx_logger = sphinx_logging.getLogger('sphinx') sphinx_logger.addFilter(CustomErrorFilter())
方法B:临时降低日志级别
若允许屏蔽所有CRITICAL级日志,可在conf.py中添加:
import logging logging.basicConfig() logging.getLogger('sphinx').setLevel(logging.ERROR)
注意:此方法会屏蔽所有CRITICAL级日志,可能错过其他重要报错信息。
内容的提问来源于stack exchange,提问作者OverLordGoldDragon
相关产品推荐
相关产品推荐

