iPython自定义单元格魔术-将输出存储在变量中?

wfveoks0  于 2022-12-02  发布在  Python
关注(0)|答案(1)|浏览(120)

我最近发现了iPython魔术函数,并写了一些自定义魔术。我想使用单元格魔术来解析字符串,稍微修改一下,然后返回结果。有没有办法把我自定义的单元格魔术函数的输出存储在一个变量中?
我知道你可以像这样存储一个行幻函数的输出:

@register_line_magic
def linemagic(line, cell=None):
    #do something
    return line

hello = %linemagic hello
print(hello)

返回:

>>> hello

如果我有更大的字符串,我想使用单元魔术代替:

@register_cell_magic
def cellmagic(line, cell=None):
    #do something
    return cell

无法使用hello = %%cellmagic ...来存储结果。是否有其他方法来捕获函数输出?

jpfvwuh4

jpfvwuh41#

你可以使用IPython的输出缓存系统定义几个全局变量:

In [2]: from IPython.core.magic import register_cell_magic

In [3]: @register_cell_magic
   ...: def cellmagic(line, cell=None):
   ...:     #do something
   ...:     return cell
   ...:

In [4]: %%cellmagic
   ...: "line0"
   ...: "line1"
   ...: "line2"
   ...:
   ...:
Out[4]: '"line0"\n"line1"\n"line2"\n\n'

In [5]: _
Out[5]: '"line0"\n"line1"\n"line2"\n\n'

In [6]: _4
Out[6]: '"line0"\n"line1"\n"line2"\n\n'

In [8]: _i4
Out[8]: '%%cellmagic\n"line0"\n"line1"\n"line2"'

相关问题