storemagic.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. # -*- coding: utf-8 -*-
  2. """
  3. %store magic for lightweight persistence.
  4. Stores variables, aliases and macros in IPython's database.
  5. To automatically restore stored variables at startup, add this to your
  6. :file:`ipython_config.py` file::
  7. c.StoreMagics.autorestore = True
  8. """
  9. # Copyright (c) IPython Development Team.
  10. # Distributed under the terms of the Modified BSD License.
  11. import inspect, os, sys, textwrap
  12. from IPython.core.error import UsageError
  13. from IPython.core.magic import Magics, magics_class, line_magic
  14. from traitlets import Bool
  15. def restore_aliases(ip, alias=None):
  16. staliases = ip.db.get('stored_aliases', {})
  17. if alias is None:
  18. for k,v in staliases.items():
  19. #print "restore alias",k,v # dbg
  20. #self.alias_table[k] = v
  21. ip.alias_manager.define_alias(k,v)
  22. else:
  23. ip.alias_manager.define_alias(alias, staliases[alias])
  24. def refresh_variables(ip):
  25. db = ip.db
  26. for key in db.keys('autorestore/*'):
  27. # strip autorestore
  28. justkey = os.path.basename(key)
  29. try:
  30. obj = db[key]
  31. except KeyError:
  32. print("Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % justkey)
  33. print("The error was:", sys.exc_info()[0])
  34. else:
  35. #print "restored",justkey,"=",obj #dbg
  36. ip.user_ns[justkey] = obj
  37. def restore_dhist(ip):
  38. ip.user_ns['_dh'] = ip.db.get('dhist',[])
  39. def restore_data(ip):
  40. refresh_variables(ip)
  41. restore_aliases(ip)
  42. restore_dhist(ip)
  43. @magics_class
  44. class StoreMagics(Magics):
  45. """Lightweight persistence for python variables.
  46. Provides the %store magic."""
  47. autorestore = Bool(False, help=
  48. """If True, any %store-d variables will be automatically restored
  49. when IPython starts.
  50. """
  51. ).tag(config=True)
  52. def __init__(self, shell):
  53. super(StoreMagics, self).__init__(shell=shell)
  54. self.shell.configurables.append(self)
  55. if self.autorestore:
  56. restore_data(self.shell)
  57. @line_magic
  58. def store(self, parameter_s=''):
  59. """Lightweight persistence for python variables.
  60. Example::
  61. In [1]: l = ['hello',10,'world']
  62. In [2]: %store l
  63. In [3]: exit
  64. (IPython session is closed and started again...)
  65. ville@badger:~$ ipython
  66. In [1]: l
  67. NameError: name 'l' is not defined
  68. In [2]: %store -r
  69. In [3]: l
  70. Out[3]: ['hello', 10, 'world']
  71. Usage:
  72. * ``%store`` - Show list of all variables and their current
  73. values
  74. * ``%store spam bar`` - Store the *current* value of the variables spam
  75. and bar to disk
  76. * ``%store -d spam`` - Remove the variable and its value from storage
  77. * ``%store -z`` - Remove all variables from storage
  78. * ``%store -r`` - Refresh all variables, aliases and directory history
  79. from store (overwrite current vals)
  80. * ``%store -r spam bar`` - Refresh specified variables and aliases from store
  81. (delete current val)
  82. * ``%store foo >a.txt`` - Store value of foo to new file a.txt
  83. * ``%store foo >>a.txt`` - Append value of foo to file a.txt
  84. It should be noted that if you change the value of a variable, you
  85. need to %store it again if you want to persist the new value.
  86. Note also that the variables will need to be pickleable; most basic
  87. python types can be safely %store'd.
  88. Also aliases can be %store'd across sessions.
  89. To remove an alias from the storage, use the %unalias magic.
  90. """
  91. opts,argsl = self.parse_options(parameter_s,'drz',mode='string')
  92. args = argsl.split()
  93. ip = self.shell
  94. db = ip.db
  95. # delete
  96. if 'd' in opts:
  97. try:
  98. todel = args[0]
  99. except IndexError:
  100. raise UsageError('You must provide the variable to forget')
  101. else:
  102. try:
  103. del db['autorestore/' + todel]
  104. except:
  105. raise UsageError("Can't delete variable '%s'" % todel)
  106. # reset
  107. elif 'z' in opts:
  108. for k in db.keys('autorestore/*'):
  109. del db[k]
  110. elif 'r' in opts:
  111. if args:
  112. for arg in args:
  113. try:
  114. obj = db['autorestore/' + arg]
  115. except KeyError:
  116. try:
  117. restore_aliases(ip, alias=arg)
  118. except KeyError:
  119. print("no stored variable or alias %s" % arg)
  120. else:
  121. ip.user_ns[arg] = obj
  122. else:
  123. restore_data(ip)
  124. # run without arguments -> list variables & values
  125. elif not args:
  126. vars = db.keys('autorestore/*')
  127. vars.sort()
  128. if vars:
  129. size = max(map(len, vars))
  130. else:
  131. size = 0
  132. print('Stored variables and their in-db values:')
  133. fmt = '%-'+str(size)+'s -> %s'
  134. get = db.get
  135. for var in vars:
  136. justkey = os.path.basename(var)
  137. # print 30 first characters from every var
  138. print(fmt % (justkey, repr(get(var, '<unavailable>'))[:50]))
  139. # default action - store the variable
  140. else:
  141. # %store foo >file.txt or >>file.txt
  142. if len(args) > 1 and args[1].startswith('>'):
  143. fnam = os.path.expanduser(args[1].lstrip('>').lstrip())
  144. if args[1].startswith('>>'):
  145. fil = open(fnam, 'a')
  146. else:
  147. fil = open(fnam, 'w')
  148. with fil:
  149. obj = ip.ev(args[0])
  150. print("Writing '%s' (%s) to file '%s'." % (args[0],
  151. obj.__class__.__name__, fnam))
  152. if not isinstance (obj, str):
  153. from pprint import pprint
  154. pprint(obj, fil)
  155. else:
  156. fil.write(obj)
  157. if not obj.endswith('\n'):
  158. fil.write('\n')
  159. return
  160. # %store foo
  161. for arg in args:
  162. try:
  163. obj = ip.user_ns[arg]
  164. except KeyError:
  165. # it might be an alias
  166. name = arg
  167. try:
  168. cmd = ip.alias_manager.retrieve_alias(name)
  169. except ValueError:
  170. raise UsageError("Unknown variable '%s'" % name)
  171. staliases = db.get('stored_aliases',{})
  172. staliases[name] = cmd
  173. db['stored_aliases'] = staliases
  174. print("Alias stored: %s (%s)" % (name, cmd))
  175. return
  176. else:
  177. modname = getattr(inspect.getmodule(obj), '__name__', '')
  178. if modname == '__main__':
  179. print(textwrap.dedent("""\
  180. Warning:%s is %s
  181. Proper storage of interactively declared classes (or instances
  182. of those classes) is not possible! Only instances
  183. of classes in real modules on file system can be %%store'd.
  184. """ % (arg, obj) ))
  185. return
  186. #pickled = pickle.dumps(obj)
  187. db[ 'autorestore/' + arg ] = obj
  188. print("Stored '%s' (%s)" % (arg, obj.__class__.__name__))
  189. def load_ipython_extension(ip):
  190. """Load the extension in IPython."""
  191. ip.register_magics(StoreMagics)