以编程方式解析具有Sphinx特定指令的.rst文件

Ale*_*kie 7 python docutils python-sphinx

我希望能够在Python中解析基于sphinx的rst进行进一步处理和检查.就像是:

import sphinx
p = sphinx.parse("/path/to/file.rst")
do_something_with(p)
Run Code Online (Sandbox Code Playgroud)

似乎在使用docutils.core.publish_file的docutils中可以实现某些功能:

publish_file(open("/path/to/file.rst")
Run Code Online (Sandbox Code Playgroud)

但是,这对sphinx特定指令等一无所知......

Pra*_*ota 8

您可以使用Sphinx Extensions在最终写入之前执行自定义处理.文档中有一个非常好的入门示例项目,讨论了允许您自定义Sphinx的各种钩子.

根据您要执行的操作,您可能需要将您的do_something函数作为其中一个事件的回调参数提供.

doctree-resolved(app, doctree, docname)
html-page-context(app, pagename, templatename, context, doctree)
Run Code Online (Sandbox Code Playgroud)

然后你可以按如下方式扩展sphinx

def setup(app):
    app.connect('doctree-resolved', do_something)
Run Code Online (Sandbox Code Playgroud)

如果Sphinx教程中的示例不够详细,Doug Hellmann也有一篇关于为Sphinx创建拼写检查器的博客文章.我发现它是我不得不写一段时间的Sphinx扩展的有用参考.