且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在ipython-notebook的Markdown单元格中展开变量

更新时间:2023-09-29 23:07:16

尽管尚无法使用真正的Markdown单元,但您可以轻松创建魔术来获得相同的效果.

Although it's not possible yet to do with a real Markdown cell, you can easily create a magic to get the same effect.

from __future__ import absolute_import
from IPython.core.getipython import get_ipython
from IPython.core.magic import (Magics, magics_class,  cell_magic)

@magics_class
class MarkdownMagics(Magics):

    @cell_magic
    def markdown(self, line, cell):
        from IPython.core.display import HTML
        from markdown import markdown

        vars = line.split()

        d = {}
        for k, v in self.shell.user_ns.items():
            if k in vars:
                d[k] = v

        return HTML("<p>{}</p>".format(markdown(cell.format(**d))))

get_ipython().register_magics(MarkdownMagics)

设置一些变量

foo = 1
bar = 2

然后调用魔术,参数是您要从命名空间中获取的变量.

Then call the magic, with arguments being the variables you want to take from the namespace.

%%markdown foo bar

Substitute _{foo}_ and *{bar}*