How to check if you are in a Jupyter laptop

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

If a user imports a module into a Jupyter laptop, I would like to put a β€œpretty” formatting for the DataFrame, using something like:

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

If the user is not in the Jupyter laptop, I would like to display the DataFrame text form:

 print(my_df) 

How to check if code is running from a Jupyter laptop? Or, how can I display a DataFrame in text form from the command line, and also display an HTML form if it is imported into a Jupyter laptop?

 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) 
+8
python pandas jupyter-notebook jupyter
source share
2 answers

You do not need to check if the code is being executed from the laptop; 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 laptop:

laptop printout

UPDATE
To check if you are working inside the Ipython interactive shell (command line or browser-based), check get_ipython . (Adapted from Ipython docs)

Changed 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 would be:
- beautiful print in Jupyter browser

- print text at startup as a script from the command line (for example, python test.py )
- if you run line by line in the Python shell, it will not turn into an interactive Ipython shell after printing

+6
source share

You should look at os.environ.

On my car you can see it in

 os.environ['_'] 
0
source share

All Articles