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

问题描述

我有一个大型的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文件

谢谢您的时间。

解决方法

您希望将answer you linked中的步骤添加为从sphinx生成的Makefile的一部分,然后再执行任何特定于sphinx的命令。

# 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代码的build命令将在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/目录并运行unittests(例如python的unittest库)。第三部分将进入docs/目录,并使用Sphinx生成的Makefile为目标html运行make。为此,您还需要更新测试和文档以在其路径中包含libs/,以便他们可以导入从构建生成的.so文件。 (注意:@符号可防止将该行输出到控制台。如果希望将其视为构建的一部分,则应将其省略)