我希望能够将 jupyter notebook 作为常规 python 文件运行(使用标准 python 解释器) 出色地。我面临的问题是,在 python 中,我无法以可用的形式呈现 Markdown 对象:
运行下面的代码会在 notebook 中正常呈现,但会打印 <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 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)
这还是不太好...
请您参考如下方法:
选项 1:包含“text/plain”和“text/markdown”条目的字典
您可以将包含不同 MIME 类型的字典传递给 IPython 的 display(..., raw=True):Jupyter Notebook 将使用丰富的表示形式,而 IPython 或纯 Python 前端将回退到 text/plain 表示。
这是一个最小的完整示例;尝试在 IPython 终端和 Jupyter notebook 中运行它,您会看到它在两者中都能正确呈现。
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 类的对象定义自定义文本/纯格式器
示例基于 IPython display 中的“定义新的 int 格式化程序”示例文档。您需要在 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文档:
See the
display_datamessage in the messaging documentation for more details about this message type.The following MIME types are currently implemented:
- text/plain
- text/html
- text/markdown
- text/latex
- application/json
- application/javascript
- image/png
- image/jpeg
- image/svg+xml
