是否可以在 IPython/Jupyter 中结合魔法?

Roe*_*ant 4 python ipython jupyter-notebook

有时您想同时使用多种魔法。现在我知道你可以使用

%%time
%%bash
ls 
Run Code Online (Sandbox Code Playgroud)

但是当我制定自己的命令时,这种链接不起作用......

from IPython.core.magic import register_cell_magic

@register_cell_magic
def accio(line, cell):
    print('accio')
    exec(cell)
Run Code Online (Sandbox Code Playgroud)

导致使用时报错

%%accio
%%bash
ls
Run Code Online (Sandbox Code Playgroud)

我应该使用什么而不是exec

geo*_*xsh 5

您必须应用 IPython 特殊转换,才能使用单元格运行嵌套魔术,例如%%time魔术

@register_cell_magic
def accio(line, cell):
    ipy = get_ipython()
    expr = ipy.input_transformer_manager.transform_cell(cell)
    expr_ast = ipy.compile.ast_parse(expr)
    expr_ast = ipy.transform_ast(expr_ast)
    code = ipy.compile(expr_ast, '', 'exec')
    exec(code)
Run Code Online (Sandbox Code Playgroud)

或者干脆打电话run_cell

@register_cell_magic
def accio(line, cell):
    get_ipython().run_cell(cell)
Run Code Online (Sandbox Code Playgroud)

结果:

In [1]: %%accio
   ...: %%time
   ...: %%bash
   ...: date
   ...:
accio
Wed Nov 14 17:41:55 CST 2018
CPU times: user 1.42 ms, sys: 4.21 ms, total: 5.63 ms
Wall time: 9.64 ms
Run Code Online (Sandbox Code Playgroud)