如何使用sphinx生成python文档时保留换行符

Sau*_*ena 46 python python-sphinx

我正在使用Sphinx为python项目生成文档.输出html不保留docstring中存在的换行符.例:

def testMethod(arg1,arg2):
    """
    This is a test method

    Arguments:
    arg1: arg1 description
    arg2: arg2 description

    Returns:
    None
    """
    print "I am a test method"
Run Code Online (Sandbox Code Playgroud)

狮身人面像O/P:

TestModule.testMethod(arg1, arg2)

This is a test method

Arguments: arg1: arg1 description arg2: arg2 description

Returns: None
Run Code Online (Sandbox Code Playgroud)

知道怎么解决吗?

Owe*_*wen 43

一般来说,在重组文本中使用

| Vertical bars
| like this
Run Code Online (Sandbox Code Playgroud)

保持换行符

  • 不要只是添加| 在两个单独的行上(如果你想要两个换行符)...确保在|后面有2个空格 所以它变为:|(空格)(空格)换行. (9认同)

geo*_*ika 23

如果将以下内容添加到主.rst文件中:

.. |br| raw:: html

   <br />
Run Code Online (Sandbox Code Playgroud)

然后在您的标记中,您可以添加|br|以仅为HTML创建换行符.

I want to break this line here: |br| after the break.
Run Code Online (Sandbox Code Playgroud)

来自:http://docutils.sourceforge.net/FAQ.html#how-to-indicate-a-line-break-or-a-significant-newline

  • 请注意| br | 在文本中需要被空格包围. (3认同)

kar*_*son 15

这个答案来得晚,但也许对其他人来说仍然有用.

您可以reStructuredText在文档字符串中使用.这看起来像

:param arg1: arg1 description
:type arg1: str
:param arg2: arg2 description
:type arg2: str
Run Code Online (Sandbox Code Playgroud)

从您示例的外观来看,您似乎正在使用Google Style for docstrings(http://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=Comments#Comments).

Sphinx本身并不支持这些.然而,有一个扩展名为https://pypi.python.org/pypi/sphinxcontrib-napoleonnapoleon解析Google和Numpy风格的文档字符串.

要使用扩展名,你必须附加'sphinxcontrib.napoleon'extensionSphinx中的-list conf.py(通常doc/source/conf.py),所以它就像是

extensions = [                                                                  
'sphinx.ext.autodoc',                                                       
'sphinxcontrib.napoleon',                                                   
'sphinx.ext.doctest',                                                                                                             
]
Run Code Online (Sandbox Code Playgroud)

  • 从Sphinx 1.3开始,拿破仑扩展将与spinx.ext.napoleon下的Sphinx一起打包.sphinxcontrib.napoleon扩展将继续与Sphinx <= 1.2一起使用. (6认同)

Fra*_*sco 9

在你的情况下你可以写:

def testMethod(arg1,arg2):
  """
  This is a test method

  | Arguments:
  | arg1: arg1 description
  | arg2: arg2 description

  | Returns:
  | None
  """
  print "I am a test method"
Run Code Online (Sandbox Code Playgroud)

  • 这在 Python 3.8 中对我不起作用 (3认同)

小智 5

在我的特定情况下,我试图让autodoc读取文档字符串(""" my doc string """).我最终使用了\n我需要添加换行符的所有地方:

This is the first line\n
and this is the second line\n
Run Code Online (Sandbox Code Playgroud)

  • 当您的文档字符串采用 Google 格式时,您知道如何执行此操作吗? (3认同)