检测 ipython notebook 是否正在输出到终端
Detecting if ipython notebook is outputting to a terminal
我想检测是否正在终端中执行 Jupyter Notebook,例如通过 ipython --TerminalIPythonApp.file_to_run
命令,与启用 HTML 的笔记本相反。请注意,这不同于检测 Python 代码是 运行 与 python
还是在笔记本中。
基于此,我可以格式化 Pandas 适合 HTML 或终端显示的数据帧。
如何检测笔记本是否正在输出到终端?
这可能会有所帮助。
from IPython import get_ipython
def type_of_execution():
try:
type_of_exec = str(type(get_ipython()))
if 'terminal' in type_of_exec:
return 'terminal'
elif 'zmqshell' in type_of_exec:
return 'jupyter'
else:
return 'python'
except:
return 'terminal likely'
print("Checking..")
print(type_of_execution())
根据 William 的回答,我明白了。
终端输出示例:
HTML 输出示例:
这是一些示例代码,从 William 的回答中清理出来,还有一些关于如何使用它的更多上下文。
See an example quantitative finance notebook using this. See full source code.
"""Helpers to deal with Jupyter Notebook issues."""
import enum
from typing import Callable
import pandas as pd
from IPython import get_ipython
from IPython.display import display
from IPython.terminal.interactiveshell import TerminalInteractiveShell
from ipykernel.zmqshell import ZMQInteractiveShell
class JupyterOutputMode(enum.Enum):
"""What kind of output Jupyter Notebook supports."""
#: We could not figure out - please debug
unknown = "unknown"
#: The notebook is run by terminal
terminal = "terminal"
#: Your normal HTML notebook
html = "html"
def get_notebook_execution_mode() -> JupyterOutputMode:
"""Determine if the Jupyter Notebook supports HTML output."""
# See
# for discussion
ipython = get_ipython()
if isinstance(ipython, TerminalInteractiveShell):
# Hello ANSI graphics my old friend
return JupyterOutputMode.terminal
elif isinstance(ipython, ZMQInteractiveShell):
# MAke an assumption ZMQ instance is a HTML notebook
return JupyterOutputMode.html
return JupyterOutputMode.unknown
def display_with_styles(df: pd.DataFrame, apply_styles_func: Callable):
"""Display a Pandas dataframe as a table.
DataFrame styler objects only support HTML output.
If the Jupyter Notebook output does not have HTML support,
(it is a command line), then display DataFrame as is
without styles.
For `apply_style_func` example see :py:method:`tradingstrategy.analysis.portfolioanalyzer.expand_timeline`.
:param df: Pandas Dataframe we want to display as a table.
:param apply_styles_func: A function to call on DataFrame to add its styles on it.
We need to pass this as callable due to Pandas architectural limitations.
The function will create styles using `pandas.DataFrame.style` object.
However if styles are applied the resulting object can no longer be displayed in a terminal.
Thus, we need to separate the procses of creating dataframe and creating styles and applying them.
"""
mode = get_notebook_execution_mode()
if mode == JupyterOutputMode.html:
display(apply_styles_func(df))
else:
display(df)
我想检测是否正在终端中执行 Jupyter Notebook,例如通过 ipython --TerminalIPythonApp.file_to_run
命令,与启用 HTML 的笔记本相反。请注意,这不同于检测 Python 代码是 运行 与 python
还是在笔记本中。
基于此,我可以格式化 Pandas 适合 HTML 或终端显示的数据帧。
如何检测笔记本是否正在输出到终端?
这可能会有所帮助。
from IPython import get_ipython
def type_of_execution():
try:
type_of_exec = str(type(get_ipython()))
if 'terminal' in type_of_exec:
return 'terminal'
elif 'zmqshell' in type_of_exec:
return 'jupyter'
else:
return 'python'
except:
return 'terminal likely'
print("Checking..")
print(type_of_execution())
根据 William 的回答,我明白了。
终端输出示例:
HTML 输出示例:
这是一些示例代码,从 William 的回答中清理出来,还有一些关于如何使用它的更多上下文。
See an example quantitative finance notebook using this. See full source code.
"""Helpers to deal with Jupyter Notebook issues."""
import enum
from typing import Callable
import pandas as pd
from IPython import get_ipython
from IPython.display import display
from IPython.terminal.interactiveshell import TerminalInteractiveShell
from ipykernel.zmqshell import ZMQInteractiveShell
class JupyterOutputMode(enum.Enum):
"""What kind of output Jupyter Notebook supports."""
#: We could not figure out - please debug
unknown = "unknown"
#: The notebook is run by terminal
terminal = "terminal"
#: Your normal HTML notebook
html = "html"
def get_notebook_execution_mode() -> JupyterOutputMode:
"""Determine if the Jupyter Notebook supports HTML output."""
# See
# for discussion
ipython = get_ipython()
if isinstance(ipython, TerminalInteractiveShell):
# Hello ANSI graphics my old friend
return JupyterOutputMode.terminal
elif isinstance(ipython, ZMQInteractiveShell):
# MAke an assumption ZMQ instance is a HTML notebook
return JupyterOutputMode.html
return JupyterOutputMode.unknown
def display_with_styles(df: pd.DataFrame, apply_styles_func: Callable):
"""Display a Pandas dataframe as a table.
DataFrame styler objects only support HTML output.
If the Jupyter Notebook output does not have HTML support,
(it is a command line), then display DataFrame as is
without styles.
For `apply_style_func` example see :py:method:`tradingstrategy.analysis.portfolioanalyzer.expand_timeline`.
:param df: Pandas Dataframe we want to display as a table.
:param apply_styles_func: A function to call on DataFrame to add its styles on it.
We need to pass this as callable due to Pandas architectural limitations.
The function will create styles using `pandas.DataFrame.style` object.
However if styles are applied the resulting object can no longer be displayed in a terminal.
Thus, we need to separate the procses of creating dataframe and creating styles and applying them.
"""
mode = get_notebook_execution_mode()
if mode == JupyterOutputMode.html:
display(apply_styles_func(df))
else:
display(df)