【问题标题】:Create a Cell magics that Execute code before and after the cell execution创建一个在单元执行之前和之后执行代码的单元魔法
【发布时间】:2017-03-09 20:55:50
【问题描述】:

我有一个特殊的类来捕获和处理给定算法的日志。这看起来像这样

report = Report2File(logger,"./path")
report.start()

solveProblem()

report.stop()
del report

我想更懒一点,只写

%%report "./path"
solveProblem()

这种魔法细胞接缝的创建一开始很容易

更新:

@magics_class
class MyMagics(Magics):

    @cell_magic
    def cmagic(self, line, cell):
        "my cell magic"
        self.before()
        exec(cell)
        self.after()
        return line, cell

    def before(self):
        do stuff ...

    def after(self):
        do stuff ...

ip = get_ipython()
ip.register_magics(MyMagics)

但是我遇到了两个问题:

  1. 我不知道如何将记录器对象传递给我的魔法
  2. Jupyter 一直告诉我 MyMagics 模块不是 ipython 扩展

部分回答

this talk 给了我 2 的答案。

代替

ip = get_ipython()
ip.register_magics(MyMagics)

注册魔法的正确方法如下

def load_ipython_extension(ip):
    ip.register_magics(MyMagics)

def unload_ipython_extension(ip):
    pass

【问题讨论】:

    标签: ipython jupyter-notebook jupyter ipython-magic


    【解决方案1】:

    您还需要使用@magics_class(来自 IPython.core.magic)来装饰类。
    要传递参数,请查看 @magic_arguments 文档中的示例:这很容易理解。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多