tim
tim

Reputation: 10186

IPython: Alias which uses a magic function itself

I couldn't find anything about this so Im asking here: I want to create an alias in IPython which itself uses an IPython-magic-function.

That means: I often need to to retype

%run process.py

thus I'd like to create an alias like this:

%alias rp %run process.py

the creation works, but when calling rp, it says, that the command %run could not be found. Any ideas about how to do this?

Upvotes: 3

Views: 482

Answers (1)

GuiltyDolphin
GuiltyDolphin

Reputation: 778

Try this:

When you enter the IPython console, type %run process.py

Then you can use the %macro magic to bind rp to %run process.py.

Do so with the In storage of inputs.

%run process.py
%macro rp In[-2]

Should work!


%macro can also be used to cover a range of inputs, using the syntax %macro name range - where range can be an integer or integers in the form start-end.

For instance, if you wanted to time two functions with a single command you can specify the line ranges.

Define functions:

In[20]: def foo(x): return x
In[21]: def bar(x): return x*x

Time functions:

In[22]: %timeit foo(100)
10000000 loops, best of 3: 137 ns per loop
In[23]: %timeit bar(100)
10000000 loops, best of 3: 194 ns per loop

Bind macro to name time_fb:

In[24]: %macro time_fb 22-23

Macro bound:

Macro `time_fb` created. To execute, type its name (without quotes).
=== Macro contents: ===
get_ipython().magic('timeit foo(100)')
get_ipython().magic('timeit bar(100)')

Check it works:

In[25]: time_fb
10000000 loops, best of 3: 135 ns per loop
10000000 loops, best of 3: 192 ns per loop

Upvotes: 5

Related Questions