简体   繁体   English

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

[英]Python Sphinx: How to embed code into a docstring?

How can I embed code into a docstring to tell Sphinx to format the code similar as it will be done in Markdown (different background colour, monospaced sans font)?如何将代码嵌入到文档字符串中以告诉 Sphinx 将代码格式化为类似于在 Markdown 中完成的代码(不同的背景颜色,等宽无字体)? For example to document a code usage example.例如记录代码使用示例。

""" 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::我认为在你的情况下最明智的是.. code-block::

""" This is a module documentation

Use this module like this:

.. code-block:: python

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

"""

Notice the blank line between the directive and the code block - it must be there in order for the block to render properly.注意指令和代码块之间的空行——它必须在那里才能正确呈现块。

Another way ( see the comment of mzjn on this post ) to get code highlighted is to end with two(!) colons at the line before the code:突出显示代码的另一种方法( 请参阅 mzjn 在这篇文章中的评论)是在代码前的行以两个(!)冒号结尾:

""" This is a module documentation

Use this module like this::

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

"""

The :: does the trick. ::可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Sphinx 在 Python 文档字符串中指示有效范围? - How to indicate a valid range in a Python docstring using Sphinx? 如何在来自 Python 文档字符串的 Sphinx 文档中显示图像? - How do I display an image in Sphinx docs from a Python docstring? 是否可以在Python中将图片嵌入到文档字符串中? - Is it possible embed pictures into docstring in Python? Python:如何在包级别帮助菜单中嵌入所有docstring帮助? - Python: how to embed all docstring help at package level help menu? 如何将代码段添加到python docstring(而不是doctest)? - How to add code snippets to python docstring (not as doctest)? Sphinx autofunction生成没有换行符的python docstring - Sphinx autofunction generate python docstring without newlines 带有 sphinx 新行的 Python 自动文档字符串 - Python auto docstring with sphinx new line 是否有用于收益的 Sphinx reST Python 文档字符串字段? - Is there a Sphinx reST Python docstring field for yields? 在 Sphinx 中使用 Python 文档字符串覆盖和扩展动词 - Using Python docstring override and extend verbs in Sphinx 如何在结合sphinx docstring的numpy docstring中正确添加嵌套列表 - how to correctly add nested list in numpy docstring in combination with sphinx docstring
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM