【问题标题】:Python Sphinx: How to embed code into a docstring?Python Sphinx:如何将代码嵌入到文档字符串中?
【发布时间】:2020-10-20 19:19:55
【问题描述】:

如何将代码嵌入到文档字符串中以告诉 Sphinx 格式化代码,就像在 Markdown 中所做的一样(不同的背景颜色,等宽的无字体)?例如记录一个代码使用示例。

""" This is a module documentation

Use this module like this:

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

"""

【问题讨论】:

  • 像这样使用 f-string string = f"""Example {variable_name}"""
  • @Abbas Sphinx 是一个文档渲染引擎。 F弦与它无关。

标签: python python-3.x python-sphinx docstring


【解决方案1】:

There are a few ways to do it。我认为在你的情况下最明智的是.. code-block::

""" This is a module documentation

Use this module like this:

.. code-block:: python

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

"""

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

【讨论】:

    【解决方案2】:

    另一种突出显示代码的方法 (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)
    
    """
    

    :: 可以解决问题。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 2013-06-28
    • 1970-01-01
    • 1970-01-01
    • 2012-05-05
    相关资源
    最近更新 更多