使输出单元格像Markdown

nom*_*-ir 16 ipython-notebook

我喜欢IPython的Markdown单元格,用于在笔记本中集成HTML和其他丰富内容.我想知道输出单元格中是否可以类似地格式化命令输出.

这是我输出HTML的函数之一:

    print_html():
      print """
      <h2>Matplotlib's chart gallery (Click a chart to see the code to create it)</h2><br>
      <div align="center"> <iframe title="Matplotlib Gallery" width="950"
      height="250" src="http://matplotlib.org/gallery.html#api" frameborder="0"
      allowfullscreen></iframe></div>
    """
Run Code Online (Sandbox Code Playgroud)

上面的HTML代码,如果放在markdown(输入)单元格中,会产生与Matplotlib库的良好链接.但在输出单元格中,它只是纯文本.有什么办法让它内容丰富吗?

nom*_*-ir 17

在这里找到了一个解决方案:http://mail.scipy.org/pipermail/ipython-user/2012-April/009838.html

在这里引用解决方案为ref:

布莱恩格兰杰:

"让函数返回包含在HTML对象中的原始HTML:

from IPython.core.display import HTML
...
...
def foo():
    raw_html = "<h1>Yah, rendered HTML</h1>"
    return HTML(raw_html)
Run Code Online (Sandbox Code Playgroud)

"

现在调用foo()确实提供了我想要的格式化的html.


Elp*_*lpy 7

最近在博客文章中发布了一个更先进的解决方案:

http://guido.vonrudorff.de/ipython-notebook-code-output-as-markdown/

它创建并注册了一个新的IPython魔术%%asmarkdown.您使用此命令添加的每个代码单元格的输出将呈现为纯粹的降价单元格.使用原始问题的内容,以下内容将按预期运行:

%%asmarkdown
print """
<h2>Matplotlib's chart gallery (Click a chart to see the code to create it)</h2><br>
<div align="center"> <iframe title="Matplotlib Gallery" width="950"
height="250" src="http://matplotlib.org/gallery.html#api" frameborder="0"
allowfullscreen></iframe></div>
"""
Run Code Online (Sandbox Code Playgroud)