##// END OF EJS Templates
Update posix process piping to use pexpect-u with a unicode interface.
Update posix process piping to use pexpect-u with a unicode interface.

File last commit:

r5426:180f7916
r5432:8ceb9ae0
Show More
storemagic.py
188 lines | 5.9 KiB | text/x-python | PythonLexer
vivainio
aliases can be %store'd
r166 # -*- coding: utf-8 -*-
"""
%store magic for lightweight persistence.
Thomas Kluyver
Improve documentation for extensions, and for storemagic extension.
r5426 Stores variables, aliases and macros in IPython's database. Stored values will
be automatically restored whenever the extension is loaded.
Fernando Perez
Add docstring explaining how to enable the `storemagic` extension....
r5379
Thomas Kluyver
Improve documentation for extensions, and for storemagic extension.
r5426 To enable this functionality, list it in your default profile
`ipython_config.py` file::
Fernando Perez
Add docstring explaining how to enable the `storemagic` extension....
r5379
Thomas Kluyver
Improve documentation for extensions, and for storemagic extension.
r5426 c.InteractiveShellApp.extensions = ['storemagic']
Fernando Perez
Add docstring explaining how to enable the `storemagic` extension....
r5379
Thomas Kluyver
Improve documentation for extensions, and for storemagic extension.
r5426 Or to use it temporarily, run this in your IPython session::
%load_ext storemagic
Fernando Perez
Add docstring explaining how to enable the `storemagic` extension....
r5379
vivainio
aliases can be %store'd
r166 """
Brian Granger
Continuing a massive refactor of everything.
r2205 from IPython.core.error import TryNext, UsageError
Thomas Kluyver
Restore pspersistence, including %store magic, as an extension.
r5378 from IPython.utils import pickleshare
vivainio
Grand Persistence Overhaul, featuring PickleShare. startup...
r165
vivainio
fixed missing import in pspersistence, Hans Meine's patch
r246 import inspect,pickle,os,sys,textwrap
Brian Granger
FakeModule.py => core/fakemodule.py and updated tests and imports.
r2020 from IPython.core.fakemodule import FakeModule
vivainio
Grand Persistence Overhaul, featuring PickleShare. startup...
r165
Thomas Kluyver
Restore pspersistence, including %store magic, as an extension.
r5378 def restore_aliases(ip):
fperez
Defaults rename, clean up api to use properties or direct access rather than...
r284 staliases = ip.db.get('stored_aliases', {})
vivainio
aliases can be %store'd
r166 for k,v in staliases.items():
#print "restore alias",k,v # dbg
vivainio
callable alias fixes
r783 #self.alias_table[k] = v
Thomas Kluyver
Restore pspersistence, including %store magic, as an extension.
r5378 ip.alias_manager.define_alias(k,v)
vivainio
aliases can be %store'd
r166
vivainio
Grand Persistence Overhaul, featuring PickleShare. startup...
r165 def refresh_variables(ip):
fperez
Defaults rename, clean up api to use properties or direct access rather than...
r284 db = ip.db
vivainio
Grand Persistence Overhaul, featuring PickleShare. startup...
r165 for key in db.keys('autorestore/*'):
# strip autorestore
justkey = os.path.basename(key)
try:
obj = db[key]
except KeyError:
print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % justkey
print "The error was:",sys.exc_info()[0]
else:
#print "restored",justkey,"=",obj #dbg
fperez
Defaults rename, clean up api to use properties or direct access rather than...
r284 ip.user_ns[justkey] = obj
Bernardo B. Marques
remove all trailling spaces
r4872
vivainio
Grand Persistence Overhaul, featuring PickleShare. startup...
r165
vivainio
store dhist persistently in db
r713 def restore_dhist(ip):
Thomas Kluyver
Restore pspersistence, including %store magic, as an extension.
r5378 ip.user_ns['_dh'] = ip.db.get('dhist',[])
Bernardo B. Marques
remove all trailling spaces
r4872
Thomas Kluyver
Restore pspersistence, including %store magic, as an extension.
r5378 def restore_data(ip):
vivainio
Grand Persistence Overhaul, featuring PickleShare. startup...
r165 refresh_variables(ip)
Thomas Kluyver
Restore pspersistence, including %store magic, as an extension.
r5378 restore_aliases(ip)
restore_dhist(ip)
vivainio
Grand Persistence Overhaul, featuring PickleShare. startup...
r165
def magic_store(self, parameter_s=''):
"""Lightweight persistence for python variables.
Thomas Kluyver
Improve documentation for extensions, and for storemagic extension.
r5426 Example::
Bernardo B. Marques
remove all trailling spaces
r4872
Thomas Kluyver
Improve documentation for extensions, and for storemagic extension.
r5426 In [1]: l = ['hello',10,'world']
In [2]: %store l
In [3]: exit
Bernardo B. Marques
remove all trailling spaces
r4872
Thomas Kluyver
Improve documentation for extensions, and for storemagic extension.
r5426 (IPython session is closed and started again...)
Bernardo B. Marques
remove all trailling spaces
r4872
Thomas Kluyver
Improve documentation for extensions, and for storemagic extension.
r5426 ville@badger:~$ ipython
In [1]: l
Out[1]: ['hello', 10, 'world']
Bernardo B. Marques
remove all trailling spaces
r4872
vivainio
Grand Persistence Overhaul, featuring PickleShare. startup...
r165 Usage:
Bernardo B. Marques
remove all trailling spaces
r4872
Thomas Kluyver
Improve documentation for extensions, and for storemagic extension.
r5426 * ``%store`` - Show list of all variables and their current values
* ``%store spam`` - Store the *current* value of the variable spam to disk
* ``%store -d spam`` - Remove the variable and its value from storage
* ``%store -z`` - Remove all variables from storage
* ``%store -r`` - Refresh all variables from store (delete current vals)
* ``%store foo >a.txt`` - Store value of foo to new file a.txt
* ``%store foo >>a.txt`` - Append value of foo to file a.txt
Bernardo B. Marques
remove all trailling spaces
r4872
vivainio
Grand Persistence Overhaul, featuring PickleShare. startup...
r165 It should be noted that if you change the value of a variable, you
need to %store it again if you want to persist the new value.
Bernardo B. Marques
remove all trailling spaces
r4872
vivainio
Grand Persistence Overhaul, featuring PickleShare. startup...
r165 Note also that the variables will need to be pickleable; most basic
Thomas Kluyver
Improve documentation for extensions, and for storemagic extension.
r5426 python types can be safely %store'd.
Bernardo B. Marques
remove all trailling spaces
r4872
vivainio
some docstring changes
r476 Also aliases can be %store'd across sessions.
vivainio
Grand Persistence Overhaul, featuring PickleShare. startup...
r165 """
Bernardo B. Marques
remove all trailling spaces
r4872
vivainio
Grand Persistence Overhaul, featuring PickleShare. startup...
r165 opts,argsl = self.parse_options(parameter_s,'drz',mode='string')
args = argsl.split(None,1)
Thomas Kluyver
Restore pspersistence, including %store magic, as an extension.
r5378 ip = self.shell
fperez
Defaults rename, clean up api to use properties or direct access rather than...
r284 db = ip.db
vivainio
Grand Persistence Overhaul, featuring PickleShare. startup...
r165 # delete
if opts.has_key('d'):
try:
todel = args[0]
except IndexError:
Ville M. Vainio
pspersistence report UsageError's instead of crashing on 'error'
r1223 raise UsageError('You must provide the variable to forget')
vivainio
Grand Persistence Overhaul, featuring PickleShare. startup...
r165 else:
try:
vivainio
aliases can be %store'd
r166 del db['autorestore/' + todel]
vivainio
Grand Persistence Overhaul, featuring PickleShare. startup...
r165 except:
Ville M. Vainio
pspersistence report UsageError's instead of crashing on 'error'
r1223 raise UsageError("Can't delete variable '%s'" % todel)
vivainio
Grand Persistence Overhaul, featuring PickleShare. startup...
r165 # reset
elif opts.has_key('z'):
vivainio
aliases can be %store'd
r166 for k in db.keys('autorestore/*'):
del db[k]
vivainio
Grand Persistence Overhaul, featuring PickleShare. startup...
r165
elif opts.has_key('r'):
refresh_variables(ip)
Bernardo B. Marques
remove all trailling spaces
r4872
vivainio
Grand Persistence Overhaul, featuring PickleShare. startup...
r165 # run without arguments -> list variables & values
elif not args:
vars = self.db.keys('autorestore/*')
Bernardo B. Marques
remove all trailling spaces
r4872 vars.sort()
vivainio
Grand Persistence Overhaul, featuring PickleShare. startup...
r165 if vars:
size = max(map(len,vars))
else:
size = 0
Bernardo B. Marques
remove all trailling spaces
r4872
vivainio
Grand Persistence Overhaul, featuring PickleShare. startup...
r165 print 'Stored variables and their in-db values:'
fmt = '%-'+str(size)+'s -> %s'
vivainio
aliases can be %store'd
r166 get = db.get
vivainio
Grand Persistence Overhaul, featuring PickleShare. startup...
r165 for var in vars:
justkey = os.path.basename(var)
# print 30 first characters from every var
print fmt % (justkey,repr(get(var,'<unavailable>'))[:50])
Bernardo B. Marques
remove all trailling spaces
r4872
vivainio
Grand Persistence Overhaul, featuring PickleShare. startup...
r165 # default action - store the variable
else:
# %store foo >file.txt or >>file.txt
if len(args) > 1 and args[1].startswith('>'):
fnam = os.path.expanduser(args[1].lstrip('>').lstrip())
if args[1].startswith('>>'):
fil = open(fnam,'a')
else:
fil = open(fnam,'w')
obj = ip.ev(args[0])
print "Writing '%s' (%s) to file '%s'." % (args[0],
obj.__class__.__name__, fnam)
Bernardo B. Marques
remove all trailling spaces
r4872
vivainio
Grand Persistence Overhaul, featuring PickleShare. startup...
r165 if not isinstance (obj,basestring):
vivainio
Fix %store to avoid "%store obj.attr" half-success (and fail explicitly).
r243 from pprint import pprint
vivainio
Grand Persistence Overhaul, featuring PickleShare. startup...
r165 pprint(obj,fil)
else:
fil.write(obj)
if not obj.endswith('\n'):
fil.write('\n')
Bernardo B. Marques
remove all trailling spaces
r4872
vivainio
Grand Persistence Overhaul, featuring PickleShare. startup...
r165 fil.close()
return
Bernardo B. Marques
remove all trailling spaces
r4872
vivainio
Grand Persistence Overhaul, featuring PickleShare. startup...
r165 # %store foo
vivainio
aliases can be %store'd
r166 try:
fperez
Defaults rename, clean up api to use properties or direct access rather than...
r284 obj = ip.user_ns[args[0]]
vivainio
Fix %store to avoid "%store obj.attr" half-success (and fail explicitly).
r243 except KeyError:
vivainio
aliases can be %store'd
r166 # it might be an alias
Brian Granger
Massive refactoring of of the core....
r2245 # This needs to be refactored to use the new AliasManager stuff.
Thomas Kluyver
Restore pspersistence, including %store magic, as an extension.
r5378 if args[0] in self.alias_manager:
name = args[0]
nargs, cmd = self.alias_manager.alias_table[ name ]
vivainio
aliases can be %store'd
r166 staliases = db.get('stored_aliases',{})
Thomas Kluyver
Restore pspersistence, including %store magic, as an extension.
r5378 staliases[ name ] = cmd
Bernardo B. Marques
remove all trailling spaces
r4872 db['stored_aliases'] = staliases
Thomas Kluyver
Restore pspersistence, including %store magic, as an extension.
r5378 print "Alias stored: %s (%s)" % (name, cmd)
vivainio
aliases can be %store'd
r166 return
vivainio
Fix %store to avoid "%store obj.attr" half-success (and fail explicitly).
r243 else:
Ville M. Vainio
pspersistence report UsageError's instead of crashing on 'error'
r1223 raise UsageError("Unknown variable '%s'" % args[0])
Bernardo B. Marques
remove all trailling spaces
r4872
vivainio
aliases can be %store'd
r166 else:
if isinstance(inspect.getmodule(obj), FakeModule):
print textwrap.dedent("""\
Bernardo B. Marques
remove all trailling spaces
r4872 Warning:%s is %s
vivainio
aliases can be %store'd
r166 Proper storage of interactively declared classes (or instances
of those classes) is not possible! Only instances
of classes in real modules on file system can be %%store'd.
Bernardo B. Marques
remove all trailling spaces
r4872 """ % (args[0], obj) )
vivainio
aliases can be %store'd
r166 return
#pickled = pickle.dumps(obj)
self.db[ 'autorestore/' + args[0] ] = obj
print "Stored '%s' (%s)" % (args[0], obj.__class__.__name__)
vivainio
Grand Persistence Overhaul, featuring PickleShare. startup...
r165
Thomas Kluyver
Restore pspersistence, including %store magic, as an extension.
r5378 def load_ipython_extension(ip):
ip.define_magic('store', magic_store)
restore_data(ip)