Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if code is executed in the IPython notebook?

I have some Python code example I'd like to share that should do something different if executed in the terminal Python / IPython or in the IPython notebook.

How can I check from my Python code if it's running in the IPython notebook?

like image 453
Christoph Avatar asked Mar 14 '13 14:03

Christoph


People also ask

How do I know if my code is running in Jupyter Notebook?

Your first Jupyter Notebook will open in new tab — each notebook uses its own tab because you can open multiple notebooks simultaneously. If you switch back to the dashboard, you will see the new file Untitled. ipynb and you should see some green text that tells you your notebook is running.

How do I track a program in Jupyter Notebook?

You can easily try it out by clicking on launch binder badge there and starting a notebook. Then right-click in the open notebook and select Open Variable Inspector from the list. The animation will show you how to drag the tabs to arrange them side by side on your screen.

How do I view IPython notebooks?

Double-click on the Jupyter Notebook desktop launcher (icon shows [IPy]) to start the Jupyter Notebook App. The notebook interface will appear in a new browser window or tab.

How does Jupyter Notebook execute code?

To run a piece of code, click on the cell to select it, then press SHIFT+ENTER or press the play button in the toolbar above. Additionally, the Cell dropdown menu has several options to run cells, including running one cell at a time or to run all cells at once.


1 Answers

The following worked for my needs:

get_ipython().__class__.__name__ 

It returns 'TerminalInteractiveShell' on a terminal IPython, 'ZMQInteractiveShell' on Jupyter (notebook AND qtconsole) and fails (NameError) on a regular Python interpreter. The method get_python() seems to be available in the global namespace by default when IPython is started.

Wrapping it in a simple function:

def isnotebook():     try:         shell = get_ipython().__class__.__name__         if shell == 'ZMQInteractiveShell':             return True   # Jupyter notebook or qtconsole         elif shell == 'TerminalInteractiveShell':             return False  # Terminal running IPython         else:             return False  # Other type (?)     except NameError:         return False      # Probably standard Python interpreter 

The above was tested with Python 3.5.2, IPython 5.1.0 and Jupyter 4.2.1 on macOS 10.12 and Ubuntu 14.04.4 LTS

like image 172
Gustavo Bezerra Avatar answered Sep 22 '22 20:09

Gustavo Bezerra