Skip to content

Trash: Cookbook Custom magic examples

Carreau edited this page Sep 6, 2014 · 3 revisions

This is deprecated , just go here http://ipython.org/ipython-doc/dev/interactive/reference.html#defining-your-own-magics .


Magic commands are defined by the define_magic function in IPython.core.interactiveshell. Here's how to define your own %impall magic command that import all names from a module (and reloads the module):

 def doimp(self, arg):
     self.ex("import %s; reload(%s); from %s import *" % (
     arg,arg,arg)
     )
 
 ip.define_magic('impall', doimp)

Just save the text above to e.g. myimport.py and add import myimport to your IPYTHON_DIR/profile_default/ipython_config.py.


The above did not work for me in ipython 0.13, but this alternative did:

ipy_startup.py

 ip = get_ipython()
 
 def foo(self, bar):
     print bar
 
 ip.define_magic('footest', foo)

Run output

 In [1]: footest hello world
 hello world

%memit - Quick memory usage benchmarking

IPython user vene (Vlad Niculae) posted about custom magic function simplifying memory profiler interaction within IPython. Additionally psutil module is required for speedup on Linux and as necessary requirement on Windows. Script is hosted on gist.

Example usage from included docstring:

 In [3]: %memit np.zeros(1e7)
 best of 3: 76.402344 MB per loop
 Out[3]: 76.40234375
Clone this wiki locally