10
3

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 5 years have passed since last update.

モジュールが import されたのが Jupyter notebook か否かを調べる

Last updated at Posted at 2019-08-05

tqdm など Jupyter Notebook で使っているのか判定したい場合がある. 1 Jupyter notebook に書いたコードで直接判定するのではなく、Jupyter notebook から import されたモジュールの中からも判別できてほしい.

方法は Stack overflow を見ると判定方法が百花繚乱でわからん. 2 import される場合でも使えるものもあれば使えないものもある. ねえ、Zen of Python ってあったよね?3

There should be one-- and preferably only one --obvious way to do it.

問題

'get_ipython' in globals() は Jupyter Notebook から直接呼ぶ場合は True、Jupyter Notebook から import された場合は False なので使えない。

結論

'ipykernel' in sys.modules

Jupyter Notebook なら True, python script などその他は False. ipython のターミナル環境でも False.

if 'ipykernel' in sys.modules:
   # Jupyter Notebook
   from tqdm import tqdm_notebook as tqdm
else:
   # ipython, python script, ...
   from tqdm import tqdm

別解

環境や将来の変更によって使えない場合にもうひとつ候補を。get_ipythonglobals() になくても呼べることを利用して、もみじあめさんバージョン1をちょっと変える

def is_env_notebook():
    """Determine wheather is the environment Jupyter Notebook"""

    try:
        env_name = get_ipython().__class__.__name__
    except NameError:
        return False

    if env_name == 'TerminalInteractiveShell':
        # IPython shell
        return False
    # Jupyter Notebook (env_name == 'ZMQInteractiveShell')
    return True

なんで globals() にない get_ipython() が呼べるの??

実験

Jupyter Notebook

Jupyter Notebook に直接書いた場合

'get_ipython' in globals()  # => True
get_ipython().__class__.__name__  # => ZMQInteractiveShell

Import from Jupyter Notebook

'get_ipython' in globals()  # => False
get_ipython().__class__.__name__  # => ZMQInteractiveShell

なんで get_ipython() は globals() に無いに呼べるの??

IPython

In [1]: 'get_ipython' in globals()
Out[1]: True

In [2]: get_ipython().__class__.__name__
Out[2]: 'TerminalInteractiveShell'

Script

スクリプトで import して python3 で実行:

'get_ipython' in globals()  # => False
get_ipython().__class__.__name__  # => NameError: name 'get_ipython' is not defined

>>> って出る python のインタラクティブモードも同じ.

環境

$ python3 --version
Python 3.7.1

$ jupyter --version
jupyter core     : 4.5.0
jupyter-notebook : 5.7.8
ipython          : 7.6.0
  1. Python: 実行環境が Jupyter Notebook か判定する https://blog.amedama.jp/entry/detect-jupyter-env 2

  2. How can I check if code is executed in the IPython notebook? https://stackoverflow.com/questions/15411967/how-can-i-check-if-code-is-executed-in-the-ipython-notebook

  3. PEP 20 -- The Zen of Python https://www.python.org/dev/peps/pep-0020/

10
3
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
10
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?