首页 > 解决方案 > 我可以直接调用 sphinx.parsers.Parser() 并解析 reST 的片段吗?

问题描述

我需要将一个独立的 reST 内容片段解析为一个 doctree(供以后处理)。我可以很容易地通过 docutils 做到这一点,例如:

# ref: http://stackoverflow.com/questions/12883428/

import docutils.nodes
import docutils.parsers.rst
import docutils.utils

def parse_rst(text: str) -> docutils.nodes.document:
    parser = docutils.parsers.rst.Parser()
    components = (docutils.parsers.rst.Parser,)
    settings = docutils.frontend.OptionParser(
    components=components).get_default_values()
    document = docutils.utils.new_document('<rst-doc>', settings=settings)
    parser.parse(text, document)
    return document

class MyVisitor(docutils.nodes.NodeVisitor):

    def visit_reference(self, node: docutils.nodes.reference) -> None:
        """Called for "reference" nodes."""
        print(node)

    def unknown_visit(self, node: docutils.nodes.Node) -> None:
        """Called for all other node types."""
        print(node)

if __name__ == '__main__':
    doc = parse_rst('spam spam lovely spam')
    visitor = MyVisitor(doc)
    doc.walk(visitor)

除非 reST 内容包含特定于 Sphinx 的指令/角色(例如.. glossary:::term:等),否则该方法有效。所以我需要 Sphinx 解析器而不是 docutils 解析器。

我尝试了子类化sphinx.parsers.Parser;使用from sphinx.application import Sphinxthenapp.build()来伪造一个 sphinx docs 项目。

但是参考和解决方法变得复杂,所以我怀疑我以错误的方式接近它。我可以在成熟的sphinx-build工作流程之外使用 sphinx 解析器吗?

标签: pythonparsingpython-sphinx

解决方案


推荐阅读