How to store ipython magic output in a variable

I am a python and beginner of Ipython. This may be a trivial question. This is probably duplicated with other questions. However, I do not know what keywords I should look for.

I already knew how to interact with the shell.

For instance:

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 interact with the magic of Ipython?

for instance

 In [1]: a = %history -t ...Ipython result... In [2]: a In [3]: type(a) Out[3]: NoneType 
+6
source share
3 answers

For the history command, in particular, the simplest solution is

 In [243]: history -t -f history.txt In [244]: with open('history.txt') as f: .....: HIST = [l.strip() for l in f] .....: In [245]: len(HIST) Out[245]: 258 In [246]: HIST[-1] Out[246]: "get_ipython().magic(u'history -t -f history.txt')" In [247]: 

Basically, upload it to a file and read it back.

It may seem kludge, but I suspect that it comes from the nature of IPython. This is actually not an interpreter, but instead a command-line shell for the interpreter. My suspicion is that magic commands are processed internally by IPython and do not go the usual way of passing commands to the interpreter, capturing the output and storing it in the command history as Out [n]. Therefore, it is not available for call and destination.

An alternative is that get_ipython().magic just returns None .

In any case, the d = screen output for %history not available. You must dump it to a file.

It seems that he is changing to a magic team. alias , for example, returns screen output

 In [288]: a=%alias Total number of aliases: 17 In [289]: a Out[289]: [('cat', 'cat'), ('clear', 'clear'), ('cp', 'cp'), ('ldir', 'ls -F -G -l %l | grep /$'), ('less', 'less'), ('lf', 'ls -F -l -G %l | grep ^-'), ('lk', 'ls -F -l -G %l | grep ^l'), ('ll', 'ls -F -l -G'), ('ls', 'ls -F -G'), ('lx', 'ls -F -l -G %l | grep ^-..x'), ('man', 'man'), ('mkdir', 'mkdir'), ('more', 'more'), ('mv', 'mv'), ('rm', 'rm'), ('rmdir', 'rmdir'), (u'show', u'echo')] In [290]: 
+2
source

I am working on an ipython reload project and want to have a quick way to select% run from previous statements. My solution was as follows.

 import os histvar = os.popen("ipython -c 'history -g'").read() #regex match / do stuff here 
0
source

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

 %%some_magics balabala balabala a = _ 
0
source

Source: https://habr.com/ru/post/986587/


All Articles