Sphinxとは
Pythonのクラスや関数のドキュメントを自動生成するツールです。正しく、docstringを書いている場合自動的に整形してhtmlを生成してくれます。これを導入する際にいくつかトラップがあるので、それを解説します。参考にした記事は以下の通りです。
導入
Pythonの仮想環境に入ります。
-
venvの場合
$ source venv/bin/activate
-
condaの場合
$ conda activate <env_name>
Sphinxのインストール
$ pip install sphinx # Sphinx
$ pip install sphinx-book-theme # Sphinxで用いるテーマ
テストプロジェクトの作成
~$ mkdir test
~/test$ cd test
~/test$ touch main.py
# ディレクトリ構造は以下の通り
.
└── main.py
Sphinxの初期設定
インタラクティブシェルが起動するので、以下のように入力します。
~/test$ sphinx-quickstart docs
> Separate source and build directories (y/n) [n]: y
> Project name: hoge
> Author name(s): hoge
> Project release []: 1.0.0
> Project language [en]:
すると、以下のようなディレクトリ構造ができます。重要なものだけ抜粋しています。
.
├── docs
│ ├── build
│ ├── source
│ │ ├── conf.py
│ │ └── index.rst
│ ├── make.bat
│ └── Makefile
└── main.py
設定ファイルの編集
docs/source/conf.pyに以下の内容を追加します。
import os
import sys
sys.path.insert(0, os.path.abspath('../../'))
# 中略
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.napoleon',
]
# 中略
html_theme = 'sphinx_book_theme'
extensionsが非常に重要で、これがないと何も表示されません。
-
sphinx.ext.autodocは、docstringを読み込んでドキュメントを生成するための拡張機能です。 -
sphinx.ext.napoleonは、NumpyスタイルかGoogleスタイルのdocstringを読み込むための拡張機能です。
docs/source/index.rstを以下のように編集します。
globを追加することで、*が使えるようになります。
そして、*を指定することですべての.rstファイルを選択することができます。
Welcome to hoge's documentation!
================================
.. toctree::
:glob:
:maxdepth: 2
:caption: Contents:
*
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
~/test$ cd docs
~/test/docs$ sphinx-apidoc -f -o source ../
~/test/docs$ make html
最終的なディレクトリ構成は以下のようになります。重要なものだけ抜粋しています。
.
├── docs
│ ├── build
│ │ ├── html
│ │ ├── index.html # これがドキュメントのトップページ
│ ├── source
│ │ ├── conf.py
│ │ └── index.rst
│ ├── make.bat
│ └── Makefile
└── main.py
ドキュメントの確認
VSCodeにおけるhtmlの確認方法を説明します。自分でWebサーバーを建てられる人はそうしても構いません。
-
ローカル環境の場合、特別な設定は必要なく、
htmlをブラウザに貼り付ければ多分表示されます。自分はやったことがないのでうまくいかない場合は次に示す方法を参考にしてください。 -
サーバー上などの場合、
VSCodeのLive Serverという拡張機能を利用します。index.htmlが存在するフォルダをVSCodeで開き、右下のGo liveというボタンを押すとそのサーバーの何らかのポートでhtmlが表示されます。
参考サイト
-
Sphinx Themes Gallery
- Sphinx のテーマがまとまっているサイトです。