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
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 = _
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With