Python Sphinx:如何将代码嵌入文档字符串?

Python Sphinx: How to embed code into a docstring?

我如何将代码嵌入到文档字符串中以告诉 Sphinx 将代码格式化为类似于在 Markdown 中完成的代码(不同的背景颜色,等宽无字体)?例如记录代码使用示例。

""" This is a module documentation

Use this module like this:

   res = aFunction(something, goes, in)
   print(res.avalue)

"""

There are a few ways to do it. I think the most sensible in your case would be .. code-block::

""" This is a module documentation

Use this module like this:

.. code-block:: python

   res = aFunction(something, goes, in)
   print(res.avalue)

"""

注意指令和代码块之间的空白行 - 它必须存在才能使块正确呈现。

另一种 (see the comment of mzjn on this post) 突出显示代码的方法是在代码前一行以两个 (!) 冒号结束:

""" This is a module documentation

Use this module like this::

   res = aFunction(something, goes, in)
   print(res.avalue)

"""

:: 成功了。