Skip to content

Instantly share code, notes, and snippets.

@shirou
Last active December 10, 2015 23:39
Show Gist options
  • Save shirou/4511279 to your computer and use it in GitHub Desktop.
Save shirou/4511279 to your computer and use it in GitHub Desktop.
SphinxErrorhandling document
エラーハンドリング
=======================
拡張を書いているときに、エラーを出したいときがあります。こういう時には、
sphinx.errorsで定義されている例外を使いますと、通常の例外よりも表示が
親切になります。
sphinx.errorsには以下の例外が定義されています。
- SphinxError
- SphinxWarning
- ExtensionError
- ConfigError
- ThemeError
- VersionRequirementError
- PycodeError
使い方としては通常の例外と同じです。
.. code-block:: python
from sphinx.errors import ExtensionError
raise ExtensionError("Could not load extension")
なお、SphinxWarningは「Errorとして扱うようなWarningについて用いる」との
説明がついています。そのため、warningであってもその場でbuildがストップ
します。
警告のみとしたい
----------------
sphinx.application.warn()を使うことで、build時に警告表示が出来ます。Exceptionとは異な
り、buildが停止することはありません。停止させたい場合はExceptionを使っ
てください。
なお、sphinx.applicationはappとして拡張を書くときにいろいろな場所で使わ
れいます。
.. code-block::
def SomeBuilder(Builder):
def init(self):
self.app.warn("------ Print Warning")
self.app.info("------ Print Info")
こう書いておくと、
.. code-block:: none
Running Sphinx v1.1.3
loading pickled environment... done
WARNING: ------ Print Warning
------ Print Info
updating environment: 0 added, 0 changed, 0 removed
looking for now-outdated files... none found
preparing documents... done
writing output... [100%] index
build succeeded, 1 warning.
というように、画面上と最後に表示されます。
なお、上記例でも使っていますが、warnの他に
- info
があり、こちらは最後のwarningの数には含まれません。また、2013年1月に入っ
てから
- verbose
- debug
と `-v` オプションが追加されました。執筆時点での1.1.3では使えませんが、
将来のバージョンでは使えるようになると思います。
@tk0miya
Copy link

tk0miya commented Feb 4, 2013

警告を出すときは、system_message ノードを生成するという方法もあります。
docutils にはそのためのユーティリティクラス、docutils.utils.Repoter もあります。

Repoter は Sphinx 実行中に document.reporter や、state_machine.repoter として参照できるので、

document.reporter.warning(msg, line=self.lineno)

のように、警告メッセージ(用ノード)を生成できます。
これらは role や directive を定義する際に、「エラーで失敗させないが、警告を出したい」という時に
この渓谷メッセージ用ノードを返すことでエラーを通知します。
参考: https://bitbucket.org/tk0miya/blockdiag/src/67bda3b7f6494e9ffe8f5b2a94d82eda99972367/src/blockdiag/utils/rst/directives.py?at=default#cl-99

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment