Skip to main content
 首页 » 编程设计

python之如何使用 Sphinx 链接到 str 方法

2025年02月15日7bluestorm

我正在使用 Sphinx 从我的文档字符串生成我的 HTML 文档,就像一个优秀的 lil' Pythonista。

我有一个看起来像这样的文档字符串:

def do_a_thing(text): 
    ''' 
    Call the ``str.strip()`` method on ``text``. Then do something 
    else with it. 
    ''' 

但是,我希望它链接到 https://docs.python.org/3/library/stdtypes.html#str.strip而不仅仅是等宽和代码块。

我尝试了几种方法:

:py:func:`str.strip()` 
:mod:`str.strip()` 
:class:`str.strip()` 
:any:`str.strip()` 
:doc:`str.strip()` 

这些都不起作用 - 或者更准确地说,前四种方法给我一个等宽和粗体字体,但它们实际上都没有链接到任何地方。 any 指令给了我 WARNING: 'any' reference target not found: str.strip()

显然我可以自己建立一个链接,但这看起来很糟糕,而且可能也不是我想要的,因为当我升级到 Python 4 时呢?然后我必须更新文档中的所有链接,这太恶心了。

链接到 str 方法的 Python 文档的正确方法是什么?

请您参考如下方法:

Intersphinx好吧!

在 conf.py 中,添加几行。金字塔文档有很好的例子来添加 Intersphinx extension和 configuring intersphinx mappings .

extensions = [ 
    # ... 
    'sphinx.ext.intersphinx', 
    # ... 
    ] 

和

intersphinx_mapping = { 
    #... 
    'python': ('https://docs.python.org/3', None), 
    #... 
} 

然后在您的 .rst 文件中,有几种方法可以指向 Python 文档。我们更喜欢使用以下格式,向文档作者指示链接将解析为指定的外部文档源。

:mod:`venv module <python:venv>` 
:ref:`package <python:tut-packages>` 

对于 Python,您还可以使用 Python Domain 中的任何指令,包括:

:py:meth:`str.strip` 

就版本控制而言,您可以在 intersphinx 映射中使用多个名称或更新目标映射。

intersphinx_mapping = { 
    #... 
    'python2': ('https://docs.python.org/2', None), 
    'python': ('https://docs.python.org/3', None),  # use "python" for default version 
    #... 
} 

或者在未来...

intersphinx_mapping = { 
    #... 
    'python2': ('https://docs.python.org/2', None), 
    'python3': ('https://docs.python.org/3', None), 
    'python': ('https://docs.python.org/4', None),  # use "python" for default version 
    #... 
}