##// END OF EJS Templates
fixed missing import in pspersistence, Hans Meine's patch
vivainio -
Show More
@@ -1,176 +1,176
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 %store magic for lightweight persistence.
4 4
5 5 Stores variables, aliases etc. in PickleShare database.
6 6
7 7 $Id: iplib.py 1107 2006-01-30 19:02:20Z vivainio $
8 8 """
9 9
10 10 import IPython.ipapi
11 11 ip = IPython.ipapi.get()
12 12
13 13 import pickleshare
14 14
15 import inspect,pickle,os,textwrap
15 import inspect,pickle,os,sys,textwrap
16 16 from IPython.FakeModule import FakeModule
17 17
18 18 def restore_aliases(self):
19 19 ip = self.getapi()
20 20 staliases = ip.getdb().get('stored_aliases', {})
21 21 for k,v in staliases.items():
22 22 #print "restore alias",k,v # dbg
23 23 self.alias_table[k] = v
24 24
25 25
26 26 def refresh_variables(ip):
27 27 db = ip.getdb()
28 28 for key in db.keys('autorestore/*'):
29 29 # strip autorestore
30 30 justkey = os.path.basename(key)
31 31 try:
32 32 obj = db[key]
33 33 except KeyError:
34 34 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % justkey
35 35 print "The error was:",sys.exc_info()[0]
36 36 else:
37 37 #print "restored",justkey,"=",obj #dbg
38 38 ip.user_ns()[justkey] = obj
39 39
40 40
41 41
42 42 def restore_data(self):
43 43 ip = self.getapi()
44 44 refresh_variables(ip)
45 45 restore_aliases(self)
46 46 raise IPython.ipapi.TryNext
47 47
48 48 ip.set_hook('late_startup_hook', restore_data)
49 49
50 50 def magic_store(self, parameter_s=''):
51 51 """Lightweight persistence for python variables.
52 52
53 53 Example:
54 54
55 55 ville@badger[~]|1> A = ['hello',10,'world']\\
56 56 ville@badger[~]|2> %store A\\
57 57 ville@badger[~]|3> Exit
58 58
59 59 (IPython session is closed and started again...)
60 60
61 61 ville@badger:~$ ipython -p pysh\\
62 62 ville@badger[~]|1> print A
63 63
64 64 ['hello', 10, 'world']
65 65
66 66 Usage:
67 67
68 68 %store - Show list of all variables and their current values\\
69 69 %store <var> - Store the *current* value of the variable to disk\\
70 70 %store -d <var> - Remove the variable and its value from storage\\
71 71 %store -z - Remove all variables from storage\\
72 72 %store -r - Refresh all variables from store (delete current vals)\\
73 73 %store foo >a.txt - Store value of foo to new file a.txt\\
74 74 %store foo >>a.txt - Append value of foo to file a.txt\\
75 75
76 76 It should be noted that if you change the value of a variable, you
77 77 need to %store it again if you want to persist the new value.
78 78
79 79 Note also that the variables will need to be pickleable; most basic
80 80 python types can be safely %stored.
81 81 """
82 82
83 83 opts,argsl = self.parse_options(parameter_s,'drz',mode='string')
84 84 args = argsl.split(None,1)
85 85 ip = self.getapi()
86 86 db = ip.getdb()
87 87 # delete
88 88 if opts.has_key('d'):
89 89 try:
90 90 todel = args[0]
91 91 except IndexError:
92 92 error('You must provide the variable to forget')
93 93 else:
94 94 try:
95 95 del db['autorestore/' + todel]
96 96 except:
97 97 error("Can't delete variable '%s'" % todel)
98 98 # reset
99 99 elif opts.has_key('z'):
100 100 for k in db.keys('autorestore/*'):
101 101 del db[k]
102 102
103 103 elif opts.has_key('r'):
104 104 refresh_variables(ip)
105 105
106 106
107 107 # run without arguments -> list variables & values
108 108 elif not args:
109 109 vars = self.db.keys('autorestore/*')
110 110 vars.sort()
111 111 if vars:
112 112 size = max(map(len,vars))
113 113 else:
114 114 size = 0
115 115
116 116 print 'Stored variables and their in-db values:'
117 117 fmt = '%-'+str(size)+'s -> %s'
118 118 get = db.get
119 119 for var in vars:
120 120 justkey = os.path.basename(var)
121 121 # print 30 first characters from every var
122 122 print fmt % (justkey,repr(get(var,'<unavailable>'))[:50])
123 123
124 124 # default action - store the variable
125 125 else:
126 126 # %store foo >file.txt or >>file.txt
127 127 if len(args) > 1 and args[1].startswith('>'):
128 128 fnam = os.path.expanduser(args[1].lstrip('>').lstrip())
129 129 if args[1].startswith('>>'):
130 130 fil = open(fnam,'a')
131 131 else:
132 132 fil = open(fnam,'w')
133 133 obj = ip.ev(args[0])
134 134 print "Writing '%s' (%s) to file '%s'." % (args[0],
135 135 obj.__class__.__name__, fnam)
136 136
137 137
138 138 if not isinstance (obj,basestring):
139 139 from pprint import pprint
140 140 pprint(obj,fil)
141 141 else:
142 142 fil.write(obj)
143 143 if not obj.endswith('\n'):
144 144 fil.write('\n')
145 145
146 146 fil.close()
147 147 return
148 148
149 149 # %store foo
150 150 try:
151 151 obj = ip.user_ns()[args[0]]
152 152 except KeyError:
153 153 # it might be an alias
154 154 if args[0] in self.alias_table:
155 155 staliases = db.get('stored_aliases',{})
156 156 staliases[ args[0] ] = self.alias_table[ args[0] ]
157 157 db['stored_aliases'] = staliases
158 158 print "Alias stored:", args[0], self.alias_table[ args[0] ]
159 159 return
160 160 else:
161 161 print "Error: unknown variable '%s'" % args[0]
162 162
163 163 else:
164 164 if isinstance(inspect.getmodule(obj), FakeModule):
165 165 print textwrap.dedent("""\
166 166 Warning:%s is %s
167 167 Proper storage of interactively declared classes (or instances
168 168 of those classes) is not possible! Only instances
169 169 of classes in real modules on file system can be %%store'd.
170 170 """ % (args[0], obj) )
171 171 return
172 172 #pickled = pickle.dumps(obj)
173 173 self.db[ 'autorestore/' + args[0] ] = obj
174 174 print "Stored '%s' (%s)" % (args[0], obj.__class__.__name__)
175 175
176 176 ip.expose_magic('store',magic_store)
General Comments 0
You need to be logged in to leave comments. Login now