##// END OF EJS Templates
Update docs on %store magic.
Thomas Kluyver -
Show More
@@ -1,208 +1,203
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 %store magic for lightweight persistence.
4 4
5 Stores variables, aliases and macros in IPython's database. Stored values will
6 be automatically restored whenever the extension is loaded.
5 Stores variables, aliases and macros in IPython's database.
7 6
8 To enable this functionality, list it in your default profile
9 `ipython_config.py` file::
7 To automatically restore stored variables at startup, add this to your
8 :file:`ipython_config.py` file::
10 9
11 c.InteractiveShellApp.extensions = ['storemagic']
12
13 Or to use it temporarily, run this in your IPython session::
14
15 %load_ext storemagic
10 c.StoreMagic.autorestore = True
16 11
17 12 """
18 13
19 14 from IPython.core.error import TryNext, UsageError
20 15 from IPython.core.plugin import Plugin
21 16 from IPython.utils import pickleshare
22 17 from IPython.utils.traitlets import Bool, Instance
23 18
24 19 import inspect,pickle,os,sys,textwrap
25 20 from IPython.core.fakemodule import FakeModule
26 21
27 22 def restore_aliases(ip):
28 23 staliases = ip.db.get('stored_aliases', {})
29 24 for k,v in staliases.items():
30 25 #print "restore alias",k,v # dbg
31 26 #self.alias_table[k] = v
32 27 ip.alias_manager.define_alias(k,v)
33 28
34 29
35 30 def refresh_variables(ip):
36 31 db = ip.db
37 32 for key in db.keys('autorestore/*'):
38 33 # strip autorestore
39 34 justkey = os.path.basename(key)
40 35 try:
41 36 obj = db[key]
42 37 except KeyError:
43 38 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % justkey
44 39 print "The error was:",sys.exc_info()[0]
45 40 else:
46 41 #print "restored",justkey,"=",obj #dbg
47 42 ip.user_ns[justkey] = obj
48 43
49 44
50 45 def restore_dhist(ip):
51 46 ip.user_ns['_dh'] = ip.db.get('dhist',[])
52 47
53 48 def restore_data(ip):
54 49 refresh_variables(ip)
55 50 restore_aliases(ip)
56 51 restore_dhist(ip)
57 52
58 53 def magic_store(self, parameter_s=''):
59 54 """Lightweight persistence for python variables.
60 55
61 56 Example::
62 57
63 58 In [1]: l = ['hello',10,'world']
64 59 In [2]: %store l
65 60 In [3]: exit
66 61
67 62 (IPython session is closed and started again...)
68 63
69 64 ville@badger:~$ ipython
70 65 In [1]: l
71 66 Out[1]: ['hello', 10, 'world']
72 67
73 68 Usage:
74 69
75 70 * ``%store`` - Show list of all variables and their current values
76 71 * ``%store spam`` - Store the *current* value of the variable spam to disk
77 72 * ``%store -d spam`` - Remove the variable and its value from storage
78 73 * ``%store -z`` - Remove all variables from storage
79 74 * ``%store -r`` - Refresh all variables from store (delete current vals)
80 75 * ``%store foo >a.txt`` - Store value of foo to new file a.txt
81 76 * ``%store foo >>a.txt`` - Append value of foo to file a.txt
82 77
83 78 It should be noted that if you change the value of a variable, you
84 79 need to %store it again if you want to persist the new value.
85 80
86 81 Note also that the variables will need to be pickleable; most basic
87 82 python types can be safely %store'd.
88 83
89 84 Also aliases can be %store'd across sessions.
90 85 """
91 86
92 87 opts,argsl = self.parse_options(parameter_s,'drz',mode='string')
93 88 args = argsl.split(None,1)
94 89 ip = self.shell
95 90 db = ip.db
96 91 # delete
97 92 if opts.has_key('d'):
98 93 try:
99 94 todel = args[0]
100 95 except IndexError:
101 96 raise UsageError('You must provide the variable to forget')
102 97 else:
103 98 try:
104 99 del db['autorestore/' + todel]
105 100 except:
106 101 raise UsageError("Can't delete variable '%s'" % todel)
107 102 # reset
108 103 elif opts.has_key('z'):
109 104 for k in db.keys('autorestore/*'):
110 105 del db[k]
111 106
112 107 elif opts.has_key('r'):
113 108 refresh_variables(ip)
114 109
115 110
116 111 # run without arguments -> list variables & values
117 112 elif not args:
118 113 vars = self.db.keys('autorestore/*')
119 114 vars.sort()
120 115 if vars:
121 116 size = max(map(len,vars))
122 117 else:
123 118 size = 0
124 119
125 120 print 'Stored variables and their in-db values:'
126 121 fmt = '%-'+str(size)+'s -> %s'
127 122 get = db.get
128 123 for var in vars:
129 124 justkey = os.path.basename(var)
130 125 # print 30 first characters from every var
131 126 print fmt % (justkey,repr(get(var,'<unavailable>'))[:50])
132 127
133 128 # default action - store the variable
134 129 else:
135 130 # %store foo >file.txt or >>file.txt
136 131 if len(args) > 1 and args[1].startswith('>'):
137 132 fnam = os.path.expanduser(args[1].lstrip('>').lstrip())
138 133 if args[1].startswith('>>'):
139 134 fil = open(fnam,'a')
140 135 else:
141 136 fil = open(fnam,'w')
142 137 obj = ip.ev(args[0])
143 138 print "Writing '%s' (%s) to file '%s'." % (args[0],
144 139 obj.__class__.__name__, fnam)
145 140
146 141
147 142 if not isinstance (obj,basestring):
148 143 from pprint import pprint
149 144 pprint(obj,fil)
150 145 else:
151 146 fil.write(obj)
152 147 if not obj.endswith('\n'):
153 148 fil.write('\n')
154 149
155 150 fil.close()
156 151 return
157 152
158 153 # %store foo
159 154 try:
160 155 obj = ip.user_ns[args[0]]
161 156 except KeyError:
162 157 # it might be an alias
163 158 # This needs to be refactored to use the new AliasManager stuff.
164 159 if args[0] in self.alias_manager:
165 160 name = args[0]
166 161 nargs, cmd = self.alias_manager.alias_table[ name ]
167 162 staliases = db.get('stored_aliases',{})
168 163 staliases[ name ] = cmd
169 164 db['stored_aliases'] = staliases
170 165 print "Alias stored: %s (%s)" % (name, cmd)
171 166 return
172 167 else:
173 168 raise UsageError("Unknown variable '%s'" % args[0])
174 169
175 170 else:
176 171 if isinstance(inspect.getmodule(obj), FakeModule):
177 172 print textwrap.dedent("""\
178 173 Warning:%s is %s
179 174 Proper storage of interactively declared classes (or instances
180 175 of those classes) is not possible! Only instances
181 176 of classes in real modules on file system can be %%store'd.
182 177 """ % (args[0], obj) )
183 178 return
184 179 #pickled = pickle.dumps(obj)
185 180 self.db[ 'autorestore/' + args[0] ] = obj
186 181 print "Stored '%s' (%s)" % (args[0], obj.__class__.__name__)
187 182
188 183
189 184 class StoreMagic(Plugin):
190 185 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
191 186 autorestore = Bool(False, config=True)
192 187
193 188 def __init__(self, shell, config):
194 189 super(StoreMagic, self).__init__(shell=shell, config=config)
195 190 shell.define_magic('store', magic_store)
196 191
197 192 if self.autorestore:
198 193 restore_data(shell)
199 194
200 195 _loaded = False
201 196
202 197 def load_ipython_extension(ip):
203 198 """Load the extension in IPython."""
204 199 global _loaded
205 200 if not _loaded:
206 201 plugin = StoreMagic(shell=ip, config=ip.config)
207 202 ip.plugin_manager.register_plugin('storemagic', plugin)
208 203 _loaded = True
@@ -1,154 +1,155
1 1 ================================================
2 2 Development version
3 3 ================================================
4 4
5 5 The changes listed here are a brief summary of the substantial work on IPython
6 6 since the 0.11.x release series. For more details, please consult the actual
7 7 source.
8 8
9 9 Main `ipython` branch
10 10 =====================
11 11
12 12
13 13 New features
14 14 ------------
15 15
16 16 .. Expand on this:
17 17 * **HTML Notebook**: A powerful new interface puts IPython in your browser. You
18 18 can start it with the command ``ipython notebook``. See :ref:`the Notebook
19 19 docs <htmlnotebook>` for technical details.
20 20
21 21 * **Tabbed QtConsole**: The QtConsole now supports starting multiple kernels in
22 22 tabs, and has a menubar, so it looks and behaves more like a real application.
23 23 Keyboard enthusiasts can disable the menubar with ctrl-shift-M (:ghpull:`887`).
24 24
25 25 * **Python 3 compatibility**: IPython can now be installed from a single
26 26 codebase on Python 2 and Python 3. The installation process for Python 3
27 27 automatically runs 2to3. The same 'default' profile is now used for
28 28 Python 2 and 3 (the previous version had a separate 'python3' profile).
29 29
30 30 * **PyPy support**: The terminal interface to IPython now runs under
31 31 `PyPy <http://pypy.org/>`_.
32 32
33 33 * **SSH Tunnels**: In 0.11, the :mod:`IPython.parallel` Client could tunnel its
34 34 connections to the Controller via ssh. Now, the QtConsole :ref:`supports
35 35 <ssh_tunnels>` ssh tunneling, as do parallel engines.
36 36
37 37 * **relaxed command-line parsing**: 0.11 was released with overly-strict
38 38 command-line parsing, preventing the ability to specify arguments with spaces,
39 39 e.g. ``ipython --pylab qt`` or ``ipython -c "print 'hi'"``. This has
40 40 been fixed, by using argparse. The new parsing is a strict superset of 0.11, so
41 41 any commands in 0.11 should still work in 0.12.
42 42
43 43 * **HistoryAccessor**: The :class:`~IPython.core.history.HistoryManager` class for
44 44 interacting with your IPython SQLite history database has been split, adding
45 45 a parent :class:`~IPython.core.history.HistoryAccessor` class, so that users can
46 46 write code to access and search their IPython history without being in an IPython
47 47 session (:ghpull:`824`).
48 48
49 49 * **kernel %gui and %pylab**: The ``%gui`` and ``%pylab`` magics have been restored
50 50 to the IPython kernel (e.g. in the qtconsole or notebook). This allows activation
51 51 of pylab-mode, or eventloop integration after starting the kernel, which was
52 52 unavailable in 0.11. Unlike in the terminal, this can be set only once, and
53 53 cannot be changed.
54 54
55 55 * **%config**: A new ``%config`` magic has been added, giving easy access to the
56 56 IPython configuration system at runtime (:ghpull:`923`).
57 57
58 58 * **Standalone Kernel**: ``ipython kernel`` subcommand has been added, to allow
59 59 starting a standalone kernel, that can be used with various frontends.
60 60
61 61 * **Multiline History**: Multiline readline history has been restored to the
62 62 Terminal frontend by default (:ghpull:`838`).
63 63
64 64 * **%store**: The ``%store`` magic from earlier versions has been updated and
65 placed in an extension, :ref:`extensions_storemagic`. Add 'storemagic' to ``c.InteractiveShellApp.extensions``
66 in ipython_config.py to enable it (:ghpull:`1029`).
65 re-enabled (:ref:`extensions_storemagic`; :ghpull:`1029`). To autorestore
66 stored variables on startup, specify ``c.StoreMagic.autorestore = True`` in
67 :file:`ipython_config.py`.
67 68
68 69
69 70
70 71 Major Bugs fixed
71 72 ----------------
72 73
73 74 * Simple configuration errors should no longer crash IPython. In 0.11, errors in
74 75 config files, as well as invalid trait values, could crash IPython. Now, such
75 76 errors are reported, and help is displayed.
76 77
77 78 * Certain SyntaxErrors no longer crash IPython (e.g. just typing keywords, such as
78 79 ``return``, ``break``, etc.). See :ghissue:`704`.
79 80
80 81 * IPython path utils, such as :func:`~IPython.utils.path.get_ipython_dir` now check
81 82 for write permissions, so IPython should function on systems where the default
82 83 path resolution might point to a read-only location, such as ``HOMESHARE`` on
83 84 Windows (:ghissue:`669`).
84 85
85 86 * :func:`raw_input` now works in the kernel when multiple frontends are in use. The
86 87 request will be sent to the frontend that made the request, and an exception is
87 88 raised if that frontend does not support stdin requests (e.g. the notebook)
88 89 (:ghissue:`673`).
89 90
90 91 * :mod:`zmq` version detection no longer uses simple lexicographical comparison to
91 92 check minimum version, which prevents 0.11 from working with pyzmq-2.1.10
92 93 (:ghpull:`758`).
93 94
94 95 * A bug in PySide < 1.0.7 caused crashes on OSX when tooltips were shown
95 96 (:ghissue:`711`). these tooltips are now disabled on old PySide (:ghpull:`963`).
96 97
97 98 * IPython no longer crashes when started on recent versions of Python 3 in
98 99 Windows (:ghissue:`737`).
99 100
100 101 * Instances of classes defined interactively can now be pickled (:ghissue:`29`;
101 102 :ghpull:`648`). Note that pickling saves a reference to the class definition,
102 103 so unpickling the instances will only work where the class has been defined.
103 104
104 105 .. * use bullet list
105 106
106 107 Backwards incompatible changes
107 108 ------------------------------
108 109
109 110 * IPython connection information is no longer specified via ip/port directly,
110 111 rather via json connection files. These files are stored in the security
111 112 directory, and enable us to turn on HMAC message authentication by default,
112 113 significantly improving the security of kernels. Various utility functions
113 114 have been added to :mod:`IPython.lib.kernel`, for easier connecting to existing
114 115 kernels.
115 116
116 117 * :class:`~IPython.zmq.kernelmanager.KernelManager` now has one ip, and several port
117 118 traits, rather than several ip/port pair ``_addr`` traits. This better matches the
118 119 rest of the code, where the ip cannot not be set separately for each channel.
119 120
120 121 * Custom prompts are now configured using a new class,
121 122 :class:`~IPython.core.prompts.PromptManager`, which has traits for :attr:`in_template`,
122 123 :attr:`in2_template` (the ``...:`` continuation prompt), :attr:`out_template`
123 124 and :attr:`rewrite_template`. This uses Python's string formatting system, so
124 125 you can use ``{time}`` and ``{cwd}``, although we have preserved the abbreviations
125 126 from previous versions, e.g. ``\#`` (prompt number) and ``\w`` (working
126 127 directory). For the list of available fields, refer to the source of
127 128 :file:`IPython/core/prompts.py`.
128 129
129 130 * The class inheritance of the Launchers in :mod:`IPython.parallel.apps.launcher`
130 131 used by ipcluster has changed, so that trait names are more consistent across
131 132 batch systems. This may require a few renames in your config files, if you
132 133 customized the command-line args for launching controllers and engines. The
133 134 configurable names have also been changed to be clearer that they point to class
134 135 names, and can now be specified by name only, rather than requiring the full
135 136 import path of each class, e.g.::
136 137
137 138 IPClusterEngines.engine_launcher = 'IPython.parallel.apps.launcher.MPIExecEngineSetLauncher'
138 139 IPClusterStart.controller_launcher = 'IPython.parallel.apps.launcher.SSHControllerLauncher'
139 140
140 141 would now be specified as::
141 142
142 143 IPClusterEngines.engine_launcher_class = 'MPIExec'
143 144 IPClusterStart.controller_launcher_class = 'SSH'
144 145
145 146 The full path will still work, and is necessary for using custom launchers not in
146 147 IPython's launcher module.
147 148
148 149 * For embedding a shell, note that the parameter ``user_global_ns`` has been
149 150 replaced by ``user_module``, and expects a module-like object, rather than
150 151 a namespace dict. The ``user_ns`` parameter works the same way as before, and
151 152 calling :func:`~IPython.frontend.terminal.embed.embed` with no arguments still
152 153 works the same way.
153 154
154 155 .. * use bullet list
General Comments 0
You need to be logged in to leave comments. Login now