[IPython-user] repeat multiple command

Fernando Perez Fernando.Perez at colorado.edu
Fri Mar 17 17:09:08 CST 2006


John Hunter wrote:
> 
> Suppose I type a multiline command in ipython and want to reexecute
> the batch.  Eg,
> 
> 
> In [36]: for i in range(4):
>    ....:     if i>1:
>    ....:         big.append(i)
>    ....:
> ------------------------------------------------------------
> Traceback (most recent call last):
>   File "<ipython console>", line 3, in ?
> NameError: name 'big' is not defined
> 
> and realize, oops, I forgot to define "big".  So the I want to do
> 
> In [37]: big = []
> 
> and then rerun all the lines from In[36] .
> 
> Magic incantation?

In [1]: for i in range(4):
    ...:     if i>1:
    ...:         big.append(i)
    ...:
    ...:
---------------------------------------------------------------------------
exceptions.NameError                                 Traceback (most recent 
call last)

/home/fperez/<ipython console>

NameError: name 'big' is not defined

In [2]: big=[]

In [3]: exec In[1]

In [4]: big
Out[4]: [2, 3]

Discussion:  In[] is like a list holding all inputs as strings, so you can 
just repeat it.  Internally, macro uses it and does the slicing for you, but 
macro is little more than a light convenience wrapper around exec and In[]. 
If you think you'll repeat it many times, name it as a macro, which will 
require less typing to recall:

In [6]: macro mm 1
Macro `mm` created. To execute, type its name (without quotes).
Macro contents:
for i in range(4):
     if i>1:
         big.append(i)


In [7]: mm
Out[7]: Executing Macro...

In [9]: big
Out[9]: [2, 3, 2, 3]

In [10]: mm
Out[10]: Executing Macro...

In [12]: big
Out[12]: [2, 3, 2, 3, 2, 3]

In [13]: big=[]

In [14]: mm
Out[14]: Executing Macro...

In [16]: big
Out[16]: [2, 3]



Cheers,

f




More information about the IPython-user mailing list