如何在依赖于就地构建的 Python 项目中使用 Sphinx?

How to use Sphinx in a Python project that depends on being built in place?

我有一个主要是 Python 的大型项目,我正在尝试记录。该项目的一部分依赖于可通过 Cython 访问的 C++ 源代码。

当 运行 正常使用代码时,它 运行 没问题,但是在尝试使用 Sphinx 进行自动记录时,我遇到了 运行 问题。我认为 this guy 的想法是正确的,但我无法实现它。

我的Makefile看起来像这样

# Minimal makefile for Sphinx documentation
#

# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS    ?=
SPHINXBUILD   ?= sphinx-build
SOURCEDIR     = .
BUILDDIR      = _build

# Put it first so that "make" without argument is like "make help".
help:
    @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

.PHONY: help Makefile

# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option.  $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
    @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

如何告诉 Sphinx 运行 python setup.py build_ext --inplace 然后在分析代码之前引用输出 .so 文件?

感谢您的宝贵时间。

您可能希望在执行任何 sphinx 特定命令之前将 answer you linked 中的步骤添加为从 sphinx 生成的 Makefile 的一部分。

# Minimal makefile for Sphinx documentation
#

# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS    ?=
SPHINXBUILD   ?= sphinx-build
SOURCEDIR     = .
BUILDDIR      = _build

# Put it first so that "make" without argument is like "make help".
help:
    @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

.PHONY: help Makefile

# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option.  $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
    @cd /path/to/setup.py; python setup.py build_ext --inplace
    @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

将其添加到 sphinx 生成的 catch-all 命令之上意味着生成 cython 代码的构建命令将在 sphinx 相关命令之前执行。

我建议改为将 project directory to be more standard 结构化为 python 中使用的内容。不是将文档与源代码放在同一目录中,而是将源代码和文档放在一个单独的目录中。

root directory/
  myproject/ (source code for Cython module)
  libs/ (generated .so files from Cython)
  tests/ (directory to hold test cases that should run after building)
    __init__.py
  docs/
    Makefile (from sphinx)
  Makefile (project)
  setup.py

项目的 Makefile 将负责构建源代码,然后构建文档。它的 Makefile 类似于以下内容:

.all:
    @python setup.py build_ext 
    @cd tests; $(MAKE) python -m unittest
    @cd docs; $(MAKE) html

all 的第一部分将生成源代码(并且应该更新以将生成的 .so 文件放置到 libs/ 文件夹中)。第二部分将进入 tests/ 目录和 运行 单元测试(例如 python 的单元测试库)。第三部分将进入 docs/ 目录并 运行 使用 Sphinx 生成的 Makefile 为目标 html 制作。为此,您还需要更新测试和文档以在其路径中包含 libs/,以便他们可以导入从构建生成的 .so 文件。 (注意:@ 符号防止该行被输出到控制台。如果希望将其视为构建的一部分,则应省略)