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

2024-06-01 09:49:17 发布

您现在位置:Python中文网/ 问答频道 /正文

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

运行下面的代码会在笔记本中呈现,但会在 当只使用python运行时。在

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

我正试图想出一个办法,但却发现了一个丑陋的工作:

^{pr2}$

这看起来很恶心!有没有更简单的方法来获得合理的降价对象display?或者至少有一种更简单的方法来知道display是否能够呈现降价?在

同样的问题也适用于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)

但这不是很好。。。在


Tags: 对象方法fromreturnifondefipython
1条回答
网友
1楼 · 发布于 2024-06-01 09:49:17

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

您可以将包含不同MIME类型的dict传递给IPython的display(..., raw=True):Jupyter笔记本将使用丰富的表示形式,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的对象定义自定义文本/纯格式设置程序

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

^{pr2}$

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

摘自DisplayFormatter文档:

See the display_data message 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

相关问题 更多 >