3

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?

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
tim
  • 9,896
  • 20
  • 81
  • 137
  • Try using a script with the .ipy suffix. See: http://stackoverflow.com/questions/21541319/how-to-run-ipython-script-from-the-command-line-syntax-error-with-magic-functi/21542596#21542596 – ditkin Jun 11 '14 at 13:50
  • I dont want to run it on startup, I just want to make the command available..., so where to put the script? – tim Jun 11 '14 at 13:56

1 Answers1

5

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
GuiltyDolphin
  • 768
  • 1
  • 7
  • 10
  • The problem with it is, that e.g. warnings are not outputted when using the macro (I fire warnings using `w.warn("blaaaaa")` in my python script. – tim Jun 12 '14 at 06:37
  • 1
    @tim - If you put w.filterwarnings("always") at the top of your script, it should always display warnings. There are some more display options [here](https://docs.python.org/2/library/warnings.html#the-warnings-filter). Note that warnings will be displayed each time with 'always'. – GuiltyDolphin Jun 12 '14 at 15:07