最终用户将如何访问 Sphinx 为 Python 包生成的文档?

How would the end-user access the Sphinx generated documentation for a Python package?

我在 python 中开发了一个包,并使用 Sphinx 为它创建了文档。

文件夹结构的相关部分如下所示:

my_package
  setup.py
  my_package
    my_module.py
  docs
    index.rst
    _build
      html
        index.html

包将托管在 LAN 中由 PYTHONPATH 引用的某个位置。我的最终用户只需 import my_package 即可访问我的包裹。他们不知道文档(或与此相关的包)位于何处。使用 help(my_package) 只会向用户显示模块中的文档。

所以,我想知道如何让我的最终用户访问 index.html 文件?我考虑过使用从指定位置打开 html 文件的方法进行编码,但我不喜欢在路径中进行硬编码的想法。有这样做的标准方法吗?

因此,如果您唯一担心的是您不知道模块将安装在哪里,您可以通过调用 your_module.__file__(参见 this post)来确定。此外,您还可以利用 os.path 模块。例如,调用 os.path.dirname(your_module.__file__) 可能 return 您的 docs 文件夹所在的文件夹路径。然后,您可以相应地修改路径以访问 .html 文件。

扩展 @pkqxdd-s 建议:

您可以轻松获取 my_package

模块中文档的路径
# my_module.py

def get_docs_index_path():
    import os
    my_package_root = os.path.dirname(os.path.dirname(__file__))
    docs_index = os.path.join(my_package_root, 'docs', '_build', 'html', 'index.html')
    return docs_index

现在您可以将路径添加到 my_modulemy_package 文档字符串,这样调用 help(my_module) 的用户将得到类似

的内容
... 
# original my_module docstring
...

See sphinx docs at <path to your index>

请参阅 this question 以了解如何将 get_docs_index_path() 中的路径添加到文档字符串。

通常,文档会单独部署到包中。例如 pandas 存储库(其中包含 .rst 文件中文档的源代码)保存在 Github, but the built documentation is available at its own url.