包含带有指令的 Sphinx 的多个 RST 文件 .. include::

问题描述

在我的 Sphinx 项目中,我想要一个包含多个 RST 文件的包含文件夹,我可以在其他项目中重用这些文件。我的源文件夹看起来像:

\source
    \include
         links.rst  # Here I have useful external links
         roles.rst  # Here I define custom roles
         subs.rst   # Here I definne common substitutions (replace directive)
    ... rest of my stuff
    conf.py

基本上,我希望能够在我的源 RST 文件中编写一个 .. include:: 来说明我的所有文件,即相当于 /include/*.rst

我想出了一个简洁的解决方案,我在下面发布,因为它可能对其他人有用。但是,很高兴听到其他替代方案,因为我的解决方案在使用 sphinx-autobuild 时会出现无限循环问题。

解决方法

我的解决方案包括修改 conf.py 以包含这一小段代码:

conf.py

import os

# Code to generate include.rst
files = os.listdir('include')

with open('include.rst','w') as file:
    for rst in files:
        file.write('.. include:: /include/' + rst + '\n')

这将在根源目录中创建一个新的 include.rst 文件,如下所示:

\source
    \include
         links.rst  # Here I have useful external links
         roles.rst  # Here I define custom roles
         subs.rst   # Here I definne common substitutions (replace directive)
    ... rest of my stuff
    conf.py
    include.rst

新文件 include.rst 看起来像:

.. include:: /include/links.rst
.. include:: /include/roles.rst
.. include:: /include/subs.rst

最后,在我的源文件中,我只需要在文件顶部添加一行

.. include:: include.rst

从我所有的自定义链接、角色和替换(或您可能想要的任何其他内容)中受益。

问题: 我在这里的解决方案提出了一个问题。由于我在检测到更改时使用 sphinx-autobuild 自动构建 html 输出,因此会产生无限循环,因为每次执行 conf.py 时都会创建文件 include.rst。关于如何解决这个问题的任何想法?

更新: 我找到了上面提到的问题的解决方案,实际上这很明显。 现在我使用 sphinx-autobuild 选项执行 --re-ignore 为:

> sphinx-autobuild source build/html --re-ignore include.rst

并且循环停止发生。 现在,如果我更改子 rst 文件(即角色、链接或子文件),这是可以的,但是如果 include.rst 发生更改(例如添加了新的子 rst 文件),那么我需要停止并重新运行sphinx-autobuild