LoginSignup
13
16

More than 5 years have passed since last update.

Sphinx のセットアップまとめ

Posted at

概要

Python パッケージのドキュメント作成には Sphinx が便利.sphinx-apidoc, autodoc を使えば,docstrings から API リファレンスを自動で作成してくれる.これらを使う時,いつもだいたい同じセットアップが必要なので,備忘録としてまとめておく.

前準備

sphinx のインストールとドキュメント用ディレクトリの作成.

$ pip install sphinx
$ mkdir docs
$ cd docs

その結果,次のようなディレクトリ構成になっているとする.

.
├── README.md
├── docs
├── <your package>
└── tests
    └── テストたち

sphinx-quickstart

基本的にはデフォルトで,次の項目だけ設定する.

  • source と build は分ける
  • autodoc: automatically insert docstrings from modules は yes
  • mathjax は必要に応じて yes
  • viewcode も必要に応じて yes

sphinx-apidoc の設定

Makefile を編集して,ドキュメントのコンパイル時に sphinx-apidoc を呼ぶようにする.

まずは,sphinx-apidoc 用のターゲットを作る.sphinx-apidoc で自動生成されたファイルは,ワイルドカードでインポートするために, source/modules の中に保存している.

Makefile
.PHONY: sphinx-apidoc
sphinx-apidoc:
    sphinx-apidoc -f -o source/modules -M "../<module_path>/"
    # glob でインポートする時に邪魔なので削除
    rm source/modules/modules.rst

そして,すべてのターゲットの依存関係に sphinx-apidoc ターゲットを追加する.例えば,html ターゲットの場合,

Makefile
.PHONY: html
# html:
html: sphinx-apidoc # これを追加
    $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
    @echo
    @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."

ソースファイルの編集

sphinx のパスに対象のパッケージが含まれるように source/conf.py に以下を追加する.

conf.py
import sys
import os
sys.path.insert(0, os.path.abspath("../.."))

そして,sphinx-apidoc で生成されたファイルを読み込むために,以下を source/index.rst に追加する.

index.rst
.. toctree::
   :glob:
   :maxdepth: 2

   modules/*

最後に,お好みでデザインを変更する.個人的には Read the docs テーマ が気に入っているので source/conf.py に以下を追加する.

conf.py
import sphinx_rtd_theme
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]

コンパイル

コンパイルは docs ディレクトリで,

$ make html
13
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
16