For the history command, specifically, 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, dump it to a file and read it back in.
This may seem a kludge, but I suspect it comes from the nature of IPython. It isn't actually an interpreter, but instead is a command line shell for the underlying interpreter. My suspicion is that the magic commands are handled inside IPython and do not go through the normal path of passing the command to the interpreter, capturing the output, and storing it in the command history as Out[n]. So it is not available for recall and assignment.
The alternative is that get_ipython().magic
simply returns None
.
Either way, the screen output d=for %history
is not available. You have to dump it to a file.
It seems to vary per magic command. alias
, for example, does return the 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]: