LoginSignup
6
5

More than 3 years have passed since last update.

JupyterのTracebackを見やすくする

Posted at

better-exceptionsを jupyter でも

この記事は何?

 jupyerでバッチコードも書くアナタ、pdbを起動させるのがかったるいアナタにオススメします。ExceptionでTracebackが起動すると前後の変数を出力しておいてくれる優れモノのモジュール「better-exceptions」をjupyterでも使えるようにするHackです。
BetterExceptions.png

イントロ

「PythonのException発生時のTracebackを綺麗に見る」

 元記事は、Twitter:@vaaaaanquish氏の上記記事で、Traceback周りのモジュール紹介してくれています。大変秀逸な記事です。氏はその中で様々な機能拡張がコメントされていますが、そこはかとなくオススメされていた「better-exception」は、Traceback停止時に、変数の内容を一緒に表示してくれる優れモノ。

 こりゃjupyterでも使いたいと思い、アレコレ試したところjupyterでも使えるようになったので、ノウハウとして投稿することにしました。

モジュール作者はQixさん(githubはこちら)

リポジトリのREADME.mdにある紹介画像を下に引用します。
screenshot.png

元々はシェルやREPL環境用

 IDE環境がある人はそれでできている機能ですが、何かの理由でシェルやREPL環境用で実行してTracebackが発生した際には、パッとデバッグできないのが厄介。better_exceptionsがインポートしてあれば、業務は劇的に向上します。

better-exceptionsの使い方

インストール

 まだ、未インストールの方はインストールをしてください

 pip install better_exceptions

また、REPLやシェルでも使う方は環境変数を設定すると幸せになれるかも

export BETTER_EXCEPTIONS=1  # Linux / OSX

Python REPL (インタラクティブ・シェル)に入って使う

下記のように起動コマンドでーmオプションを使ってbetter-exceptionsモジュールをしています。

$ python -m better_exceptions
Type "help", "copyright", "credits" or "license" for more information.
(BetterExceptionsConsole)
>>>

jupyterでもbetter-exceptionsを使う

jupyter用の設定ファイルをipythonのスタートアップパスにおきます。

ipythonのスタートアップパス

$HOME/.ipython/profile_default/startup/00-better_exceptions.py

jupyter用設定ファイル ↓↓↓↓↓

00-better_exceptions.py
import sys
try:
    import better_exceptions
except ImportError:
    better_exceptions = None

def exception_thunk(exc_tuple=None, filename=None,
                    tb_offset=None, exception_only=False, **kwargs):
    new_exc_tuple = exc_tuple or sys.exc_info()
    if not isinstance(new_exc_tuple[0], SyntaxError):
        return print(better_exceptions.format_exception(*new_exc_tuple))
    else:
        return old_show_tb(exc_tuple, filename,
                           tb_offset, exception_only)
if better_exceptions:
    ip = get_ipython()
    old_show_tb = ip.showtraceback
    ip.showtraceback = exception_thunk

実行例

githubのテストスクリプトによる実行例(意図的に例外を発生させるコード)
スクリーンショット 2019-06-25 23.24.29.png

実行例その2
スクリーンショット 2019-06-25 23.24.41.png

コード中にあるようにbetter_exceptions.MAX_LENGTHで出力する文字数(水色)を調整できます。

本当に便利(マジで関心しています)。

実は正式採用にはなっていない

上の'00-better...'ファイルは未だリポジトリには正式採用されていません。github上のissue ipython support#10 の中でユーザ同士の提案で出てきたコードです。その中から良さげなものをピックしました。pdbとも上手く同居できるようです(当方はまだ試していません)。
https://github.com/Qix-/better-exceptions/issues/10

良い jupyter生活を!

6
5
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
6
5