如何检查您是否在Jupyter笔记本中 [英] How to check if you are in a Jupyter notebook

查看:492
本文介绍了如何检查您是否在Jupyter笔记本中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个具有显示pandas DataFrame(my_df)功能的python模块.

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

如果用户将模块导入到Jupyter笔记本中,我想通过以下方式为DataFrame提供漂亮的"格式:

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)

如果用户不在Jupyter笔记本中,我想显示DataFrame的文本形式:

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

print(my_df)

如何检查代码是否正在从Jupyter笔记本运行?或者,如何将DataFrame从命令行以文本形式显示,而不是将HTML形式导入到Jupyter笔记本中则显示HTML形式?

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)

推荐答案

您不需要检查代码是否正在从Notebook运行.从命令行调用时,display()打印文本.

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)

从命令行:

$ python test.py 
   bar  foo
0    7    1
1    8    2
2    9    3

从Jupyter笔记本中:

From a Jupyter Notebook:

更新
要检查您是否在交互式Ipython shell(基于命令行或基于浏览器)中运行,请检查get_ipython. (改编自 Ipython 文档)

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)

修改后的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)

此方法将:
-在浏览器Jupyter笔记本中漂亮打印
-从命令行作为脚本运行时打印文本(例如python test.py)
-如果在Python Shell中逐行运行,则打印后不会变成交互式Ipython Shell

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

这篇关于如何检查您是否在Jupyter笔记本中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆