How to check if you are in a Jupyter notebook

Viewed 7159

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 Answers
Related