开发“Hello World”扩展

本教程的目标是创建一个添加新指令的非常基本的扩展。此指令将输出包含“hello world”的段落。

本教程仅提供基本信息。有关详细信息,请参阅 other tutorials 这涉及到更多的细节。

警告

对于这个扩展,您需要对 docutils 和 Python 。

概述

我们希望扩展名为sphinx添加以下内容:

  • A helloworld 指令,只输出文本“hello world”。

先决条件

我们不会通过 PyPI 并将其作为现有项目的一部分。这意味着您需要使用现有项目或使用 sphinx-quickstart .

我们假设您使用的是单独的来源 (source )并建立 (build )文件夹。扩展文件可以在项目的任何文件夹中。在我们的例子中,让我们执行以下操作:

  1. 创建一个 _ext 文件夹在 source

  2. 在中创建新的python文件 _ext 文件夹名为 helloworld.py

下面是您可能获得的文件夹结构示例:

└── source
    ├── _ext
    │   └── helloworld.py
    ├── _static
    ├── conf.py
    ├── somefolder
    ├── index.rst
    ├── somefile.rst
    └── someotherfile.rst

正在写入扩展名

正常开放 helloworld.py 并在其中粘贴以下代码:

 1from docutils import nodes
 2from docutils.parsers.rst import Directive
 3
 4from sphinx.application import Sphinx
 5from sphinx.util.typing import ExtensionMetadata
 6
 7
 8class HelloWorld(Directive):
 9    def run(self):
10        paragraph_node = nodes.paragraph(text='Hello World!')
11        return [paragraph_node]
12
13
14def setup(app: Sphinx) -> ExtensionMetadata:
15    app.add_directive('helloworld', HelloWorld)
16
17    return {
18        'version': '0.1',
19        'parallel_read_safe': True,
20        'parallel_write_safe': True,
21    }

在这个例子中发生了一些基本的事情,您将看到它们对于所有的指令。

指令类

我们的新指令在 HelloWorld 班级。

1from sphinx.util.typing import ExtensionMetadata
2
3
4class HelloWorld(Directive):
5    def run(self):

此类扩展了docutils Directive 班级。所有创建指令的扩展都应该扩展这个类。

此类包含 run 方法。这个方法是一个需求,它是每个指令的一部分。它包含指令的主要逻辑,并返回一个由sphinx处理的docutils节点列表。这些节点是docutils表示文档内容的方式。有许多可用的节点类型:文本、段落、引用、表等。

这个 nodes.paragraph 类创建新的段落节点。段落节点通常包含一些文本,我们可以使用 text 参数。

这个 setup 功能

此功能是一项要求。我们用它把新指令插入Sphinx。

 1
 2
 3def setup(app: Sphinx) -> ExtensionMetadata:
 4    app.add_directive('helloworld', HelloWorld)
 5
 6    return {
 7        'version': '0.1',
 8        'parallel_read_safe': True,
 9        'parallel_write_safe': True,
10    }

您可以做的最简单的事情是调用 add_directive() 方法,这就是我们在这里所做的。对于这个特定的调用,第一个参数是REST文件中使用的指令本身的名称。在本例中,我们将使用 helloworld 。例如:

Some intro text here...

.. helloworld::

Some more text here...

我们还将 extension metadata 这表明了扩展的版本,以及使用扩展进行并行读和写是安全的。

使用扩展名

必须在您的 conf.py 归档让Sphinx知道。这里需要两个步骤:

  1. 添加 _ext 目录到 Python path 使用 sys.path.append . 这应该放在文件的顶部。

  2. 更新或创建 extensions 列出扩展名并将其添加到列表中

例如:

import os
import sys

sys.path.append(os.path.abspath("./_ext"))

extensions = ['helloworld']

小技巧

我们不会把这个扩展作为 Python package ,我们需要修改 Python path 所以Sphinx可以找到我们的延伸。这就是为什么我们需要打电话给 sys.path.append .

现在可以在文件中使用扩展名。例如:

Some intro text here...

.. helloworld::

Some more text here...

上述样品将产生:

Some intro text here...

Hello World!

Some more text here...

进一步阅读

这是创建新指令的扩展的基本原则。

有关更高级的示例,请参阅 开发“TODO”扩展 .