Storing macros in IPython

I found the answer to this in a couple of obscure places.

First, in the README found in $HOME/.ipython, it says, "For more information on configuring IPython, do: ipython config -h"

Doing that produces a bunch of help including the following advice:

To initialize a profile with the default configuration file, do::

  $> ipython profile create

and start editing `IPYTHONDIR/profile_default/ipython_config.py`

The old docs for this configuration file are here: Configuring the ipython command line application. The latest (as of Jan. 2020) are in the much improved section on Configuration and customization.

Finally, I found my answer in the docs for storemagic [Link updated, Jan. 2020]:

%store magic for lightweight persistence. Stores variables, aliases and macros in IPython’s database. To automatically restore stored variables at startup, add this to your ipython_config.py file:

c.StoreMagics.autorestore = True

Add that, restart IPython and bang! there are my macros. Cool!


As an alternative to defining a macro in the shell then storing it, you could just define the macro in a startup file. For example, you could put the following line into IPYTHONDIR/profile_default/ipython_config.py:

get_ipython().define_macro('foo','print "Foobarbatbizbuzzbonk"')

If you want to define a macro for a magic command, you could use something like this:

get_ipython().define_macro('clr',"""get_ipython().magic(u'%reset -sf')""");

I haven't figured out how to define a macro for a magic command with options that will accept arguments (e.g., typing 'rn tmp' instead of '%run -i tmp' to run the file tmp.py in ipython's namespace).


I must admit that sometimes finding a good documentation for ipython is a nightmare (for the basics). It seems like this interactive console has been created for really gurus of programming. At least, that is what I feel when trying to solve a simple issue like saving a variable for posterior use...something more than simple in matlab.

But to answer your qestion... try to open ipython normally just typing ipython and then write %store -r

It should recover your data with original name(s). I still do not know the use of storing variables into files or recovering just the variabels that I want. BTw, to know the names of your stored variables, type %store.

Hope it works for you.

Tags:

Ipython