Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to store ipython magic output into variable

I am a python and Ipython beginner. This may be a trivial question. It is probably duplicated with other questions. However I do not know what key words I should search.

I have already known how to interactive with shell.

For example:

In [1]: a = !ls
In [2]: a
        ...same ls result as shell...
In [3]: type(a)
Out[3]: IPython.utils.text.SList

However, how to interactive with Ipython magic?

For example

In [1]: a = %history -t 
        ...Ipython result...
In [2]: a
In [3]: type(a)
Out[3]: NoneType
like image 403
Kir Chou Avatar asked May 05 '15 17:05

Kir Chou


2 Answers

with line magic, you can use result = %lsmagic to get result into variable; with cell magic, thanks to ipython, you can use _ to get result, for example:

%%some_magics
balabala
balabala

a = _
like image 133
李东泽 Avatar answered Sep 19 '22 13:09

李东泽


At least for the %history command, the output is written to stdout, so by redirecting that to a StringIO, you can capture the output without any temporary file, like this:

@register_line_magic
def get_magic_out(command):
    ipy = get_ipython()
    out = io.StringIO()

    with redirect_stdout(out):
        ipy.magic(command)

    return out.getvalue()

Gist: get_magic_out.py

Which you can then use like this:

In [1]: import get_magic_out as _ # We don't actually use the module, because of the `@register_line_magic` decorator

In [2]: x = %get_magic_out history

In [3]: x
Out[3]: 'import get_magic_out\nx = %get_magic_out history\n'
like image 30
Christian Reall-Fluharty Avatar answered Sep 21 '22 13:09

Christian Reall-Fluharty