jupyter笔记本与jupyter控制台:显示markdown(以及latex、html等)对象

hir*_*ist 5 python sage python-3.x jupyter jupyter-notebook

我希望能够将 jupyter 笔记本作为常规 python 文件运行(使用标准 python 解释器)。我面临的问题是,在 python 中,我无法在可用的位置渲染 markdown 对象:

运行下面的代码会像在笔记本中那样呈现,但<IPython.core.display.Markdown object>在仅使用 python 运行时会打印。

from IPython.display import Markdown, display
display(Markdown('# Hello World!'))
Run Code Online (Sandbox Code Playgroud)

我试图想出一种方法来实现这一点,但发现了这个丑陋的解决方法:

from IPython.display import Markdown, display
from IPython import get_ipython
from IPython.core.displaypub import DisplayPublisher
from ipykernel.zmqshell import ZMQDisplayPublisher

display_pub_class = get_ipython().display_pub_class()

def displaymd(strg):
    if isinstance(display_pub_class, ZMQDisplayPublisher):
        display(Markdown(strg))
    elif isinstance(display_pub_class, DisplayPublisher):
        print(strg)
    else:
        # ??
        display(strg)

displaymd('# Hello World!')
Run Code Online (Sandbox Code Playgroud)

这看起来很老套!有没有更简单的方法来获取合理display的 Markdown 对象?或者至少有一种更简单的方法来知道是否display能够渲染 markdown?

同样的问题也适用于 Latex、html 和类似的对象。


刚刚找到了一种稍微简单的方法来检查我是否在 ipython 上:

def on_ipython():
    if 'get_ipython' in globals():
        return True
    else:
        return False

def displaymd(strg):
    if on_ipython():
        display(Markdown(strg))
    else:
        print(strg)
Run Code Online (Sandbox Code Playgroud)

但这仍然不太好......

Est*_*eis 4

选项 1:同时包含“text/plain”和“text/markdown”条目的字典

您可以将包含不同 MIME 类型的字典传递给 IPython display(..., raw=True):Jupyter Notebook 将使用丰富的表示形式,而 IPython 或普通 Python 前端将回退到该text/plain表示形式。

这是一个最小的完整示例;尝试在 IPython 终端和 Jupyter 笔记本中运行它,您将看到它在两者中都能正确呈现。

from IPython.display import display


my_markdown_string = '''\
# Heading one

This is

* a
* list
'''

display({'text/plain': my_markdown_string,
         'text/markdown': my_markdown_string},
        raw=True)
Run Code Online (Sandbox Code Playgroud)

选项 2:为 Markdown 类的对象定义自定义文本/纯格式格式化程序

示例基于intIPythondisplay文档中的“定义新格式化程序”示例。您需要在 IPython 中运行它来查看其效果。

from IPython.display import display, Markdown

def md_formatter(md, pp, cycle):
    pp.text(md.data)

text_plain = get_ipython().display_formatter.formatters['text/plain']
text_plain.for_type(Markdown, md_formatter)

display(Markdown('x **x** x'))
# x **x** x

del text_plain.type_printers[Markdown]
display(Markdown('x **x** x'))
# <IPython.core.display.Markdown object>
Run Code Online (Sandbox Code Playgroud)

附录:Jupyter/IPython 已知的 MIME 类型列表

取自DisplayFormatter文档:

有关此消息类型的更多详细信息,请参阅消息传递文档中的display_data消息。

当前实现了以下 MIME 类型:

  • 文本/纯文本
  • 文本/html
  • 文本/降价
  • 文本/乳胶
  • 应用程序/json
  • 应用程序/javascript
  • 图片/png
  • 图片/jpeg
  • 图像/svg+xml