有时你想同时使用多个魔法。现在我知道你可以用
%%time
%%bash
ls 但当我自己做命令的时候这个链子不起作用..。
from IPython.core.magic import register_cell_magic
@register_cell_magic
def accio(line, cell):
    print('accio')
    exec(cell)使用时出现错误。
%%accio
%%bash
ls我应该使用什么而不是exec
发布于 2018-11-14 09:37:25
您必须应用IPython特殊转换,才能使用单元格魔术运行嵌套魔术。
@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_cell
@register_cell_magic
def accio(line, cell):
    get_ipython().run_cell(cell)结果:
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发布于 2018-11-14 01:44:03
在IPython源代码中,它们几乎总是使用类来创建神奇的语句,因为它们可以保存值,我认为这就是您所需要的。
请查看此源代码以查看一些示例。
https://stackoverflow.com/questions/53204167
复制相似问题