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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With