强制Sphinx用Python文档字符串而不是reStructuredText解释Markdown [英] Force Sphinx to interpret Markdown in Python docstrings instead of reStructuredText
问题描述
我正在使用Sphinx记录python项目.我想在我的文档字符串中使用Markdown格式化它们. 即使我使用recommonmark
扩展名,它也仅涵盖手动编写的.md
文件,而不包括文档字符串.
I'm using Sphinx to document a python project. I would like to use Markdown in my docstrings to format them. Even if I use the recommonmark
extension, it only covers the .md
files written manually, not the docstrings.
我在扩展程序中使用autodoc
,napoleon
和recommonmark
.
I use autodoc
, napoleon
and recommonmark
in my extensions.
如何在我的文档字符串中<使狮身人面像解析降价?
How can I make sphinx parse markdown in my docstrings?
推荐答案
Sphinx's autodoc
extension emits an event named autodoc-process-docstring
every time it processes a doc-string. You can hook into that mechanism to convert the syntax from Markdown to reStructuredText.
我不知道为什么 recommonmark
不能立即提供该功能.它应该是一个容易添加的功能.就个人而言,我在项目中使用 m2r
进行转换.因为它很快-比例如 pandoc
快得多.速度很重要,因为转换是即时进行的,并分别处理每个文档字符串.除此之外,任何Markdown-to-reST转换器都可以.
I do not know why recommonmark
does not offer that functionality out of the box. It should be an easy feature to add. Personally, I use m2r
for the conversion in my projects. Because it's fast — much faster than pandoc
, for example. Speed is important as the conversion happens on the fly and handles each doc-string individually. Other than that, any Markdown-to-reST converter would do.
安装m2r
并将以下内容添加到Sphinx的配置文件conf.py
:
Install m2r
and add the following to Sphinx's configuration file conf.py
:
import m2r
def docstring(app, what, name, obj, options, lines):
md = '\n'.join(lines)
rst = m2r.convert(md)
lines.clear()
lines += rst.splitlines()
def setup(app):
app.connect('autodoc-process-docstring', docstring)
[已编辑以添加... ]
与上述相同,但带有 commonmark
:
Just like above, but with commonmark
:
import commonmark
def docstring(app, what, name, obj, options, lines):
md = '\n'.join(lines)
ast = commonmark.Parser().parse(md)
rst = commonmark.ReStructuredTextRenderer().render(ast)
lines.clear()
lines += rst.splitlines()
def setup(app):
app.connect('autodoc-process-docstring', docstring)
它使用与Sphinx扩展名recommonmark
相同的Markdown解析器,并且与m2r
一样快,这意味着与本地reStructuredText相比,构建时间几乎没有影响.
This uses the same Markdown parser as the Sphinx extension recommonmark
and is as fast as m2r
, which means next to no effect on build time compared to native reStructuredText.
这篇关于强制Sphinx用Python文档字符串而不是reStructuredText解释Markdown的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!