How to check if you are in a Jupyter notebook

2019-04-04 18:15发布

I am creating a python module with a function to display a pandas DataFrame (my_df).

If the user imports the module into a Jupyter notebook, I would want to deliver "pretty" formatting for the DataFrame by using something like:

from IPython.display import display, HTML
display(my_df)

If the user is not in a Jupyter notebook, I would want to display the text form of the DataFrame:

print(my_df)

How can I check if the code is being run from a Jupyter notebook? Or, how can I display the DataFrame in text form from the commandline, vs display the HTML form if it is imported into a Jupyter notebook?

from IPython.display import display, HTML

def my_func(my_df):
    if [... code to check for Jupyter notebook here ...]:
        display(my_df)
    else:
        print(my_df)

2条回答
姐就是有狂的资本
2楼-- · 2019-04-04 18:41

You should look in os.environ.

On my machine you can see it in

os.environ['_']
查看更多
Lonely孤独者°
3楼-- · 2019-04-04 18:56

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 display
import 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  foo
0    7    1
1    8    2
2    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, HTML
import 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

查看更多
登录 后发表回答