##// END OF EJS Templates
aliases can be %store'd
vivainio -
Show More

The requested changes are too big and content was truncated. Show full diff

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