首页 > 解决方案 > jupyter notebook vs jupyter console:markdown(和latex、html等)对象的显示

问题描述

我也希望能够将 jupyter notebook 作为常规 python 文件(使用标准 python 解释器)运行。我面临的问题是,在 python 中,我无法以可用的方式呈现 markdown 对象:

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

from IPython.display import Markdown, display
display(Markdown('# Hello World!'))

我试图想出一种方法来完成这项工作,并发现了这个丑陋的解决方法:

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!')

这似乎很hacky!有没有更简单的方法来获得合理display的降价对象?或者至少是一种更简单的方法来了解是否display能够呈现降价?

乳胶、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)

这仍然不是很好......

标签: pythonpython-3.xjupyter-notebookjupytersage

解决方案


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

您可以将包含不同 MIME 类型的 dict 传递给 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)

选项 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>

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

取自DisplayFormatter文档:

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

当前实现了以下 MIME 类型:

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

推荐阅读