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)
If you wish to know where Jupyter isinstalled on your computer, you may run where jupyter in the Command prompt. If you wish to know which Python version is installed, run python or python -V or python --version .
Open the notebook in Jupyter Notebooks and look in the upper right corner of the screen. It should say, for example, "Python [env_name]" if the language is Python and it's using an environment called env_name.
To interrupt a cell execution, you can click the ■ “stop” button in the ribbon above the notebook, or select “Interrupt Kernel” from the Kernel menue.
On Linux and other free desktop platforms, these runtime files are stored in $XDG_RUNTIME_DIR/jupyter by default. On other platforms, it's a runtime/ subdirectory of the user's data directory (second row of the table above). An environment variable may also be used to set the runtime directory.
You should look in os.environ.
On my machine you can see it in
os.environ['_']
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:
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
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