1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Jupyter上でのデバッグのための判定用フラグ

Posted at

用途

私はPythonの独自モジュールを作る際に、Jupyter上でコーディングして、出来上がったら"Executable Script"としExportして使っている。
こういうやり方をしている時に、Jupyter上で作成時には、確認やデバッグ用のコードを書いたセルを含む。
これを、Export前に消す、あるいはif True:と書いておいて、Export前にif False:に書き換えるなどとしていたが、それなりに面倒だ。

その解決方法を確認したので、以下に示す。

判定用フラグ

先頭の方のスクリプトに以下を書き、フラグOnJupyterを設定する。

import sys
OnJupyter = __name__ == '__main__' and "ipykernel" in sys.modules

このフラグは、Jupyter上で直接実行されているノートブック上のコードでのみTrueとなる。作成したモジュールをJupyter上でimportしても、そのモジュール上では(__name____main__ではないので)Falseとなる。

デバッグ用セル

デバッグ用のセルは、以下の例の様に先頭でフラグをチェックするように書けば良い。

if OnJupyer:
    print("This is a debug code")
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?