如何在Sphinx扩展节点中读取conf.py设置?

时间:2013-02-16 20:18:26

标签: python configuration-files python-sphinx

from docutils.parsers.rst.directives.images import Figure
class MyFigure(Figure):
    def run(self):
        # here I need to read the 'thumbnails_folder' setting
        pass

def setup(app):
    app.add_config_value('thumbnails_folder', '_thumbnails', 'env')

如何在.run()中访问配置值?我阅读了Sphinx-contrib的sources,但没有按照我的方式看待事情,所以他们以我不能的方式访问conf.py。或者我应该以不同的方式做到这一点?

我想做的就是翻译这个

.. figure:: image/image.jpg

进入这个:

.. image:: image/thumbnails/image.jpg
   :target: image/image.jpg

Here's the extension code

(使用PIL生成缩略图)。并将:target:放入可下载的文件中(正如我所见,只有构建器实例可以执行此操作)。

1 个答案:

答案 0 :(得分:3)

构建环境(请参阅this page)包含对Config对象的引用。可以从此对象检索配置变量:

def run(self):
    env = self.state.document.settings.env  # sphinx.environment.BuildEnvironment 
    config = env.config                     # sphinx.config.Config
    folder = config["thumbnails_folder"] 
    ...