如何使用 Sphinx 翻译代码块中的注释

How to translate comments in code blocks using Sphinx

我使用 Sphinx 为项目编写文档。我有代码示例(定义为 code-blocks,既包含字面意思,也只是内联输入)。这些代码示例中有注释,但是当我制作文档翻译时,它们没有被提取到 .po 文件中,显然没有被翻译。

如何翻译代码示例中的注释?

我发现了有关 Sphinx 修改的其他问题。答案建议修改 conf.py(制作一些钩子),创建 roleextensions。我以前从来没有这样做过,我不知道从哪里开始,也不知道什么解决方案会更好。这个问题有现成的解决方案吗?

更新。这些是我想在文档中显示的代码示例:

git clone https://github.com/ynikitenko/lena
# most of requirements are for development only
pip install -r lena/requirements.txt

(这里我想翻译评论)。一个更难(也许不是那么需要)的例子是这样的:

class End(object):
    """Stop sequence here."""

    def run(self, flow):
        """Exhaust all preceding flow and stop iteration
        (yield nothing to the following flow).
        """
        for val in flow:
            pass
        return
        # otherwise it won't be a generator
        yield "unreachable"

这些示例使用指令格式化

.. code-block:: 

我写信给来自 Documatt 的 Matt 官方sphinx-users google group, and this is the answer

It's impossible. Sphinx will have to understand comments in every language.

If you want to translate comments in code-block (and literal blocks after ::), you must translate them all. Add gettext_additional_targets = ["literal-block"] to your conf.py and re-run POT/PO update.

代码行保留在代码的“翻译”中,但现在问题已为我解决。