How to check if you are in a Jupyter notebook How to check if you are in a Jupyter notebook pandas pandas

How to check if you are in a Jupyter notebook


You don't need to check if the code is being run from a Notebook; display() prints text when called from the command line.

test.py:

from IPython.display import displayimport pandas as pd my_df = pd.DataFrame({'foo':[1,2,3],'bar':[7,8,9]})display(my_df)

From the command line:

$ python test.py    bar  foo0    7    11    8    22    9    3

From a Jupyter Notebook:

notebook printout

UPDATE
To check whether you're running inside an interactive Ipython shell (command-line or browser-based), check for get_ipython. (Adapted from the Ipython docs)

Modified test.py:

from IPython.display import display, HTMLimport pandas as pd my_df = pd.DataFrame({'foo':[1,2,3],'bar':[7,8,9]})try:    get_ipython    display(my_df)except:    print(my_df)

This approach will:
- pretty-print in a browser Jupyter notebook
- print text when run as a script from the command line (e.g. python test.py)
- if run line-by-line in a Python shell, it will not turn into an interactive Ipython shell after printing


You should look in os.environ.

On my machine you can see it in

os.environ['_']