Show More
@@ -1,359 +1,357 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 |
|
2 | |||
3 | """ PickleShare - a small 'shelve' like datastore with concurrency support |
|
3 | """ PickleShare - a small 'shelve' like datastore with concurrency support | |
4 |
|
4 | |||
5 | Like shelve, a PickleShareDB object acts like a normal dictionary. Unlike |
|
5 | Like shelve, a PickleShareDB object acts like a normal dictionary. Unlike | |
6 | shelve, many processes can access the database simultaneously. Changing a |
|
6 | shelve, many processes can access the database simultaneously. Changing a | |
7 | value in database is immediately visible to other processes accessing the |
|
7 | value in database is immediately visible to other processes accessing the | |
8 | same database. |
|
8 | same database. | |
9 |
|
9 | |||
10 | Concurrency is possible because the values are stored in separate files. Hence |
|
10 | Concurrency is possible because the values are stored in separate files. Hence | |
11 | the "database" is a directory where *all* files are governed by PickleShare. |
|
11 | the "database" is a directory where *all* files are governed by PickleShare. | |
12 |
|
12 | |||
13 | Example usage:: |
|
13 | Example usage:: | |
14 |
|
14 | |||
15 | from pickleshare import * |
|
15 | from pickleshare import * | |
16 | db = PickleShareDB('~/testpickleshare') |
|
16 | db = PickleShareDB('~/testpickleshare') | |
17 | db.clear() |
|
17 | db.clear() | |
18 | print "Should be empty:",db.items() |
|
18 | print "Should be empty:",db.items() | |
19 | db['hello'] = 15 |
|
19 | db['hello'] = 15 | |
20 | db['aku ankka'] = [1,2,313] |
|
20 | db['aku ankka'] = [1,2,313] | |
21 | db['paths/are/ok/key'] = [1,(5,46)] |
|
21 | db['paths/are/ok/key'] = [1,(5,46)] | |
22 | print db.keys() |
|
22 | print db.keys() | |
23 | del db['aku ankka'] |
|
23 | del db['aku ankka'] | |
24 |
|
24 | |||
25 | This module is certainly not ZODB, but can be used for low-load |
|
25 | This module is certainly not ZODB, but can be used for low-load | |
26 | (non-mission-critical) situations where tiny code size trumps the |
|
26 | (non-mission-critical) situations where tiny code size trumps the | |
27 | advanced features of a "real" object database. |
|
27 | advanced features of a "real" object database. | |
28 |
|
28 | |||
29 | Installation guide: easy_install pickleshare |
|
29 | Installation guide: easy_install pickleshare | |
30 |
|
30 | |||
31 | Author: Ville Vainio <vivainio@gmail.com> |
|
31 | Author: Ville Vainio <vivainio@gmail.com> | |
32 | License: MIT open source license. |
|
32 | License: MIT open source license. | |
33 |
|
33 | |||
34 | """ |
|
34 | """ | |
35 |
|
35 | |||
36 | from IPython.external.path import path as Path |
|
36 | from IPython.external.path import path as Path | |
37 | import os,stat,time |
|
37 | import os,stat,time | |
38 | import cPickle as pickle |
|
38 | import cPickle as pickle | |
39 | import UserDict |
|
39 | import UserDict | |
40 | import warnings |
|
40 | import warnings | |
41 | import glob |
|
41 | import glob | |
42 |
|
42 | |||
43 | from sets import Set as set |
|
|||
44 |
|
||||
45 | def gethashfile(key): |
|
43 | def gethashfile(key): | |
46 | return ("%02x" % abs(hash(key) % 256))[-2:] |
|
44 | return ("%02x" % abs(hash(key) % 256))[-2:] | |
47 |
|
45 | |||
48 | _sentinel = object() |
|
46 | _sentinel = object() | |
49 |
|
47 | |||
50 | class PickleShareDB(UserDict.DictMixin): |
|
48 | class PickleShareDB(UserDict.DictMixin): | |
51 | """ The main 'connection' object for PickleShare database """ |
|
49 | """ The main 'connection' object for PickleShare database """ | |
52 | def __init__(self,root): |
|
50 | def __init__(self,root): | |
53 | """ Return a db object that will manage the specied directory""" |
|
51 | """ Return a db object that will manage the specied directory""" | |
54 | self.root = Path(root).expanduser().abspath() |
|
52 | self.root = Path(root).expanduser().abspath() | |
55 | if not self.root.isdir(): |
|
53 | if not self.root.isdir(): | |
56 | self.root.makedirs() |
|
54 | self.root.makedirs() | |
57 | # cache has { 'key' : (obj, orig_mod_time) } |
|
55 | # cache has { 'key' : (obj, orig_mod_time) } | |
58 | self.cache = {} |
|
56 | self.cache = {} | |
59 |
|
57 | |||
60 |
|
58 | |||
61 | def __getitem__(self,key): |
|
59 | def __getitem__(self,key): | |
62 | """ db['key'] reading """ |
|
60 | """ db['key'] reading """ | |
63 | fil = self.root / key |
|
61 | fil = self.root / key | |
64 | try: |
|
62 | try: | |
65 | mtime = (fil.stat()[stat.ST_MTIME]) |
|
63 | mtime = (fil.stat()[stat.ST_MTIME]) | |
66 | except OSError: |
|
64 | except OSError: | |
67 | raise KeyError(key) |
|
65 | raise KeyError(key) | |
68 |
|
66 | |||
69 | if fil in self.cache and mtime == self.cache[fil][1]: |
|
67 | if fil in self.cache and mtime == self.cache[fil][1]: | |
70 | return self.cache[fil][0] |
|
68 | return self.cache[fil][0] | |
71 | try: |
|
69 | try: | |
72 | # The cached item has expired, need to read |
|
70 | # The cached item has expired, need to read | |
73 | obj = pickle.load(fil.open()) |
|
71 | obj = pickle.load(fil.open()) | |
74 | except: |
|
72 | except: | |
75 | raise KeyError(key) |
|
73 | raise KeyError(key) | |
76 |
|
74 | |||
77 | self.cache[fil] = (obj,mtime) |
|
75 | self.cache[fil] = (obj,mtime) | |
78 | return obj |
|
76 | return obj | |
79 |
|
77 | |||
80 | def __setitem__(self,key,value): |
|
78 | def __setitem__(self,key,value): | |
81 | """ db['key'] = 5 """ |
|
79 | """ db['key'] = 5 """ | |
82 | fil = self.root / key |
|
80 | fil = self.root / key | |
83 | parent = fil.parent |
|
81 | parent = fil.parent | |
84 | if parent and not parent.isdir(): |
|
82 | if parent and not parent.isdir(): | |
85 | parent.makedirs() |
|
83 | parent.makedirs() | |
86 | pickled = pickle.dump(value,fil.open('w')) |
|
84 | pickled = pickle.dump(value,fil.open('w')) | |
87 | try: |
|
85 | try: | |
88 | self.cache[fil] = (value,fil.mtime) |
|
86 | self.cache[fil] = (value,fil.mtime) | |
89 | except OSError,e: |
|
87 | except OSError,e: | |
90 | if e.errno != 2: |
|
88 | if e.errno != 2: | |
91 | raise |
|
89 | raise | |
92 |
|
90 | |||
93 | def hset(self, hashroot, key, value): |
|
91 | def hset(self, hashroot, key, value): | |
94 | """ hashed set """ |
|
92 | """ hashed set """ | |
95 | hroot = self.root / hashroot |
|
93 | hroot = self.root / hashroot | |
96 | if not hroot.isdir(): |
|
94 | if not hroot.isdir(): | |
97 | hroot.makedirs() |
|
95 | hroot.makedirs() | |
98 | hfile = hroot / gethashfile(key) |
|
96 | hfile = hroot / gethashfile(key) | |
99 | d = self.get(hfile, {}) |
|
97 | d = self.get(hfile, {}) | |
100 | d.update( {key : value}) |
|
98 | d.update( {key : value}) | |
101 | self[hfile] = d |
|
99 | self[hfile] = d | |
102 |
|
100 | |||
103 |
|
101 | |||
104 |
|
102 | |||
105 | def hget(self, hashroot, key, default = _sentinel, fast_only = True): |
|
103 | def hget(self, hashroot, key, default = _sentinel, fast_only = True): | |
106 | """ hashed get """ |
|
104 | """ hashed get """ | |
107 | hroot = self.root / hashroot |
|
105 | hroot = self.root / hashroot | |
108 | hfile = hroot / gethashfile(key) |
|
106 | hfile = hroot / gethashfile(key) | |
109 |
|
107 | |||
110 | d = self.get(hfile, _sentinel ) |
|
108 | d = self.get(hfile, _sentinel ) | |
111 | #print "got dict",d,"from",hfile |
|
109 | #print "got dict",d,"from",hfile | |
112 | if d is _sentinel: |
|
110 | if d is _sentinel: | |
113 | if fast_only: |
|
111 | if fast_only: | |
114 | if default is _sentinel: |
|
112 | if default is _sentinel: | |
115 | raise KeyError(key) |
|
113 | raise KeyError(key) | |
116 |
|
114 | |||
117 | return default |
|
115 | return default | |
118 |
|
116 | |||
119 | # slow mode ok, works even after hcompress() |
|
117 | # slow mode ok, works even after hcompress() | |
120 | d = self.hdict(hashroot) |
|
118 | d = self.hdict(hashroot) | |
121 |
|
119 | |||
122 | return d.get(key, default) |
|
120 | return d.get(key, default) | |
123 |
|
121 | |||
124 | def hdict(self, hashroot): |
|
122 | def hdict(self, hashroot): | |
125 | """ Get all data contained in hashed category 'hashroot' as dict """ |
|
123 | """ Get all data contained in hashed category 'hashroot' as dict """ | |
126 | hfiles = self.keys(hashroot + "/*") |
|
124 | hfiles = self.keys(hashroot + "/*") | |
127 | hfiles.sort() |
|
125 | hfiles.sort() | |
128 | last = len(hfiles) and hfiles[-1] or '' |
|
126 | last = len(hfiles) and hfiles[-1] or '' | |
129 | if last.endswith('xx'): |
|
127 | if last.endswith('xx'): | |
130 | # print "using xx" |
|
128 | # print "using xx" | |
131 | hfiles = [last] + hfiles[:-1] |
|
129 | hfiles = [last] + hfiles[:-1] | |
132 |
|
130 | |||
133 | all = {} |
|
131 | all = {} | |
134 |
|
132 | |||
135 | for f in hfiles: |
|
133 | for f in hfiles: | |
136 | # print "using",f |
|
134 | # print "using",f | |
137 | try: |
|
135 | try: | |
138 | all.update(self[f]) |
|
136 | all.update(self[f]) | |
139 | except KeyError: |
|
137 | except KeyError: | |
140 | print "Corrupt",f,"deleted - hset is not threadsafe!" |
|
138 | print "Corrupt",f,"deleted - hset is not threadsafe!" | |
141 | del self[f] |
|
139 | del self[f] | |
142 |
|
140 | |||
143 | self.uncache(f) |
|
141 | self.uncache(f) | |
144 |
|
142 | |||
145 | return all |
|
143 | return all | |
146 |
|
144 | |||
147 | def hcompress(self, hashroot): |
|
145 | def hcompress(self, hashroot): | |
148 | """ Compress category 'hashroot', so hset is fast again |
|
146 | """ Compress category 'hashroot', so hset is fast again | |
149 |
|
147 | |||
150 | hget will fail if fast_only is True for compressed items (that were |
|
148 | hget will fail if fast_only is True for compressed items (that were | |
151 | hset before hcompress). |
|
149 | hset before hcompress). | |
152 |
|
150 | |||
153 | """ |
|
151 | """ | |
154 | hfiles = self.keys(hashroot + "/*") |
|
152 | hfiles = self.keys(hashroot + "/*") | |
155 | all = {} |
|
153 | all = {} | |
156 | for f in hfiles: |
|
154 | for f in hfiles: | |
157 | # print "using",f |
|
155 | # print "using",f | |
158 | all.update(self[f]) |
|
156 | all.update(self[f]) | |
159 | self.uncache(f) |
|
157 | self.uncache(f) | |
160 |
|
158 | |||
161 | self[hashroot + '/xx'] = all |
|
159 | self[hashroot + '/xx'] = all | |
162 | for f in hfiles: |
|
160 | for f in hfiles: | |
163 | p = self.root / f |
|
161 | p = self.root / f | |
164 | if p.basename() == 'xx': |
|
162 | if p.basename() == 'xx': | |
165 | continue |
|
163 | continue | |
166 | p.remove() |
|
164 | p.remove() | |
167 |
|
165 | |||
168 |
|
166 | |||
169 |
|
167 | |||
170 | def __delitem__(self,key): |
|
168 | def __delitem__(self,key): | |
171 | """ del db["key"] """ |
|
169 | """ del db["key"] """ | |
172 | fil = self.root / key |
|
170 | fil = self.root / key | |
173 | self.cache.pop(fil,None) |
|
171 | self.cache.pop(fil,None) | |
174 | try: |
|
172 | try: | |
175 | fil.remove() |
|
173 | fil.remove() | |
176 | except OSError: |
|
174 | except OSError: | |
177 | # notfound and permission denied are ok - we |
|
175 | # notfound and permission denied are ok - we | |
178 | # lost, the other process wins the conflict |
|
176 | # lost, the other process wins the conflict | |
179 | pass |
|
177 | pass | |
180 |
|
178 | |||
181 | def _normalized(self, p): |
|
179 | def _normalized(self, p): | |
182 | """ Make a key suitable for user's eyes """ |
|
180 | """ Make a key suitable for user's eyes """ | |
183 | return str(self.root.relpathto(p)).replace('\\','/') |
|
181 | return str(self.root.relpathto(p)).replace('\\','/') | |
184 |
|
182 | |||
185 | def keys(self, globpat = None): |
|
183 | def keys(self, globpat = None): | |
186 | """ All keys in DB, or all keys matching a glob""" |
|
184 | """ All keys in DB, or all keys matching a glob""" | |
187 |
|
185 | |||
188 | if globpat is None: |
|
186 | if globpat is None: | |
189 | files = self.root.walkfiles() |
|
187 | files = self.root.walkfiles() | |
190 | else: |
|
188 | else: | |
191 | files = [Path(p) for p in glob.glob(self.root/globpat)] |
|
189 | files = [Path(p) for p in glob.glob(self.root/globpat)] | |
192 | return [self._normalized(p) for p in files if p.isfile()] |
|
190 | return [self._normalized(p) for p in files if p.isfile()] | |
193 |
|
191 | |||
194 | def uncache(self,*items): |
|
192 | def uncache(self,*items): | |
195 | """ Removes all, or specified items from cache |
|
193 | """ Removes all, or specified items from cache | |
196 |
|
194 | |||
197 | Use this after reading a large amount of large objects |
|
195 | Use this after reading a large amount of large objects | |
198 | to free up memory, when you won't be needing the objects |
|
196 | to free up memory, when you won't be needing the objects | |
199 | for a while. |
|
197 | for a while. | |
200 |
|
198 | |||
201 | """ |
|
199 | """ | |
202 | if not items: |
|
200 | if not items: | |
203 | self.cache = {} |
|
201 | self.cache = {} | |
204 | for it in items: |
|
202 | for it in items: | |
205 | self.cache.pop(it,None) |
|
203 | self.cache.pop(it,None) | |
206 |
|
204 | |||
207 | def waitget(self,key, maxwaittime = 60 ): |
|
205 | def waitget(self,key, maxwaittime = 60 ): | |
208 | """ Wait (poll) for a key to get a value |
|
206 | """ Wait (poll) for a key to get a value | |
209 |
|
207 | |||
210 | Will wait for `maxwaittime` seconds before raising a KeyError. |
|
208 | Will wait for `maxwaittime` seconds before raising a KeyError. | |
211 | The call exits normally if the `key` field in db gets a value |
|
209 | The call exits normally if the `key` field in db gets a value | |
212 | within the timeout period. |
|
210 | within the timeout period. | |
213 |
|
211 | |||
214 | Use this for synchronizing different processes or for ensuring |
|
212 | Use this for synchronizing different processes or for ensuring | |
215 | that an unfortunately timed "db['key'] = newvalue" operation |
|
213 | that an unfortunately timed "db['key'] = newvalue" operation | |
216 | in another process (which causes all 'get' operation to cause a |
|
214 | in another process (which causes all 'get' operation to cause a | |
217 | KeyError for the duration of pickling) won't screw up your program |
|
215 | KeyError for the duration of pickling) won't screw up your program | |
218 | logic. |
|
216 | logic. | |
219 | """ |
|
217 | """ | |
220 |
|
218 | |||
221 | wtimes = [0.2] * 3 + [0.5] * 2 + [1] |
|
219 | wtimes = [0.2] * 3 + [0.5] * 2 + [1] | |
222 | tries = 0 |
|
220 | tries = 0 | |
223 | waited = 0 |
|
221 | waited = 0 | |
224 | while 1: |
|
222 | while 1: | |
225 | try: |
|
223 | try: | |
226 | val = self[key] |
|
224 | val = self[key] | |
227 | return val |
|
225 | return val | |
228 | except KeyError: |
|
226 | except KeyError: | |
229 | pass |
|
227 | pass | |
230 |
|
228 | |||
231 | if waited > maxwaittime: |
|
229 | if waited > maxwaittime: | |
232 | raise KeyError(key) |
|
230 | raise KeyError(key) | |
233 |
|
231 | |||
234 | time.sleep(wtimes[tries]) |
|
232 | time.sleep(wtimes[tries]) | |
235 | waited+=wtimes[tries] |
|
233 | waited+=wtimes[tries] | |
236 | if tries < len(wtimes) -1: |
|
234 | if tries < len(wtimes) -1: | |
237 | tries+=1 |
|
235 | tries+=1 | |
238 |
|
236 | |||
239 | def getlink(self,folder): |
|
237 | def getlink(self,folder): | |
240 | """ Get a convenient link for accessing items """ |
|
238 | """ Get a convenient link for accessing items """ | |
241 | return PickleShareLink(self, folder) |
|
239 | return PickleShareLink(self, folder) | |
242 |
|
240 | |||
243 | def __repr__(self): |
|
241 | def __repr__(self): | |
244 | return "PickleShareDB('%s')" % self.root |
|
242 | return "PickleShareDB('%s')" % self.root | |
245 |
|
243 | |||
246 |
|
244 | |||
247 |
|
245 | |||
248 | class PickleShareLink: |
|
246 | class PickleShareLink: | |
249 | """ A shortdand for accessing nested PickleShare data conveniently. |
|
247 | """ A shortdand for accessing nested PickleShare data conveniently. | |
250 |
|
248 | |||
251 | Created through PickleShareDB.getlink(), example:: |
|
249 | Created through PickleShareDB.getlink(), example:: | |
252 |
|
250 | |||
253 | lnk = db.getlink('myobjects/test') |
|
251 | lnk = db.getlink('myobjects/test') | |
254 | lnk.foo = 2 |
|
252 | lnk.foo = 2 | |
255 | lnk.bar = lnk.foo + 5 |
|
253 | lnk.bar = lnk.foo + 5 | |
256 |
|
254 | |||
257 | """ |
|
255 | """ | |
258 | def __init__(self, db, keydir ): |
|
256 | def __init__(self, db, keydir ): | |
259 | self.__dict__.update(locals()) |
|
257 | self.__dict__.update(locals()) | |
260 |
|
258 | |||
261 | def __getattr__(self,key): |
|
259 | def __getattr__(self,key): | |
262 | return self.__dict__['db'][self.__dict__['keydir']+'/' + key] |
|
260 | return self.__dict__['db'][self.__dict__['keydir']+'/' + key] | |
263 | def __setattr__(self,key,val): |
|
261 | def __setattr__(self,key,val): | |
264 | self.db[self.keydir+'/' + key] = val |
|
262 | self.db[self.keydir+'/' + key] = val | |
265 | def __repr__(self): |
|
263 | def __repr__(self): | |
266 | db = self.__dict__['db'] |
|
264 | db = self.__dict__['db'] | |
267 | keys = db.keys( self.__dict__['keydir'] +"/*") |
|
265 | keys = db.keys( self.__dict__['keydir'] +"/*") | |
268 | return "<PickleShareLink '%s': %s>" % ( |
|
266 | return "<PickleShareLink '%s': %s>" % ( | |
269 | self.__dict__['keydir'], |
|
267 | self.__dict__['keydir'], | |
270 | ";".join([Path(k).basename() for k in keys])) |
|
268 | ";".join([Path(k).basename() for k in keys])) | |
271 |
|
269 | |||
272 |
|
270 | |||
273 | def test(): |
|
271 | def test(): | |
274 | db = PickleShareDB('~/testpickleshare') |
|
272 | db = PickleShareDB('~/testpickleshare') | |
275 | db.clear() |
|
273 | db.clear() | |
276 | print "Should be empty:",db.items() |
|
274 | print "Should be empty:",db.items() | |
277 | db['hello'] = 15 |
|
275 | db['hello'] = 15 | |
278 | db['aku ankka'] = [1,2,313] |
|
276 | db['aku ankka'] = [1,2,313] | |
279 | db['paths/nest/ok/keyname'] = [1,(5,46)] |
|
277 | db['paths/nest/ok/keyname'] = [1,(5,46)] | |
280 | db.hset('hash', 'aku', 12) |
|
278 | db.hset('hash', 'aku', 12) | |
281 | db.hset('hash', 'ankka', 313) |
|
279 | db.hset('hash', 'ankka', 313) | |
282 | print "12 =",db.hget('hash','aku') |
|
280 | print "12 =",db.hget('hash','aku') | |
283 | print "313 =",db.hget('hash','ankka') |
|
281 | print "313 =",db.hget('hash','ankka') | |
284 | print "all hashed",db.hdict('hash') |
|
282 | print "all hashed",db.hdict('hash') | |
285 | print db.keys() |
|
283 | print db.keys() | |
286 | print db.keys('paths/nest/ok/k*') |
|
284 | print db.keys('paths/nest/ok/k*') | |
287 | print dict(db) # snapsot of whole db |
|
285 | print dict(db) # snapsot of whole db | |
288 | db.uncache() # frees memory, causes re-reads later |
|
286 | db.uncache() # frees memory, causes re-reads later | |
289 |
|
287 | |||
290 | # shorthand for accessing deeply nested files |
|
288 | # shorthand for accessing deeply nested files | |
291 | lnk = db.getlink('myobjects/test') |
|
289 | lnk = db.getlink('myobjects/test') | |
292 | lnk.foo = 2 |
|
290 | lnk.foo = 2 | |
293 | lnk.bar = lnk.foo + 5 |
|
291 | lnk.bar = lnk.foo + 5 | |
294 | print lnk.bar # 7 |
|
292 | print lnk.bar # 7 | |
295 |
|
293 | |||
296 | def stress(): |
|
294 | def stress(): | |
297 | db = PickleShareDB('~/fsdbtest') |
|
295 | db = PickleShareDB('~/fsdbtest') | |
298 | import time,sys |
|
296 | import time,sys | |
299 | for i in range(1000): |
|
297 | for i in range(1000): | |
300 | for j in range(1000): |
|
298 | for j in range(1000): | |
301 | if i % 15 == 0 and i < 200: |
|
299 | if i % 15 == 0 and i < 200: | |
302 | if str(j) in db: |
|
300 | if str(j) in db: | |
303 | del db[str(j)] |
|
301 | del db[str(j)] | |
304 | continue |
|
302 | continue | |
305 |
|
303 | |||
306 | if j%33 == 0: |
|
304 | if j%33 == 0: | |
307 | time.sleep(0.02) |
|
305 | time.sleep(0.02) | |
308 |
|
306 | |||
309 | db[str(j)] = db.get(str(j), []) + [(i,j,"proc %d" % os.getpid())] |
|
307 | db[str(j)] = db.get(str(j), []) + [(i,j,"proc %d" % os.getpid())] | |
310 | db.hset('hash',j, db.hget('hash',j,15) + 1 ) |
|
308 | db.hset('hash',j, db.hget('hash',j,15) + 1 ) | |
311 |
|
309 | |||
312 | print i, |
|
310 | print i, | |
313 | sys.stdout.flush() |
|
311 | sys.stdout.flush() | |
314 | if i % 10 == 0: |
|
312 | if i % 10 == 0: | |
315 | db.uncache() |
|
313 | db.uncache() | |
316 |
|
314 | |||
317 | def main(): |
|
315 | def main(): | |
318 | import textwrap |
|
316 | import textwrap | |
319 | usage = textwrap.dedent("""\ |
|
317 | usage = textwrap.dedent("""\ | |
320 | pickleshare - manage PickleShare databases |
|
318 | pickleshare - manage PickleShare databases | |
321 |
|
319 | |||
322 | Usage: |
|
320 | Usage: | |
323 |
|
321 | |||
324 | pickleshare dump /path/to/db > dump.txt |
|
322 | pickleshare dump /path/to/db > dump.txt | |
325 | pickleshare load /path/to/db < dump.txt |
|
323 | pickleshare load /path/to/db < dump.txt | |
326 | pickleshare test /path/to/db |
|
324 | pickleshare test /path/to/db | |
327 | """) |
|
325 | """) | |
328 | DB = PickleShareDB |
|
326 | DB = PickleShareDB | |
329 | import sys |
|
327 | import sys | |
330 | if len(sys.argv) < 2: |
|
328 | if len(sys.argv) < 2: | |
331 | print usage |
|
329 | print usage | |
332 | return |
|
330 | return | |
333 |
|
331 | |||
334 | cmd = sys.argv[1] |
|
332 | cmd = sys.argv[1] | |
335 | args = sys.argv[2:] |
|
333 | args = sys.argv[2:] | |
336 | if cmd == 'dump': |
|
334 | if cmd == 'dump': | |
337 | if not args: args= ['.'] |
|
335 | if not args: args= ['.'] | |
338 | db = DB(args[0]) |
|
336 | db = DB(args[0]) | |
339 | import pprint |
|
337 | import pprint | |
340 | pprint.pprint(db.items()) |
|
338 | pprint.pprint(db.items()) | |
341 | elif cmd == 'load': |
|
339 | elif cmd == 'load': | |
342 | cont = sys.stdin.read() |
|
340 | cont = sys.stdin.read() | |
343 | db = DB(args[0]) |
|
341 | db = DB(args[0]) | |
344 | data = eval(cont) |
|
342 | data = eval(cont) | |
345 | db.clear() |
|
343 | db.clear() | |
346 | for k,v in db.items(): |
|
344 | for k,v in db.items(): | |
347 | db[k] = v |
|
345 | db[k] = v | |
348 | elif cmd == 'testwait': |
|
346 | elif cmd == 'testwait': | |
349 | db = DB(args[0]) |
|
347 | db = DB(args[0]) | |
350 | db.clear() |
|
348 | db.clear() | |
351 | print db.waitget('250') |
|
349 | print db.waitget('250') | |
352 | elif cmd == 'test': |
|
350 | elif cmd == 'test': | |
353 | test() |
|
351 | test() | |
354 | stress() |
|
352 | stress() | |
355 |
|
353 | |||
356 | if __name__== "__main__": |
|
354 | if __name__== "__main__": | |
357 | main() |
|
355 | main() | |
358 |
|
356 | |||
359 |
|
357 |
@@ -1,3418 +1,3417 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Magic functions for InteractiveShell. |
|
2 | """Magic functions for InteractiveShell. | |
3 | """ |
|
3 | """ | |
4 |
|
4 | |||
5 | #***************************************************************************** |
|
5 | #***************************************************************************** | |
6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
7 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> |
|
7 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | # Distributed under the terms of the BSD License. The full license is in | |
10 | # the file COPYING, distributed as part of this software. |
|
10 | # the file COPYING, distributed as part of this software. | |
11 | #***************************************************************************** |
|
11 | #***************************************************************************** | |
12 |
|
12 | |||
13 | #**************************************************************************** |
|
13 | #**************************************************************************** | |
14 | # Modules and globals |
|
14 | # Modules and globals | |
15 |
|
15 | |||
16 | # Python standard modules |
|
16 | # Python standard modules | |
17 | import __builtin__ |
|
17 | import __builtin__ | |
18 | import bdb |
|
18 | import bdb | |
19 | import inspect |
|
19 | import inspect | |
20 | import os |
|
20 | import os | |
21 | import pdb |
|
21 | import pdb | |
22 | import pydoc |
|
22 | import pydoc | |
23 | import sys |
|
23 | import sys | |
24 | import re |
|
24 | import re | |
25 | import tempfile |
|
25 | import tempfile | |
26 | import time |
|
26 | import time | |
27 | import cPickle as pickle |
|
27 | import cPickle as pickle | |
28 | import textwrap |
|
28 | import textwrap | |
29 | from cStringIO import StringIO |
|
29 | from cStringIO import StringIO | |
30 | from getopt import getopt,GetoptError |
|
30 | from getopt import getopt,GetoptError | |
31 | from pprint import pprint, pformat |
|
31 | from pprint import pprint, pformat | |
32 | from sets import Set |
|
|||
33 |
|
32 | |||
34 | # cProfile was added in Python2.5 |
|
33 | # cProfile was added in Python2.5 | |
35 | try: |
|
34 | try: | |
36 | import cProfile as profile |
|
35 | import cProfile as profile | |
37 | import pstats |
|
36 | import pstats | |
38 | except ImportError: |
|
37 | except ImportError: | |
39 | # profile isn't bundled by default in Debian for license reasons |
|
38 | # profile isn't bundled by default in Debian for license reasons | |
40 | try: |
|
39 | try: | |
41 | import profile,pstats |
|
40 | import profile,pstats | |
42 | except ImportError: |
|
41 | except ImportError: | |
43 | profile = pstats = None |
|
42 | profile = pstats = None | |
44 |
|
43 | |||
45 | # Homebrewed |
|
44 | # Homebrewed | |
46 | import IPython |
|
45 | import IPython | |
47 | from IPython import Debugger, OInspect, wildcard |
|
46 | from IPython import Debugger, OInspect, wildcard | |
48 | from IPython.FakeModule import FakeModule |
|
47 | from IPython.FakeModule import FakeModule | |
49 | from IPython.Itpl import Itpl, itpl, printpl,itplns |
|
48 | from IPython.Itpl import Itpl, itpl, printpl,itplns | |
50 | from IPython.PyColorize import Parser |
|
49 | from IPython.PyColorize import Parser | |
51 | from IPython.ipstruct import Struct |
|
50 | from IPython.ipstruct import Struct | |
52 | from IPython.macro import Macro |
|
51 | from IPython.macro import Macro | |
53 | from IPython.genutils import * |
|
52 | from IPython.genutils import * | |
54 | from IPython import platutils |
|
53 | from IPython import platutils | |
55 | import IPython.generics |
|
54 | import IPython.generics | |
56 | import IPython.ipapi |
|
55 | import IPython.ipapi | |
57 | from IPython.ipapi import UsageError |
|
56 | from IPython.ipapi import UsageError | |
58 | from IPython.testing import decorators as testdec |
|
57 | from IPython.testing import decorators as testdec | |
59 |
|
58 | |||
60 | #*************************************************************************** |
|
59 | #*************************************************************************** | |
61 | # Utility functions |
|
60 | # Utility functions | |
62 | def on_off(tag): |
|
61 | def on_off(tag): | |
63 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
62 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" | |
64 | return ['OFF','ON'][tag] |
|
63 | return ['OFF','ON'][tag] | |
65 |
|
64 | |||
66 | class Bunch: pass |
|
65 | class Bunch: pass | |
67 |
|
66 | |||
68 | def compress_dhist(dh): |
|
67 | def compress_dhist(dh): | |
69 | head, tail = dh[:-10], dh[-10:] |
|
68 | head, tail = dh[:-10], dh[-10:] | |
70 |
|
69 | |||
71 | newhead = [] |
|
70 | newhead = [] | |
72 |
done = |
|
71 | done = set() | |
73 | for h in head: |
|
72 | for h in head: | |
74 | if h in done: |
|
73 | if h in done: | |
75 | continue |
|
74 | continue | |
76 | newhead.append(h) |
|
75 | newhead.append(h) | |
77 | done.add(h) |
|
76 | done.add(h) | |
78 |
|
77 | |||
79 | return newhead + tail |
|
78 | return newhead + tail | |
80 |
|
79 | |||
81 |
|
80 | |||
82 | #*************************************************************************** |
|
81 | #*************************************************************************** | |
83 | # Main class implementing Magic functionality |
|
82 | # Main class implementing Magic functionality | |
84 | class Magic: |
|
83 | class Magic: | |
85 | """Magic functions for InteractiveShell. |
|
84 | """Magic functions for InteractiveShell. | |
86 |
|
85 | |||
87 | Shell functions which can be reached as %function_name. All magic |
|
86 | Shell functions which can be reached as %function_name. All magic | |
88 | functions should accept a string, which they can parse for their own |
|
87 | functions should accept a string, which they can parse for their own | |
89 | needs. This can make some functions easier to type, eg `%cd ../` |
|
88 | needs. This can make some functions easier to type, eg `%cd ../` | |
90 | vs. `%cd("../")` |
|
89 | vs. `%cd("../")` | |
91 |
|
90 | |||
92 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
91 | ALL definitions MUST begin with the prefix magic_. The user won't need it | |
93 | at the command line, but it is is needed in the definition. """ |
|
92 | at the command line, but it is is needed in the definition. """ | |
94 |
|
93 | |||
95 | # class globals |
|
94 | # class globals | |
96 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
95 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', | |
97 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
96 | 'Automagic is ON, % prefix NOT needed for magic functions.'] | |
98 |
|
97 | |||
99 | #...................................................................... |
|
98 | #...................................................................... | |
100 | # some utility functions |
|
99 | # some utility functions | |
101 |
|
100 | |||
102 | def __init__(self,shell): |
|
101 | def __init__(self,shell): | |
103 |
|
102 | |||
104 | self.options_table = {} |
|
103 | self.options_table = {} | |
105 | if profile is None: |
|
104 | if profile is None: | |
106 | self.magic_prun = self.profile_missing_notice |
|
105 | self.magic_prun = self.profile_missing_notice | |
107 | self.shell = shell |
|
106 | self.shell = shell | |
108 |
|
107 | |||
109 | # namespace for holding state we may need |
|
108 | # namespace for holding state we may need | |
110 | self._magic_state = Bunch() |
|
109 | self._magic_state = Bunch() | |
111 |
|
110 | |||
112 | def profile_missing_notice(self, *args, **kwargs): |
|
111 | def profile_missing_notice(self, *args, **kwargs): | |
113 | error("""\ |
|
112 | error("""\ | |
114 | The profile module could not be found. It has been removed from the standard |
|
113 | The profile module could not be found. It has been removed from the standard | |
115 | python packages because of its non-free license. To use profiling, install the |
|
114 | python packages because of its non-free license. To use profiling, install the | |
116 | python-profiler package from non-free.""") |
|
115 | python-profiler package from non-free.""") | |
117 |
|
116 | |||
118 | def default_option(self,fn,optstr): |
|
117 | def default_option(self,fn,optstr): | |
119 | """Make an entry in the options_table for fn, with value optstr""" |
|
118 | """Make an entry in the options_table for fn, with value optstr""" | |
120 |
|
119 | |||
121 | if fn not in self.lsmagic(): |
|
120 | if fn not in self.lsmagic(): | |
122 | error("%s is not a magic function" % fn) |
|
121 | error("%s is not a magic function" % fn) | |
123 | self.options_table[fn] = optstr |
|
122 | self.options_table[fn] = optstr | |
124 |
|
123 | |||
125 | def lsmagic(self): |
|
124 | def lsmagic(self): | |
126 | """Return a list of currently available magic functions. |
|
125 | """Return a list of currently available magic functions. | |
127 |
|
126 | |||
128 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
127 | Gives a list of the bare names after mangling (['ls','cd', ...], not | |
129 | ['magic_ls','magic_cd',...]""" |
|
128 | ['magic_ls','magic_cd',...]""" | |
130 |
|
129 | |||
131 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
130 | # FIXME. This needs a cleanup, in the way the magics list is built. | |
132 |
|
131 | |||
133 | # magics in class definition |
|
132 | # magics in class definition | |
134 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
133 | class_magic = lambda fn: fn.startswith('magic_') and \ | |
135 | callable(Magic.__dict__[fn]) |
|
134 | callable(Magic.__dict__[fn]) | |
136 | # in instance namespace (run-time user additions) |
|
135 | # in instance namespace (run-time user additions) | |
137 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
136 | inst_magic = lambda fn: fn.startswith('magic_') and \ | |
138 | callable(self.__dict__[fn]) |
|
137 | callable(self.__dict__[fn]) | |
139 | # and bound magics by user (so they can access self): |
|
138 | # and bound magics by user (so they can access self): | |
140 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
139 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ | |
141 | callable(self.__class__.__dict__[fn]) |
|
140 | callable(self.__class__.__dict__[fn]) | |
142 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
141 | magics = filter(class_magic,Magic.__dict__.keys()) + \ | |
143 | filter(inst_magic,self.__dict__.keys()) + \ |
|
142 | filter(inst_magic,self.__dict__.keys()) + \ | |
144 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
143 | filter(inst_bound_magic,self.__class__.__dict__.keys()) | |
145 | out = [] |
|
144 | out = [] | |
146 |
for fn in |
|
145 | for fn in set(magics): | |
147 | out.append(fn.replace('magic_','',1)) |
|
146 | out.append(fn.replace('magic_','',1)) | |
148 | out.sort() |
|
147 | out.sort() | |
149 | return out |
|
148 | return out | |
150 |
|
149 | |||
151 | def extract_input_slices(self,slices,raw=False): |
|
150 | def extract_input_slices(self,slices,raw=False): | |
152 | """Return as a string a set of input history slices. |
|
151 | """Return as a string a set of input history slices. | |
153 |
|
152 | |||
154 | Inputs: |
|
153 | Inputs: | |
155 |
|
154 | |||
156 | - slices: the set of slices is given as a list of strings (like |
|
155 | - slices: the set of slices is given as a list of strings (like | |
157 | ['1','4:8','9'], since this function is for use by magic functions |
|
156 | ['1','4:8','9'], since this function is for use by magic functions | |
158 | which get their arguments as strings. |
|
157 | which get their arguments as strings. | |
159 |
|
158 | |||
160 | Optional inputs: |
|
159 | Optional inputs: | |
161 |
|
160 | |||
162 | - raw(False): by default, the processed input is used. If this is |
|
161 | - raw(False): by default, the processed input is used. If this is | |
163 | true, the raw input history is used instead. |
|
162 | true, the raw input history is used instead. | |
164 |
|
163 | |||
165 | Note that slices can be called with two notations: |
|
164 | Note that slices can be called with two notations: | |
166 |
|
165 | |||
167 | N:M -> standard python form, means including items N...(M-1). |
|
166 | N:M -> standard python form, means including items N...(M-1). | |
168 |
|
167 | |||
169 | N-M -> include items N..M (closed endpoint).""" |
|
168 | N-M -> include items N..M (closed endpoint).""" | |
170 |
|
169 | |||
171 | if raw: |
|
170 | if raw: | |
172 | hist = self.shell.input_hist_raw |
|
171 | hist = self.shell.input_hist_raw | |
173 | else: |
|
172 | else: | |
174 | hist = self.shell.input_hist |
|
173 | hist = self.shell.input_hist | |
175 |
|
174 | |||
176 | cmds = [] |
|
175 | cmds = [] | |
177 | for chunk in slices: |
|
176 | for chunk in slices: | |
178 | if ':' in chunk: |
|
177 | if ':' in chunk: | |
179 | ini,fin = map(int,chunk.split(':')) |
|
178 | ini,fin = map(int,chunk.split(':')) | |
180 | elif '-' in chunk: |
|
179 | elif '-' in chunk: | |
181 | ini,fin = map(int,chunk.split('-')) |
|
180 | ini,fin = map(int,chunk.split('-')) | |
182 | fin += 1 |
|
181 | fin += 1 | |
183 | else: |
|
182 | else: | |
184 | ini = int(chunk) |
|
183 | ini = int(chunk) | |
185 | fin = ini+1 |
|
184 | fin = ini+1 | |
186 | cmds.append(hist[ini:fin]) |
|
185 | cmds.append(hist[ini:fin]) | |
187 | return cmds |
|
186 | return cmds | |
188 |
|
187 | |||
189 | def _ofind(self, oname, namespaces=None): |
|
188 | def _ofind(self, oname, namespaces=None): | |
190 | """Find an object in the available namespaces. |
|
189 | """Find an object in the available namespaces. | |
191 |
|
190 | |||
192 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
191 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
193 |
|
192 | |||
194 | Has special code to detect magic functions. |
|
193 | Has special code to detect magic functions. | |
195 | """ |
|
194 | """ | |
196 |
|
195 | |||
197 | oname = oname.strip() |
|
196 | oname = oname.strip() | |
198 |
|
197 | |||
199 | alias_ns = None |
|
198 | alias_ns = None | |
200 | if namespaces is None: |
|
199 | if namespaces is None: | |
201 | # Namespaces to search in: |
|
200 | # Namespaces to search in: | |
202 | # Put them in a list. The order is important so that we |
|
201 | # Put them in a list. The order is important so that we | |
203 | # find things in the same order that Python finds them. |
|
202 | # find things in the same order that Python finds them. | |
204 | namespaces = [ ('Interactive', self.shell.user_ns), |
|
203 | namespaces = [ ('Interactive', self.shell.user_ns), | |
205 | ('IPython internal', self.shell.internal_ns), |
|
204 | ('IPython internal', self.shell.internal_ns), | |
206 | ('Python builtin', __builtin__.__dict__), |
|
205 | ('Python builtin', __builtin__.__dict__), | |
207 | ('Alias', self.shell.alias_table), |
|
206 | ('Alias', self.shell.alias_table), | |
208 | ] |
|
207 | ] | |
209 | alias_ns = self.shell.alias_table |
|
208 | alias_ns = self.shell.alias_table | |
210 |
|
209 | |||
211 | # initialize results to 'null' |
|
210 | # initialize results to 'null' | |
212 | found = 0; obj = None; ospace = None; ds = None; |
|
211 | found = 0; obj = None; ospace = None; ds = None; | |
213 | ismagic = 0; isalias = 0; parent = None |
|
212 | ismagic = 0; isalias = 0; parent = None | |
214 |
|
213 | |||
215 | # Look for the given name by splitting it in parts. If the head is |
|
214 | # Look for the given name by splitting it in parts. If the head is | |
216 | # found, then we look for all the remaining parts as members, and only |
|
215 | # found, then we look for all the remaining parts as members, and only | |
217 | # declare success if we can find them all. |
|
216 | # declare success if we can find them all. | |
218 | oname_parts = oname.split('.') |
|
217 | oname_parts = oname.split('.') | |
219 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
218 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
220 | for nsname,ns in namespaces: |
|
219 | for nsname,ns in namespaces: | |
221 | try: |
|
220 | try: | |
222 | obj = ns[oname_head] |
|
221 | obj = ns[oname_head] | |
223 | except KeyError: |
|
222 | except KeyError: | |
224 | continue |
|
223 | continue | |
225 | else: |
|
224 | else: | |
226 | #print 'oname_rest:', oname_rest # dbg |
|
225 | #print 'oname_rest:', oname_rest # dbg | |
227 | for part in oname_rest: |
|
226 | for part in oname_rest: | |
228 | try: |
|
227 | try: | |
229 | parent = obj |
|
228 | parent = obj | |
230 | obj = getattr(obj,part) |
|
229 | obj = getattr(obj,part) | |
231 | except: |
|
230 | except: | |
232 | # Blanket except b/c some badly implemented objects |
|
231 | # Blanket except b/c some badly implemented objects | |
233 | # allow __getattr__ to raise exceptions other than |
|
232 | # allow __getattr__ to raise exceptions other than | |
234 | # AttributeError, which then crashes IPython. |
|
233 | # AttributeError, which then crashes IPython. | |
235 | break |
|
234 | break | |
236 | else: |
|
235 | else: | |
237 | # If we finish the for loop (no break), we got all members |
|
236 | # If we finish the for loop (no break), we got all members | |
238 | found = 1 |
|
237 | found = 1 | |
239 | ospace = nsname |
|
238 | ospace = nsname | |
240 | if ns == alias_ns: |
|
239 | if ns == alias_ns: | |
241 | isalias = 1 |
|
240 | isalias = 1 | |
242 | break # namespace loop |
|
241 | break # namespace loop | |
243 |
|
242 | |||
244 | # Try to see if it's magic |
|
243 | # Try to see if it's magic | |
245 | if not found: |
|
244 | if not found: | |
246 | if oname.startswith(self.shell.ESC_MAGIC): |
|
245 | if oname.startswith(self.shell.ESC_MAGIC): | |
247 | oname = oname[1:] |
|
246 | oname = oname[1:] | |
248 | obj = getattr(self,'magic_'+oname,None) |
|
247 | obj = getattr(self,'magic_'+oname,None) | |
249 | if obj is not None: |
|
248 | if obj is not None: | |
250 | found = 1 |
|
249 | found = 1 | |
251 | ospace = 'IPython internal' |
|
250 | ospace = 'IPython internal' | |
252 | ismagic = 1 |
|
251 | ismagic = 1 | |
253 |
|
252 | |||
254 | # Last try: special-case some literals like '', [], {}, etc: |
|
253 | # Last try: special-case some literals like '', [], {}, etc: | |
255 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
254 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
256 | obj = eval(oname_head) |
|
255 | obj = eval(oname_head) | |
257 | found = 1 |
|
256 | found = 1 | |
258 | ospace = 'Interactive' |
|
257 | ospace = 'Interactive' | |
259 |
|
258 | |||
260 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
259 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
261 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
260 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
262 |
|
261 | |||
263 | def arg_err(self,func): |
|
262 | def arg_err(self,func): | |
264 | """Print docstring if incorrect arguments were passed""" |
|
263 | """Print docstring if incorrect arguments were passed""" | |
265 | print 'Error in arguments:' |
|
264 | print 'Error in arguments:' | |
266 | print OInspect.getdoc(func) |
|
265 | print OInspect.getdoc(func) | |
267 |
|
266 | |||
268 | def format_latex(self,strng): |
|
267 | def format_latex(self,strng): | |
269 | """Format a string for latex inclusion.""" |
|
268 | """Format a string for latex inclusion.""" | |
270 |
|
269 | |||
271 | # Characters that need to be escaped for latex: |
|
270 | # Characters that need to be escaped for latex: | |
272 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
271 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) | |
273 | # Magic command names as headers: |
|
272 | # Magic command names as headers: | |
274 | cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC, |
|
273 | cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC, | |
275 | re.MULTILINE) |
|
274 | re.MULTILINE) | |
276 | # Magic commands |
|
275 | # Magic commands | |
277 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC, |
|
276 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC, | |
278 | re.MULTILINE) |
|
277 | re.MULTILINE) | |
279 | # Paragraph continue |
|
278 | # Paragraph continue | |
280 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
279 | par_re = re.compile(r'\\$',re.MULTILINE) | |
281 |
|
280 | |||
282 | # The "\n" symbol |
|
281 | # The "\n" symbol | |
283 | newline_re = re.compile(r'\\n') |
|
282 | newline_re = re.compile(r'\\n') | |
284 |
|
283 | |||
285 | # Now build the string for output: |
|
284 | # Now build the string for output: | |
286 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
285 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) | |
287 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
286 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', | |
288 | strng) |
|
287 | strng) | |
289 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
288 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) | |
290 | strng = par_re.sub(r'\\\\',strng) |
|
289 | strng = par_re.sub(r'\\\\',strng) | |
291 | strng = escape_re.sub(r'\\\1',strng) |
|
290 | strng = escape_re.sub(r'\\\1',strng) | |
292 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
291 | strng = newline_re.sub(r'\\textbackslash{}n',strng) | |
293 | return strng |
|
292 | return strng | |
294 |
|
293 | |||
295 | def format_screen(self,strng): |
|
294 | def format_screen(self,strng): | |
296 | """Format a string for screen printing. |
|
295 | """Format a string for screen printing. | |
297 |
|
296 | |||
298 | This removes some latex-type format codes.""" |
|
297 | This removes some latex-type format codes.""" | |
299 | # Paragraph continue |
|
298 | # Paragraph continue | |
300 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
299 | par_re = re.compile(r'\\$',re.MULTILINE) | |
301 | strng = par_re.sub('',strng) |
|
300 | strng = par_re.sub('',strng) | |
302 | return strng |
|
301 | return strng | |
303 |
|
302 | |||
304 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
303 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): | |
305 | """Parse options passed to an argument string. |
|
304 | """Parse options passed to an argument string. | |
306 |
|
305 | |||
307 | The interface is similar to that of getopt(), but it returns back a |
|
306 | The interface is similar to that of getopt(), but it returns back a | |
308 | Struct with the options as keys and the stripped argument string still |
|
307 | Struct with the options as keys and the stripped argument string still | |
309 | as a string. |
|
308 | as a string. | |
310 |
|
309 | |||
311 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
310 | arg_str is quoted as a true sys.argv vector by using shlex.split. | |
312 | This allows us to easily expand variables, glob files, quote |
|
311 | This allows us to easily expand variables, glob files, quote | |
313 | arguments, etc. |
|
312 | arguments, etc. | |
314 |
|
313 | |||
315 | Options: |
|
314 | Options: | |
316 | -mode: default 'string'. If given as 'list', the argument string is |
|
315 | -mode: default 'string'. If given as 'list', the argument string is | |
317 | returned as a list (split on whitespace) instead of a string. |
|
316 | returned as a list (split on whitespace) instead of a string. | |
318 |
|
317 | |||
319 | -list_all: put all option values in lists. Normally only options |
|
318 | -list_all: put all option values in lists. Normally only options | |
320 | appearing more than once are put in a list. |
|
319 | appearing more than once are put in a list. | |
321 |
|
320 | |||
322 | -posix (True): whether to split the input line in POSIX mode or not, |
|
321 | -posix (True): whether to split the input line in POSIX mode or not, | |
323 | as per the conventions outlined in the shlex module from the |
|
322 | as per the conventions outlined in the shlex module from the | |
324 | standard library.""" |
|
323 | standard library.""" | |
325 |
|
324 | |||
326 | # inject default options at the beginning of the input line |
|
325 | # inject default options at the beginning of the input line | |
327 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
326 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') | |
328 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
327 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) | |
329 |
|
328 | |||
330 | mode = kw.get('mode','string') |
|
329 | mode = kw.get('mode','string') | |
331 | if mode not in ['string','list']: |
|
330 | if mode not in ['string','list']: | |
332 | raise ValueError,'incorrect mode given: %s' % mode |
|
331 | raise ValueError,'incorrect mode given: %s' % mode | |
333 | # Get options |
|
332 | # Get options | |
334 | list_all = kw.get('list_all',0) |
|
333 | list_all = kw.get('list_all',0) | |
335 | posix = kw.get('posix',True) |
|
334 | posix = kw.get('posix',True) | |
336 |
|
335 | |||
337 | # Check if we have more than one argument to warrant extra processing: |
|
336 | # Check if we have more than one argument to warrant extra processing: | |
338 | odict = {} # Dictionary with options |
|
337 | odict = {} # Dictionary with options | |
339 | args = arg_str.split() |
|
338 | args = arg_str.split() | |
340 | if len(args) >= 1: |
|
339 | if len(args) >= 1: | |
341 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
340 | # If the list of inputs only has 0 or 1 thing in it, there's no | |
342 | # need to look for options |
|
341 | # need to look for options | |
343 | argv = arg_split(arg_str,posix) |
|
342 | argv = arg_split(arg_str,posix) | |
344 | # Do regular option processing |
|
343 | # Do regular option processing | |
345 | try: |
|
344 | try: | |
346 | opts,args = getopt(argv,opt_str,*long_opts) |
|
345 | opts,args = getopt(argv,opt_str,*long_opts) | |
347 | except GetoptError,e: |
|
346 | except GetoptError,e: | |
348 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
347 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, | |
349 | " ".join(long_opts))) |
|
348 | " ".join(long_opts))) | |
350 | for o,a in opts: |
|
349 | for o,a in opts: | |
351 | if o.startswith('--'): |
|
350 | if o.startswith('--'): | |
352 | o = o[2:] |
|
351 | o = o[2:] | |
353 | else: |
|
352 | else: | |
354 | o = o[1:] |
|
353 | o = o[1:] | |
355 | try: |
|
354 | try: | |
356 | odict[o].append(a) |
|
355 | odict[o].append(a) | |
357 | except AttributeError: |
|
356 | except AttributeError: | |
358 | odict[o] = [odict[o],a] |
|
357 | odict[o] = [odict[o],a] | |
359 | except KeyError: |
|
358 | except KeyError: | |
360 | if list_all: |
|
359 | if list_all: | |
361 | odict[o] = [a] |
|
360 | odict[o] = [a] | |
362 | else: |
|
361 | else: | |
363 | odict[o] = a |
|
362 | odict[o] = a | |
364 |
|
363 | |||
365 | # Prepare opts,args for return |
|
364 | # Prepare opts,args for return | |
366 | opts = Struct(odict) |
|
365 | opts = Struct(odict) | |
367 | if mode == 'string': |
|
366 | if mode == 'string': | |
368 | args = ' '.join(args) |
|
367 | args = ' '.join(args) | |
369 |
|
368 | |||
370 | return opts,args |
|
369 | return opts,args | |
371 |
|
370 | |||
372 | #...................................................................... |
|
371 | #...................................................................... | |
373 | # And now the actual magic functions |
|
372 | # And now the actual magic functions | |
374 |
|
373 | |||
375 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
374 | # Functions for IPython shell work (vars,funcs, config, etc) | |
376 | def magic_lsmagic(self, parameter_s = ''): |
|
375 | def magic_lsmagic(self, parameter_s = ''): | |
377 | """List currently available magic functions.""" |
|
376 | """List currently available magic functions.""" | |
378 | mesc = self.shell.ESC_MAGIC |
|
377 | mesc = self.shell.ESC_MAGIC | |
379 | print 'Available magic functions:\n'+mesc+\ |
|
378 | print 'Available magic functions:\n'+mesc+\ | |
380 | (' '+mesc).join(self.lsmagic()) |
|
379 | (' '+mesc).join(self.lsmagic()) | |
381 | print '\n' + Magic.auto_status[self.shell.rc.automagic] |
|
380 | print '\n' + Magic.auto_status[self.shell.rc.automagic] | |
382 | return None |
|
381 | return None | |
383 |
|
382 | |||
384 | def magic_magic(self, parameter_s = ''): |
|
383 | def magic_magic(self, parameter_s = ''): | |
385 | """Print information about the magic function system. |
|
384 | """Print information about the magic function system. | |
386 |
|
385 | |||
387 | Supported formats: -latex, -brief, -rest |
|
386 | Supported formats: -latex, -brief, -rest | |
388 | """ |
|
387 | """ | |
389 |
|
388 | |||
390 | mode = '' |
|
389 | mode = '' | |
391 | try: |
|
390 | try: | |
392 | if parameter_s.split()[0] == '-latex': |
|
391 | if parameter_s.split()[0] == '-latex': | |
393 | mode = 'latex' |
|
392 | mode = 'latex' | |
394 | if parameter_s.split()[0] == '-brief': |
|
393 | if parameter_s.split()[0] == '-brief': | |
395 | mode = 'brief' |
|
394 | mode = 'brief' | |
396 | if parameter_s.split()[0] == '-rest': |
|
395 | if parameter_s.split()[0] == '-rest': | |
397 | mode = 'rest' |
|
396 | mode = 'rest' | |
398 | rest_docs = [] |
|
397 | rest_docs = [] | |
399 | except: |
|
398 | except: | |
400 | pass |
|
399 | pass | |
401 |
|
400 | |||
402 | magic_docs = [] |
|
401 | magic_docs = [] | |
403 | for fname in self.lsmagic(): |
|
402 | for fname in self.lsmagic(): | |
404 | mname = 'magic_' + fname |
|
403 | mname = 'magic_' + fname | |
405 | for space in (Magic,self,self.__class__): |
|
404 | for space in (Magic,self,self.__class__): | |
406 | try: |
|
405 | try: | |
407 | fn = space.__dict__[mname] |
|
406 | fn = space.__dict__[mname] | |
408 | except KeyError: |
|
407 | except KeyError: | |
409 | pass |
|
408 | pass | |
410 | else: |
|
409 | else: | |
411 | break |
|
410 | break | |
412 | if mode == 'brief': |
|
411 | if mode == 'brief': | |
413 | # only first line |
|
412 | # only first line | |
414 | if fn.__doc__: |
|
413 | if fn.__doc__: | |
415 | fndoc = fn.__doc__.split('\n',1)[0] |
|
414 | fndoc = fn.__doc__.split('\n',1)[0] | |
416 | else: |
|
415 | else: | |
417 | fndoc = 'No documentation' |
|
416 | fndoc = 'No documentation' | |
418 | else: |
|
417 | else: | |
419 | fndoc = fn.__doc__.rstrip() |
|
418 | fndoc = fn.__doc__.rstrip() | |
420 |
|
419 | |||
421 | if mode == 'rest': |
|
420 | if mode == 'rest': | |
422 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC, |
|
421 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC, | |
423 | fname,fndoc)) |
|
422 | fname,fndoc)) | |
424 |
|
423 | |||
425 | else: |
|
424 | else: | |
426 | magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC, |
|
425 | magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC, | |
427 | fname,fndoc)) |
|
426 | fname,fndoc)) | |
428 |
|
427 | |||
429 | magic_docs = ''.join(magic_docs) |
|
428 | magic_docs = ''.join(magic_docs) | |
430 |
|
429 | |||
431 | if mode == 'rest': |
|
430 | if mode == 'rest': | |
432 | return "".join(rest_docs) |
|
431 | return "".join(rest_docs) | |
433 |
|
432 | |||
434 | if mode == 'latex': |
|
433 | if mode == 'latex': | |
435 | print self.format_latex(magic_docs) |
|
434 | print self.format_latex(magic_docs) | |
436 | return |
|
435 | return | |
437 | else: |
|
436 | else: | |
438 | magic_docs = self.format_screen(magic_docs) |
|
437 | magic_docs = self.format_screen(magic_docs) | |
439 | if mode == 'brief': |
|
438 | if mode == 'brief': | |
440 | return magic_docs |
|
439 | return magic_docs | |
441 |
|
440 | |||
442 | outmsg = """ |
|
441 | outmsg = """ | |
443 | IPython's 'magic' functions |
|
442 | IPython's 'magic' functions | |
444 | =========================== |
|
443 | =========================== | |
445 |
|
444 | |||
446 | The magic function system provides a series of functions which allow you to |
|
445 | The magic function system provides a series of functions which allow you to | |
447 | control the behavior of IPython itself, plus a lot of system-type |
|
446 | control the behavior of IPython itself, plus a lot of system-type | |
448 | features. All these functions are prefixed with a % character, but parameters |
|
447 | features. All these functions are prefixed with a % character, but parameters | |
449 | are given without parentheses or quotes. |
|
448 | are given without parentheses or quotes. | |
450 |
|
449 | |||
451 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
450 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
452 | %automagic function), you don't need to type in the % explicitly. By default, |
|
451 | %automagic function), you don't need to type in the % explicitly. By default, | |
453 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
452 | IPython ships with automagic on, so you should only rarely need the % escape. | |
454 |
|
453 | |||
455 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
454 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
456 | to 'mydir', if it exists. |
|
455 | to 'mydir', if it exists. | |
457 |
|
456 | |||
458 | You can define your own magic functions to extend the system. See the supplied |
|
457 | You can define your own magic functions to extend the system. See the supplied | |
459 | ipythonrc and example-magic.py files for details (in your ipython |
|
458 | ipythonrc and example-magic.py files for details (in your ipython | |
460 | configuration directory, typically $HOME/.ipython/). |
|
459 | configuration directory, typically $HOME/.ipython/). | |
461 |
|
460 | |||
462 | You can also define your own aliased names for magic functions. In your |
|
461 | You can also define your own aliased names for magic functions. In your | |
463 | ipythonrc file, placing a line like: |
|
462 | ipythonrc file, placing a line like: | |
464 |
|
463 | |||
465 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
464 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile | |
466 |
|
465 | |||
467 | will define %pf as a new name for %profile. |
|
466 | will define %pf as a new name for %profile. | |
468 |
|
467 | |||
469 | You can also call magics in code using the ipmagic() function, which IPython |
|
468 | You can also call magics in code using the ipmagic() function, which IPython | |
470 | automatically adds to the builtin namespace. Type 'ipmagic?' for details. |
|
469 | automatically adds to the builtin namespace. Type 'ipmagic?' for details. | |
471 |
|
470 | |||
472 | For a list of the available magic functions, use %lsmagic. For a description |
|
471 | For a list of the available magic functions, use %lsmagic. For a description | |
473 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
472 | of any of them, type %magic_name?, e.g. '%cd?'. | |
474 |
|
473 | |||
475 | Currently the magic system has the following functions:\n""" |
|
474 | Currently the magic system has the following functions:\n""" | |
476 |
|
475 | |||
477 | mesc = self.shell.ESC_MAGIC |
|
476 | mesc = self.shell.ESC_MAGIC | |
478 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
477 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" | |
479 | "\n\n%s%s\n\n%s" % (outmsg, |
|
478 | "\n\n%s%s\n\n%s" % (outmsg, | |
480 | magic_docs,mesc,mesc, |
|
479 | magic_docs,mesc,mesc, | |
481 | (' '+mesc).join(self.lsmagic()), |
|
480 | (' '+mesc).join(self.lsmagic()), | |
482 | Magic.auto_status[self.shell.rc.automagic] ) ) |
|
481 | Magic.auto_status[self.shell.rc.automagic] ) ) | |
483 |
|
482 | |||
484 | page(outmsg,screen_lines=self.shell.rc.screen_length) |
|
483 | page(outmsg,screen_lines=self.shell.rc.screen_length) | |
485 |
|
484 | |||
486 |
|
485 | |||
487 | def magic_autoindent(self, parameter_s = ''): |
|
486 | def magic_autoindent(self, parameter_s = ''): | |
488 | """Toggle autoindent on/off (if available).""" |
|
487 | """Toggle autoindent on/off (if available).""" | |
489 |
|
488 | |||
490 | self.shell.set_autoindent() |
|
489 | self.shell.set_autoindent() | |
491 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] |
|
490 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] | |
492 |
|
491 | |||
493 |
|
492 | |||
494 | def magic_automagic(self, parameter_s = ''): |
|
493 | def magic_automagic(self, parameter_s = ''): | |
495 | """Make magic functions callable without having to type the initial %. |
|
494 | """Make magic functions callable without having to type the initial %. | |
496 |
|
495 | |||
497 | Without argumentsl toggles on/off (when off, you must call it as |
|
496 | Without argumentsl toggles on/off (when off, you must call it as | |
498 | %automagic, of course). With arguments it sets the value, and you can |
|
497 | %automagic, of course). With arguments it sets the value, and you can | |
499 | use any of (case insensitive): |
|
498 | use any of (case insensitive): | |
500 |
|
499 | |||
501 | - on,1,True: to activate |
|
500 | - on,1,True: to activate | |
502 |
|
501 | |||
503 | - off,0,False: to deactivate. |
|
502 | - off,0,False: to deactivate. | |
504 |
|
503 | |||
505 | Note that magic functions have lowest priority, so if there's a |
|
504 | Note that magic functions have lowest priority, so if there's a | |
506 | variable whose name collides with that of a magic fn, automagic won't |
|
505 | variable whose name collides with that of a magic fn, automagic won't | |
507 | work for that function (you get the variable instead). However, if you |
|
506 | work for that function (you get the variable instead). However, if you | |
508 | delete the variable (del var), the previously shadowed magic function |
|
507 | delete the variable (del var), the previously shadowed magic function | |
509 | becomes visible to automagic again.""" |
|
508 | becomes visible to automagic again.""" | |
510 |
|
509 | |||
511 | rc = self.shell.rc |
|
510 | rc = self.shell.rc | |
512 | arg = parameter_s.lower() |
|
511 | arg = parameter_s.lower() | |
513 | if parameter_s in ('on','1','true'): |
|
512 | if parameter_s in ('on','1','true'): | |
514 | rc.automagic = True |
|
513 | rc.automagic = True | |
515 | elif parameter_s in ('off','0','false'): |
|
514 | elif parameter_s in ('off','0','false'): | |
516 | rc.automagic = False |
|
515 | rc.automagic = False | |
517 | else: |
|
516 | else: | |
518 | rc.automagic = not rc.automagic |
|
517 | rc.automagic = not rc.automagic | |
519 | print '\n' + Magic.auto_status[rc.automagic] |
|
518 | print '\n' + Magic.auto_status[rc.automagic] | |
520 |
|
519 | |||
521 | @testdec.skip_doctest |
|
520 | @testdec.skip_doctest | |
522 | def magic_autocall(self, parameter_s = ''): |
|
521 | def magic_autocall(self, parameter_s = ''): | |
523 | """Make functions callable without having to type parentheses. |
|
522 | """Make functions callable without having to type parentheses. | |
524 |
|
523 | |||
525 | Usage: |
|
524 | Usage: | |
526 |
|
525 | |||
527 | %autocall [mode] |
|
526 | %autocall [mode] | |
528 |
|
527 | |||
529 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
528 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the | |
530 | value is toggled on and off (remembering the previous state). |
|
529 | value is toggled on and off (remembering the previous state). | |
531 |
|
530 | |||
532 | In more detail, these values mean: |
|
531 | In more detail, these values mean: | |
533 |
|
532 | |||
534 | 0 -> fully disabled |
|
533 | 0 -> fully disabled | |
535 |
|
534 | |||
536 | 1 -> active, but do not apply if there are no arguments on the line. |
|
535 | 1 -> active, but do not apply if there are no arguments on the line. | |
537 |
|
536 | |||
538 | In this mode, you get: |
|
537 | In this mode, you get: | |
539 |
|
538 | |||
540 | In [1]: callable |
|
539 | In [1]: callable | |
541 | Out[1]: <built-in function callable> |
|
540 | Out[1]: <built-in function callable> | |
542 |
|
541 | |||
543 | In [2]: callable 'hello' |
|
542 | In [2]: callable 'hello' | |
544 | ------> callable('hello') |
|
543 | ------> callable('hello') | |
545 | Out[2]: False |
|
544 | Out[2]: False | |
546 |
|
545 | |||
547 | 2 -> Active always. Even if no arguments are present, the callable |
|
546 | 2 -> Active always. Even if no arguments are present, the callable | |
548 | object is called: |
|
547 | object is called: | |
549 |
|
548 | |||
550 | In [2]: float |
|
549 | In [2]: float | |
551 | ------> float() |
|
550 | ------> float() | |
552 | Out[2]: 0.0 |
|
551 | Out[2]: 0.0 | |
553 |
|
552 | |||
554 | Note that even with autocall off, you can still use '/' at the start of |
|
553 | Note that even with autocall off, you can still use '/' at the start of | |
555 | a line to treat the first argument on the command line as a function |
|
554 | a line to treat the first argument on the command line as a function | |
556 | and add parentheses to it: |
|
555 | and add parentheses to it: | |
557 |
|
556 | |||
558 | In [8]: /str 43 |
|
557 | In [8]: /str 43 | |
559 | ------> str(43) |
|
558 | ------> str(43) | |
560 | Out[8]: '43' |
|
559 | Out[8]: '43' | |
561 |
|
560 | |||
562 | # all-random (note for auto-testing) |
|
561 | # all-random (note for auto-testing) | |
563 | """ |
|
562 | """ | |
564 |
|
563 | |||
565 | rc = self.shell.rc |
|
564 | rc = self.shell.rc | |
566 |
|
565 | |||
567 | if parameter_s: |
|
566 | if parameter_s: | |
568 | arg = int(parameter_s) |
|
567 | arg = int(parameter_s) | |
569 | else: |
|
568 | else: | |
570 | arg = 'toggle' |
|
569 | arg = 'toggle' | |
571 |
|
570 | |||
572 | if not arg in (0,1,2,'toggle'): |
|
571 | if not arg in (0,1,2,'toggle'): | |
573 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
572 | error('Valid modes: (0->Off, 1->Smart, 2->Full') | |
574 | return |
|
573 | return | |
575 |
|
574 | |||
576 | if arg in (0,1,2): |
|
575 | if arg in (0,1,2): | |
577 | rc.autocall = arg |
|
576 | rc.autocall = arg | |
578 | else: # toggle |
|
577 | else: # toggle | |
579 | if rc.autocall: |
|
578 | if rc.autocall: | |
580 | self._magic_state.autocall_save = rc.autocall |
|
579 | self._magic_state.autocall_save = rc.autocall | |
581 | rc.autocall = 0 |
|
580 | rc.autocall = 0 | |
582 | else: |
|
581 | else: | |
583 | try: |
|
582 | try: | |
584 | rc.autocall = self._magic_state.autocall_save |
|
583 | rc.autocall = self._magic_state.autocall_save | |
585 | except AttributeError: |
|
584 | except AttributeError: | |
586 | rc.autocall = self._magic_state.autocall_save = 1 |
|
585 | rc.autocall = self._magic_state.autocall_save = 1 | |
587 |
|
586 | |||
588 | print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall] |
|
587 | print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall] | |
589 |
|
588 | |||
590 | def magic_system_verbose(self, parameter_s = ''): |
|
589 | def magic_system_verbose(self, parameter_s = ''): | |
591 | """Set verbose printing of system calls. |
|
590 | """Set verbose printing of system calls. | |
592 |
|
591 | |||
593 | If called without an argument, act as a toggle""" |
|
592 | If called without an argument, act as a toggle""" | |
594 |
|
593 | |||
595 | if parameter_s: |
|
594 | if parameter_s: | |
596 | val = bool(eval(parameter_s)) |
|
595 | val = bool(eval(parameter_s)) | |
597 | else: |
|
596 | else: | |
598 | val = None |
|
597 | val = None | |
599 |
|
598 | |||
600 | self.shell.rc_set_toggle('system_verbose',val) |
|
599 | self.shell.rc_set_toggle('system_verbose',val) | |
601 | print "System verbose printing is:",\ |
|
600 | print "System verbose printing is:",\ | |
602 | ['OFF','ON'][self.shell.rc.system_verbose] |
|
601 | ['OFF','ON'][self.shell.rc.system_verbose] | |
603 |
|
602 | |||
604 |
|
603 | |||
605 | def magic_page(self, parameter_s=''): |
|
604 | def magic_page(self, parameter_s=''): | |
606 | """Pretty print the object and display it through a pager. |
|
605 | """Pretty print the object and display it through a pager. | |
607 |
|
606 | |||
608 | %page [options] OBJECT |
|
607 | %page [options] OBJECT | |
609 |
|
608 | |||
610 | If no object is given, use _ (last output). |
|
609 | If no object is given, use _ (last output). | |
611 |
|
610 | |||
612 | Options: |
|
611 | Options: | |
613 |
|
612 | |||
614 | -r: page str(object), don't pretty-print it.""" |
|
613 | -r: page str(object), don't pretty-print it.""" | |
615 |
|
614 | |||
616 | # After a function contributed by Olivier Aubert, slightly modified. |
|
615 | # After a function contributed by Olivier Aubert, slightly modified. | |
617 |
|
616 | |||
618 | # Process options/args |
|
617 | # Process options/args | |
619 | opts,args = self.parse_options(parameter_s,'r') |
|
618 | opts,args = self.parse_options(parameter_s,'r') | |
620 | raw = 'r' in opts |
|
619 | raw = 'r' in opts | |
621 |
|
620 | |||
622 | oname = args and args or '_' |
|
621 | oname = args and args or '_' | |
623 | info = self._ofind(oname) |
|
622 | info = self._ofind(oname) | |
624 | if info['found']: |
|
623 | if info['found']: | |
625 | txt = (raw and str or pformat)( info['obj'] ) |
|
624 | txt = (raw and str or pformat)( info['obj'] ) | |
626 | page(txt) |
|
625 | page(txt) | |
627 | else: |
|
626 | else: | |
628 | print 'Object `%s` not found' % oname |
|
627 | print 'Object `%s` not found' % oname | |
629 |
|
628 | |||
630 | def magic_profile(self, parameter_s=''): |
|
629 | def magic_profile(self, parameter_s=''): | |
631 | """Print your currently active IPyhton profile.""" |
|
630 | """Print your currently active IPyhton profile.""" | |
632 | if self.shell.rc.profile: |
|
631 | if self.shell.rc.profile: | |
633 | printpl('Current IPython profile: $self.shell.rc.profile.') |
|
632 | printpl('Current IPython profile: $self.shell.rc.profile.') | |
634 | else: |
|
633 | else: | |
635 | print 'No profile active.' |
|
634 | print 'No profile active.' | |
636 |
|
635 | |||
637 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
636 | def magic_pinfo(self, parameter_s='', namespaces=None): | |
638 | """Provide detailed information about an object. |
|
637 | """Provide detailed information about an object. | |
639 |
|
638 | |||
640 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
639 | '%pinfo object' is just a synonym for object? or ?object.""" | |
641 |
|
640 | |||
642 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
641 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
643 |
|
642 | |||
644 |
|
643 | |||
645 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
644 | # detail_level: 0 -> obj? , 1 -> obj?? | |
646 | detail_level = 0 |
|
645 | detail_level = 0 | |
647 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
646 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
648 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
647 | # happen if the user types 'pinfo foo?' at the cmd line. | |
649 | pinfo,qmark1,oname,qmark2 = \ |
|
648 | pinfo,qmark1,oname,qmark2 = \ | |
650 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
649 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
651 | if pinfo or qmark1 or qmark2: |
|
650 | if pinfo or qmark1 or qmark2: | |
652 | detail_level = 1 |
|
651 | detail_level = 1 | |
653 | if "*" in oname: |
|
652 | if "*" in oname: | |
654 | self.magic_psearch(oname) |
|
653 | self.magic_psearch(oname) | |
655 | else: |
|
654 | else: | |
656 | self._inspect('pinfo', oname, detail_level=detail_level, |
|
655 | self._inspect('pinfo', oname, detail_level=detail_level, | |
657 | namespaces=namespaces) |
|
656 | namespaces=namespaces) | |
658 |
|
657 | |||
659 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
658 | def magic_pdef(self, parameter_s='', namespaces=None): | |
660 | """Print the definition header for any callable object. |
|
659 | """Print the definition header for any callable object. | |
661 |
|
660 | |||
662 | If the object is a class, print the constructor information.""" |
|
661 | If the object is a class, print the constructor information.""" | |
663 | self._inspect('pdef',parameter_s, namespaces) |
|
662 | self._inspect('pdef',parameter_s, namespaces) | |
664 |
|
663 | |||
665 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
664 | def magic_pdoc(self, parameter_s='', namespaces=None): | |
666 | """Print the docstring for an object. |
|
665 | """Print the docstring for an object. | |
667 |
|
666 | |||
668 | If the given object is a class, it will print both the class and the |
|
667 | If the given object is a class, it will print both the class and the | |
669 | constructor docstrings.""" |
|
668 | constructor docstrings.""" | |
670 | self._inspect('pdoc',parameter_s, namespaces) |
|
669 | self._inspect('pdoc',parameter_s, namespaces) | |
671 |
|
670 | |||
672 | def magic_psource(self, parameter_s='', namespaces=None): |
|
671 | def magic_psource(self, parameter_s='', namespaces=None): | |
673 | """Print (or run through pager) the source code for an object.""" |
|
672 | """Print (or run through pager) the source code for an object.""" | |
674 | self._inspect('psource',parameter_s, namespaces) |
|
673 | self._inspect('psource',parameter_s, namespaces) | |
675 |
|
674 | |||
676 | def magic_pfile(self, parameter_s=''): |
|
675 | def magic_pfile(self, parameter_s=''): | |
677 | """Print (or run through pager) the file where an object is defined. |
|
676 | """Print (or run through pager) the file where an object is defined. | |
678 |
|
677 | |||
679 | The file opens at the line where the object definition begins. IPython |
|
678 | The file opens at the line where the object definition begins. IPython | |
680 | will honor the environment variable PAGER if set, and otherwise will |
|
679 | will honor the environment variable PAGER if set, and otherwise will | |
681 | do its best to print the file in a convenient form. |
|
680 | do its best to print the file in a convenient form. | |
682 |
|
681 | |||
683 | If the given argument is not an object currently defined, IPython will |
|
682 | If the given argument is not an object currently defined, IPython will | |
684 | try to interpret it as a filename (automatically adding a .py extension |
|
683 | try to interpret it as a filename (automatically adding a .py extension | |
685 | if needed). You can thus use %pfile as a syntax highlighting code |
|
684 | if needed). You can thus use %pfile as a syntax highlighting code | |
686 | viewer.""" |
|
685 | viewer.""" | |
687 |
|
686 | |||
688 | # first interpret argument as an object name |
|
687 | # first interpret argument as an object name | |
689 | out = self._inspect('pfile',parameter_s) |
|
688 | out = self._inspect('pfile',parameter_s) | |
690 | # if not, try the input as a filename |
|
689 | # if not, try the input as a filename | |
691 | if out == 'not found': |
|
690 | if out == 'not found': | |
692 | try: |
|
691 | try: | |
693 | filename = get_py_filename(parameter_s) |
|
692 | filename = get_py_filename(parameter_s) | |
694 | except IOError,msg: |
|
693 | except IOError,msg: | |
695 | print msg |
|
694 | print msg | |
696 | return |
|
695 | return | |
697 | page(self.shell.inspector.format(file(filename).read())) |
|
696 | page(self.shell.inspector.format(file(filename).read())) | |
698 |
|
697 | |||
699 | def _inspect(self,meth,oname,namespaces=None,**kw): |
|
698 | def _inspect(self,meth,oname,namespaces=None,**kw): | |
700 | """Generic interface to the inspector system. |
|
699 | """Generic interface to the inspector system. | |
701 |
|
700 | |||
702 | This function is meant to be called by pdef, pdoc & friends.""" |
|
701 | This function is meant to be called by pdef, pdoc & friends.""" | |
703 |
|
702 | |||
704 | #oname = oname.strip() |
|
703 | #oname = oname.strip() | |
705 | #print '1- oname: <%r>' % oname # dbg |
|
704 | #print '1- oname: <%r>' % oname # dbg | |
706 | try: |
|
705 | try: | |
707 | oname = oname.strip().encode('ascii') |
|
706 | oname = oname.strip().encode('ascii') | |
708 | #print '2- oname: <%r>' % oname # dbg |
|
707 | #print '2- oname: <%r>' % oname # dbg | |
709 | except UnicodeEncodeError: |
|
708 | except UnicodeEncodeError: | |
710 | print 'Python identifiers can only contain ascii characters.' |
|
709 | print 'Python identifiers can only contain ascii characters.' | |
711 | return 'not found' |
|
710 | return 'not found' | |
712 |
|
711 | |||
713 | info = Struct(self._ofind(oname, namespaces)) |
|
712 | info = Struct(self._ofind(oname, namespaces)) | |
714 |
|
713 | |||
715 | if info.found: |
|
714 | if info.found: | |
716 | try: |
|
715 | try: | |
717 | IPython.generics.inspect_object(info.obj) |
|
716 | IPython.generics.inspect_object(info.obj) | |
718 | return |
|
717 | return | |
719 | except IPython.ipapi.TryNext: |
|
718 | except IPython.ipapi.TryNext: | |
720 | pass |
|
719 | pass | |
721 | # Get the docstring of the class property if it exists. |
|
720 | # Get the docstring of the class property if it exists. | |
722 | path = oname.split('.') |
|
721 | path = oname.split('.') | |
723 | root = '.'.join(path[:-1]) |
|
722 | root = '.'.join(path[:-1]) | |
724 | if info.parent is not None: |
|
723 | if info.parent is not None: | |
725 | try: |
|
724 | try: | |
726 | target = getattr(info.parent, '__class__') |
|
725 | target = getattr(info.parent, '__class__') | |
727 | # The object belongs to a class instance. |
|
726 | # The object belongs to a class instance. | |
728 | try: |
|
727 | try: | |
729 | target = getattr(target, path[-1]) |
|
728 | target = getattr(target, path[-1]) | |
730 | # The class defines the object. |
|
729 | # The class defines the object. | |
731 | if isinstance(target, property): |
|
730 | if isinstance(target, property): | |
732 | oname = root + '.__class__.' + path[-1] |
|
731 | oname = root + '.__class__.' + path[-1] | |
733 | info = Struct(self._ofind(oname)) |
|
732 | info = Struct(self._ofind(oname)) | |
734 | except AttributeError: pass |
|
733 | except AttributeError: pass | |
735 | except AttributeError: pass |
|
734 | except AttributeError: pass | |
736 |
|
735 | |||
737 | pmethod = getattr(self.shell.inspector,meth) |
|
736 | pmethod = getattr(self.shell.inspector,meth) | |
738 | formatter = info.ismagic and self.format_screen or None |
|
737 | formatter = info.ismagic and self.format_screen or None | |
739 | if meth == 'pdoc': |
|
738 | if meth == 'pdoc': | |
740 | pmethod(info.obj,oname,formatter) |
|
739 | pmethod(info.obj,oname,formatter) | |
741 | elif meth == 'pinfo': |
|
740 | elif meth == 'pinfo': | |
742 | pmethod(info.obj,oname,formatter,info,**kw) |
|
741 | pmethod(info.obj,oname,formatter,info,**kw) | |
743 | else: |
|
742 | else: | |
744 | pmethod(info.obj,oname) |
|
743 | pmethod(info.obj,oname) | |
745 | else: |
|
744 | else: | |
746 | print 'Object `%s` not found.' % oname |
|
745 | print 'Object `%s` not found.' % oname | |
747 | return 'not found' # so callers can take other action |
|
746 | return 'not found' # so callers can take other action | |
748 |
|
747 | |||
749 | def magic_psearch(self, parameter_s=''): |
|
748 | def magic_psearch(self, parameter_s=''): | |
750 | """Search for object in namespaces by wildcard. |
|
749 | """Search for object in namespaces by wildcard. | |
751 |
|
750 | |||
752 | %psearch [options] PATTERN [OBJECT TYPE] |
|
751 | %psearch [options] PATTERN [OBJECT TYPE] | |
753 |
|
752 | |||
754 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
753 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |
755 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
754 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |
756 | rest of the command line must be unchanged (options come first), so |
|
755 | rest of the command line must be unchanged (options come first), so | |
757 | for example the following forms are equivalent |
|
756 | for example the following forms are equivalent | |
758 |
|
757 | |||
759 | %psearch -i a* function |
|
758 | %psearch -i a* function | |
760 | -i a* function? |
|
759 | -i a* function? | |
761 | ?-i a* function |
|
760 | ?-i a* function | |
762 |
|
761 | |||
763 | Arguments: |
|
762 | Arguments: | |
764 |
|
763 | |||
765 | PATTERN |
|
764 | PATTERN | |
766 |
|
765 | |||
767 | where PATTERN is a string containing * as a wildcard similar to its |
|
766 | where PATTERN is a string containing * as a wildcard similar to its | |
768 | use in a shell. The pattern is matched in all namespaces on the |
|
767 | use in a shell. The pattern is matched in all namespaces on the | |
769 | search path. By default objects starting with a single _ are not |
|
768 | search path. By default objects starting with a single _ are not | |
770 | matched, many IPython generated objects have a single |
|
769 | matched, many IPython generated objects have a single | |
771 | underscore. The default is case insensitive matching. Matching is |
|
770 | underscore. The default is case insensitive matching. Matching is | |
772 | also done on the attributes of objects and not only on the objects |
|
771 | also done on the attributes of objects and not only on the objects | |
773 | in a module. |
|
772 | in a module. | |
774 |
|
773 | |||
775 | [OBJECT TYPE] |
|
774 | [OBJECT TYPE] | |
776 |
|
775 | |||
777 | Is the name of a python type from the types module. The name is |
|
776 | Is the name of a python type from the types module. The name is | |
778 | given in lowercase without the ending type, ex. StringType is |
|
777 | given in lowercase without the ending type, ex. StringType is | |
779 | written string. By adding a type here only objects matching the |
|
778 | written string. By adding a type here only objects matching the | |
780 | given type are matched. Using all here makes the pattern match all |
|
779 | given type are matched. Using all here makes the pattern match all | |
781 | types (this is the default). |
|
780 | types (this is the default). | |
782 |
|
781 | |||
783 | Options: |
|
782 | Options: | |
784 |
|
783 | |||
785 | -a: makes the pattern match even objects whose names start with a |
|
784 | -a: makes the pattern match even objects whose names start with a | |
786 | single underscore. These names are normally ommitted from the |
|
785 | single underscore. These names are normally ommitted from the | |
787 | search. |
|
786 | search. | |
788 |
|
787 | |||
789 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
788 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |
790 | these options is given, the default is read from your ipythonrc |
|
789 | these options is given, the default is read from your ipythonrc | |
791 | file. The option name which sets this value is |
|
790 | file. The option name which sets this value is | |
792 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
791 | 'wildcards_case_sensitive'. If this option is not specified in your | |
793 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
792 | ipythonrc file, IPython's internal default is to do a case sensitive | |
794 | search. |
|
793 | search. | |
795 |
|
794 | |||
796 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
795 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |
797 | specifiy can be searched in any of the following namespaces: |
|
796 | specifiy can be searched in any of the following namespaces: | |
798 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
797 | 'builtin', 'user', 'user_global','internal', 'alias', where | |
799 | 'builtin' and 'user' are the search defaults. Note that you should |
|
798 | 'builtin' and 'user' are the search defaults. Note that you should | |
800 | not use quotes when specifying namespaces. |
|
799 | not use quotes when specifying namespaces. | |
801 |
|
800 | |||
802 | 'Builtin' contains the python module builtin, 'user' contains all |
|
801 | 'Builtin' contains the python module builtin, 'user' contains all | |
803 | user data, 'alias' only contain the shell aliases and no python |
|
802 | user data, 'alias' only contain the shell aliases and no python | |
804 | objects, 'internal' contains objects used by IPython. The |
|
803 | objects, 'internal' contains objects used by IPython. The | |
805 | 'user_global' namespace is only used by embedded IPython instances, |
|
804 | 'user_global' namespace is only used by embedded IPython instances, | |
806 | and it contains module-level globals. You can add namespaces to the |
|
805 | and it contains module-level globals. You can add namespaces to the | |
807 | search with -s or exclude them with -e (these options can be given |
|
806 | search with -s or exclude them with -e (these options can be given | |
808 | more than once). |
|
807 | more than once). | |
809 |
|
808 | |||
810 | Examples: |
|
809 | Examples: | |
811 |
|
810 | |||
812 | %psearch a* -> objects beginning with an a |
|
811 | %psearch a* -> objects beginning with an a | |
813 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
812 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |
814 | %psearch a* function -> all functions beginning with an a |
|
813 | %psearch a* function -> all functions beginning with an a | |
815 | %psearch re.e* -> objects beginning with an e in module re |
|
814 | %psearch re.e* -> objects beginning with an e in module re | |
816 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
815 | %psearch r*.e* -> objects that start with e in modules starting in r | |
817 | %psearch r*.* string -> all strings in modules beginning with r |
|
816 | %psearch r*.* string -> all strings in modules beginning with r | |
818 |
|
817 | |||
819 | Case sensitve search: |
|
818 | Case sensitve search: | |
820 |
|
819 | |||
821 | %psearch -c a* list all object beginning with lower case a |
|
820 | %psearch -c a* list all object beginning with lower case a | |
822 |
|
821 | |||
823 | Show objects beginning with a single _: |
|
822 | Show objects beginning with a single _: | |
824 |
|
823 | |||
825 | %psearch -a _* list objects beginning with a single underscore""" |
|
824 | %psearch -a _* list objects beginning with a single underscore""" | |
826 | try: |
|
825 | try: | |
827 | parameter_s = parameter_s.encode('ascii') |
|
826 | parameter_s = parameter_s.encode('ascii') | |
828 | except UnicodeEncodeError: |
|
827 | except UnicodeEncodeError: | |
829 | print 'Python identifiers can only contain ascii characters.' |
|
828 | print 'Python identifiers can only contain ascii characters.' | |
830 | return |
|
829 | return | |
831 |
|
830 | |||
832 | # default namespaces to be searched |
|
831 | # default namespaces to be searched | |
833 | def_search = ['user','builtin'] |
|
832 | def_search = ['user','builtin'] | |
834 |
|
833 | |||
835 | # Process options/args |
|
834 | # Process options/args | |
836 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
835 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) | |
837 | opt = opts.get |
|
836 | opt = opts.get | |
838 | shell = self.shell |
|
837 | shell = self.shell | |
839 | psearch = shell.inspector.psearch |
|
838 | psearch = shell.inspector.psearch | |
840 |
|
839 | |||
841 | # select case options |
|
840 | # select case options | |
842 | if opts.has_key('i'): |
|
841 | if opts.has_key('i'): | |
843 | ignore_case = True |
|
842 | ignore_case = True | |
844 | elif opts.has_key('c'): |
|
843 | elif opts.has_key('c'): | |
845 | ignore_case = False |
|
844 | ignore_case = False | |
846 | else: |
|
845 | else: | |
847 | ignore_case = not shell.rc.wildcards_case_sensitive |
|
846 | ignore_case = not shell.rc.wildcards_case_sensitive | |
848 |
|
847 | |||
849 | # Build list of namespaces to search from user options |
|
848 | # Build list of namespaces to search from user options | |
850 | def_search.extend(opt('s',[])) |
|
849 | def_search.extend(opt('s',[])) | |
851 | ns_exclude = ns_exclude=opt('e',[]) |
|
850 | ns_exclude = ns_exclude=opt('e',[]) | |
852 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
851 | ns_search = [nm for nm in def_search if nm not in ns_exclude] | |
853 |
|
852 | |||
854 | # Call the actual search |
|
853 | # Call the actual search | |
855 | try: |
|
854 | try: | |
856 | psearch(args,shell.ns_table,ns_search, |
|
855 | psearch(args,shell.ns_table,ns_search, | |
857 | show_all=opt('a'),ignore_case=ignore_case) |
|
856 | show_all=opt('a'),ignore_case=ignore_case) | |
858 | except: |
|
857 | except: | |
859 | shell.showtraceback() |
|
858 | shell.showtraceback() | |
860 |
|
859 | |||
861 | def magic_who_ls(self, parameter_s=''): |
|
860 | def magic_who_ls(self, parameter_s=''): | |
862 | """Return a sorted list of all interactive variables. |
|
861 | """Return a sorted list of all interactive variables. | |
863 |
|
862 | |||
864 | If arguments are given, only variables of types matching these |
|
863 | If arguments are given, only variables of types matching these | |
865 | arguments are returned.""" |
|
864 | arguments are returned.""" | |
866 |
|
865 | |||
867 | user_ns = self.shell.user_ns |
|
866 | user_ns = self.shell.user_ns | |
868 | internal_ns = self.shell.internal_ns |
|
867 | internal_ns = self.shell.internal_ns | |
869 | user_config_ns = self.shell.user_config_ns |
|
868 | user_config_ns = self.shell.user_config_ns | |
870 | out = [] |
|
869 | out = [] | |
871 | typelist = parameter_s.split() |
|
870 | typelist = parameter_s.split() | |
872 |
|
871 | |||
873 | for i in user_ns: |
|
872 | for i in user_ns: | |
874 | if not (i.startswith('_') or i.startswith('_i')) \ |
|
873 | if not (i.startswith('_') or i.startswith('_i')) \ | |
875 | and not (i in internal_ns or i in user_config_ns): |
|
874 | and not (i in internal_ns or i in user_config_ns): | |
876 | if typelist: |
|
875 | if typelist: | |
877 | if type(user_ns[i]).__name__ in typelist: |
|
876 | if type(user_ns[i]).__name__ in typelist: | |
878 | out.append(i) |
|
877 | out.append(i) | |
879 | else: |
|
878 | else: | |
880 | out.append(i) |
|
879 | out.append(i) | |
881 | out.sort() |
|
880 | out.sort() | |
882 | return out |
|
881 | return out | |
883 |
|
882 | |||
884 | def magic_who(self, parameter_s=''): |
|
883 | def magic_who(self, parameter_s=''): | |
885 | """Print all interactive variables, with some minimal formatting. |
|
884 | """Print all interactive variables, with some minimal formatting. | |
886 |
|
885 | |||
887 | If any arguments are given, only variables whose type matches one of |
|
886 | If any arguments are given, only variables whose type matches one of | |
888 | these are printed. For example: |
|
887 | these are printed. For example: | |
889 |
|
888 | |||
890 | %who function str |
|
889 | %who function str | |
891 |
|
890 | |||
892 | will only list functions and strings, excluding all other types of |
|
891 | will only list functions and strings, excluding all other types of | |
893 | variables. To find the proper type names, simply use type(var) at a |
|
892 | variables. To find the proper type names, simply use type(var) at a | |
894 | command line to see how python prints type names. For example: |
|
893 | command line to see how python prints type names. For example: | |
895 |
|
894 | |||
896 | In [1]: type('hello')\\ |
|
895 | In [1]: type('hello')\\ | |
897 | Out[1]: <type 'str'> |
|
896 | Out[1]: <type 'str'> | |
898 |
|
897 | |||
899 | indicates that the type name for strings is 'str'. |
|
898 | indicates that the type name for strings is 'str'. | |
900 |
|
899 | |||
901 | %who always excludes executed names loaded through your configuration |
|
900 | %who always excludes executed names loaded through your configuration | |
902 | file and things which are internal to IPython. |
|
901 | file and things which are internal to IPython. | |
903 |
|
902 | |||
904 | This is deliberate, as typically you may load many modules and the |
|
903 | This is deliberate, as typically you may load many modules and the | |
905 | purpose of %who is to show you only what you've manually defined.""" |
|
904 | purpose of %who is to show you only what you've manually defined.""" | |
906 |
|
905 | |||
907 | varlist = self.magic_who_ls(parameter_s) |
|
906 | varlist = self.magic_who_ls(parameter_s) | |
908 | if not varlist: |
|
907 | if not varlist: | |
909 | if parameter_s: |
|
908 | if parameter_s: | |
910 | print 'No variables match your requested type.' |
|
909 | print 'No variables match your requested type.' | |
911 | else: |
|
910 | else: | |
912 | print 'Interactive namespace is empty.' |
|
911 | print 'Interactive namespace is empty.' | |
913 | return |
|
912 | return | |
914 |
|
913 | |||
915 | # if we have variables, move on... |
|
914 | # if we have variables, move on... | |
916 | count = 0 |
|
915 | count = 0 | |
917 | for i in varlist: |
|
916 | for i in varlist: | |
918 | print i+'\t', |
|
917 | print i+'\t', | |
919 | count += 1 |
|
918 | count += 1 | |
920 | if count > 8: |
|
919 | if count > 8: | |
921 | count = 0 |
|
920 | count = 0 | |
922 |
|
921 | |||
923 |
|
922 | |||
924 |
|
923 | |||
925 | def magic_whos(self, parameter_s=''): |
|
924 | def magic_whos(self, parameter_s=''): | |
926 | """Like %who, but gives some extra information about each variable. |
|
925 | """Like %who, but gives some extra information about each variable. | |
927 |
|
926 | |||
928 | The same type filtering of %who can be applied here. |
|
927 | The same type filtering of %who can be applied here. | |
929 |
|
928 | |||
930 | For all variables, the type is printed. Additionally it prints: |
|
929 | For all variables, the type is printed. Additionally it prints: | |
931 |
|
930 | |||
932 | - For {},[],(): their length. |
|
931 | - For {},[],(): their length. | |
933 |
|
932 | |||
934 | - For numpy and Numeric arrays, a summary with shape, number of |
|
933 | - For numpy and Numeric arrays, a summary with shape, number of | |
935 | elements, typecode and size in memory. |
|
934 | elements, typecode and size in memory. | |
936 |
|
935 | |||
937 | - Everything else: a string representation, snipping their middle if |
|
936 | - Everything else: a string representation, snipping their middle if | |
938 | too long.""" |
|
937 | too long.""" | |
939 |
|
938 | |||
940 | varnames = self.magic_who_ls(parameter_s) |
|
939 | varnames = self.magic_who_ls(parameter_s) | |
941 | if not varnames: |
|
940 | if not varnames: | |
942 | if parameter_s: |
|
941 | if parameter_s: | |
943 | print 'No variables match your requested type.' |
|
942 | print 'No variables match your requested type.' | |
944 | else: |
|
943 | else: | |
945 | print 'Interactive namespace is empty.' |
|
944 | print 'Interactive namespace is empty.' | |
946 | return |
|
945 | return | |
947 |
|
946 | |||
948 | # if we have variables, move on... |
|
947 | # if we have variables, move on... | |
949 |
|
948 | |||
950 | # for these types, show len() instead of data: |
|
949 | # for these types, show len() instead of data: | |
951 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
950 | seq_types = [types.DictType,types.ListType,types.TupleType] | |
952 |
|
951 | |||
953 | # for numpy/Numeric arrays, display summary info |
|
952 | # for numpy/Numeric arrays, display summary info | |
954 | try: |
|
953 | try: | |
955 | import numpy |
|
954 | import numpy | |
956 | except ImportError: |
|
955 | except ImportError: | |
957 | ndarray_type = None |
|
956 | ndarray_type = None | |
958 | else: |
|
957 | else: | |
959 | ndarray_type = numpy.ndarray.__name__ |
|
958 | ndarray_type = numpy.ndarray.__name__ | |
960 | try: |
|
959 | try: | |
961 | import Numeric |
|
960 | import Numeric | |
962 | except ImportError: |
|
961 | except ImportError: | |
963 | array_type = None |
|
962 | array_type = None | |
964 | else: |
|
963 | else: | |
965 | array_type = Numeric.ArrayType.__name__ |
|
964 | array_type = Numeric.ArrayType.__name__ | |
966 |
|
965 | |||
967 | # Find all variable names and types so we can figure out column sizes |
|
966 | # Find all variable names and types so we can figure out column sizes | |
968 | def get_vars(i): |
|
967 | def get_vars(i): | |
969 | return self.shell.user_ns[i] |
|
968 | return self.shell.user_ns[i] | |
970 |
|
969 | |||
971 | # some types are well known and can be shorter |
|
970 | # some types are well known and can be shorter | |
972 | abbrevs = {'IPython.macro.Macro' : 'Macro'} |
|
971 | abbrevs = {'IPython.macro.Macro' : 'Macro'} | |
973 | def type_name(v): |
|
972 | def type_name(v): | |
974 | tn = type(v).__name__ |
|
973 | tn = type(v).__name__ | |
975 | return abbrevs.get(tn,tn) |
|
974 | return abbrevs.get(tn,tn) | |
976 |
|
975 | |||
977 | varlist = map(get_vars,varnames) |
|
976 | varlist = map(get_vars,varnames) | |
978 |
|
977 | |||
979 | typelist = [] |
|
978 | typelist = [] | |
980 | for vv in varlist: |
|
979 | for vv in varlist: | |
981 | tt = type_name(vv) |
|
980 | tt = type_name(vv) | |
982 |
|
981 | |||
983 | if tt=='instance': |
|
982 | if tt=='instance': | |
984 | typelist.append( abbrevs.get(str(vv.__class__), |
|
983 | typelist.append( abbrevs.get(str(vv.__class__), | |
985 | str(vv.__class__))) |
|
984 | str(vv.__class__))) | |
986 | else: |
|
985 | else: | |
987 | typelist.append(tt) |
|
986 | typelist.append(tt) | |
988 |
|
987 | |||
989 | # column labels and # of spaces as separator |
|
988 | # column labels and # of spaces as separator | |
990 | varlabel = 'Variable' |
|
989 | varlabel = 'Variable' | |
991 | typelabel = 'Type' |
|
990 | typelabel = 'Type' | |
992 | datalabel = 'Data/Info' |
|
991 | datalabel = 'Data/Info' | |
993 | colsep = 3 |
|
992 | colsep = 3 | |
994 | # variable format strings |
|
993 | # variable format strings | |
995 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
994 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" | |
996 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
995 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' | |
997 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
996 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
998 | # find the size of the columns to format the output nicely |
|
997 | # find the size of the columns to format the output nicely | |
999 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
998 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
1000 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
999 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
1001 | # table header |
|
1000 | # table header | |
1002 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
1001 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
1003 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
1002 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
1004 | # and the table itself |
|
1003 | # and the table itself | |
1005 | kb = 1024 |
|
1004 | kb = 1024 | |
1006 | Mb = 1048576 # kb**2 |
|
1005 | Mb = 1048576 # kb**2 | |
1007 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
1006 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
1008 | print itpl(vformat), |
|
1007 | print itpl(vformat), | |
1009 | if vtype in seq_types: |
|
1008 | if vtype in seq_types: | |
1010 | print len(var) |
|
1009 | print len(var) | |
1011 | elif vtype in [array_type,ndarray_type]: |
|
1010 | elif vtype in [array_type,ndarray_type]: | |
1012 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
1011 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
1013 | if vtype==ndarray_type: |
|
1012 | if vtype==ndarray_type: | |
1014 | # numpy |
|
1013 | # numpy | |
1015 | vsize = var.size |
|
1014 | vsize = var.size | |
1016 | vbytes = vsize*var.itemsize |
|
1015 | vbytes = vsize*var.itemsize | |
1017 | vdtype = var.dtype |
|
1016 | vdtype = var.dtype | |
1018 | else: |
|
1017 | else: | |
1019 | # Numeric |
|
1018 | # Numeric | |
1020 | vsize = Numeric.size(var) |
|
1019 | vsize = Numeric.size(var) | |
1021 | vbytes = vsize*var.itemsize() |
|
1020 | vbytes = vsize*var.itemsize() | |
1022 | vdtype = var.typecode() |
|
1021 | vdtype = var.typecode() | |
1023 |
|
1022 | |||
1024 | if vbytes < 100000: |
|
1023 | if vbytes < 100000: | |
1025 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
1024 | print aformat % (vshape,vsize,vdtype,vbytes) | |
1026 | else: |
|
1025 | else: | |
1027 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
1026 | print aformat % (vshape,vsize,vdtype,vbytes), | |
1028 | if vbytes < Mb: |
|
1027 | if vbytes < Mb: | |
1029 | print '(%s kb)' % (vbytes/kb,) |
|
1028 | print '(%s kb)' % (vbytes/kb,) | |
1030 | else: |
|
1029 | else: | |
1031 | print '(%s Mb)' % (vbytes/Mb,) |
|
1030 | print '(%s Mb)' % (vbytes/Mb,) | |
1032 | else: |
|
1031 | else: | |
1033 | try: |
|
1032 | try: | |
1034 | vstr = str(var) |
|
1033 | vstr = str(var) | |
1035 | except UnicodeEncodeError: |
|
1034 | except UnicodeEncodeError: | |
1036 | vstr = unicode(var).encode(sys.getdefaultencoding(), |
|
1035 | vstr = unicode(var).encode(sys.getdefaultencoding(), | |
1037 | 'backslashreplace') |
|
1036 | 'backslashreplace') | |
1038 | vstr = vstr.replace('\n','\\n') |
|
1037 | vstr = vstr.replace('\n','\\n') | |
1039 | if len(vstr) < 50: |
|
1038 | if len(vstr) < 50: | |
1040 | print vstr |
|
1039 | print vstr | |
1041 | else: |
|
1040 | else: | |
1042 | printpl(vfmt_short) |
|
1041 | printpl(vfmt_short) | |
1043 |
|
1042 | |||
1044 | def magic_reset(self, parameter_s=''): |
|
1043 | def magic_reset(self, parameter_s=''): | |
1045 | """Resets the namespace by removing all names defined by the user. |
|
1044 | """Resets the namespace by removing all names defined by the user. | |
1046 |
|
1045 | |||
1047 | Input/Output history are left around in case you need them. |
|
1046 | Input/Output history are left around in case you need them. | |
1048 |
|
1047 | |||
1049 | Parameters |
|
1048 | Parameters | |
1050 | ---------- |
|
1049 | ---------- | |
1051 | -y : force reset without asking for confirmation. |
|
1050 | -y : force reset without asking for confirmation. | |
1052 |
|
1051 | |||
1053 | Examples |
|
1052 | Examples | |
1054 | -------- |
|
1053 | -------- | |
1055 | In [6]: a = 1 |
|
1054 | In [6]: a = 1 | |
1056 |
|
1055 | |||
1057 | In [7]: a |
|
1056 | In [7]: a | |
1058 | Out[7]: 1 |
|
1057 | Out[7]: 1 | |
1059 |
|
1058 | |||
1060 | In [8]: 'a' in _ip.user_ns |
|
1059 | In [8]: 'a' in _ip.user_ns | |
1061 | Out[8]: True |
|
1060 | Out[8]: True | |
1062 |
|
1061 | |||
1063 | In [9]: %reset -f |
|
1062 | In [9]: %reset -f | |
1064 |
|
1063 | |||
1065 | In [10]: 'a' in _ip.user_ns |
|
1064 | In [10]: 'a' in _ip.user_ns | |
1066 | Out[10]: False |
|
1065 | Out[10]: False | |
1067 | """ |
|
1066 | """ | |
1068 |
|
1067 | |||
1069 | if parameter_s == '-f': |
|
1068 | if parameter_s == '-f': | |
1070 | ans = True |
|
1069 | ans = True | |
1071 | else: |
|
1070 | else: | |
1072 | ans = self.shell.ask_yes_no( |
|
1071 | ans = self.shell.ask_yes_no( | |
1073 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1072 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
1074 | if not ans: |
|
1073 | if not ans: | |
1075 | print 'Nothing done.' |
|
1074 | print 'Nothing done.' | |
1076 | return |
|
1075 | return | |
1077 | user_ns = self.shell.user_ns |
|
1076 | user_ns = self.shell.user_ns | |
1078 | for i in self.magic_who_ls(): |
|
1077 | for i in self.magic_who_ls(): | |
1079 | del(user_ns[i]) |
|
1078 | del(user_ns[i]) | |
1080 |
|
1079 | |||
1081 | # Also flush the private list of module references kept for script |
|
1080 | # Also flush the private list of module references kept for script | |
1082 | # execution protection |
|
1081 | # execution protection | |
1083 | self.shell.clear_main_mod_cache() |
|
1082 | self.shell.clear_main_mod_cache() | |
1084 |
|
1083 | |||
1085 | def magic_logstart(self,parameter_s=''): |
|
1084 | def magic_logstart(self,parameter_s=''): | |
1086 | """Start logging anywhere in a session. |
|
1085 | """Start logging anywhere in a session. | |
1087 |
|
1086 | |||
1088 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1087 | %logstart [-o|-r|-t] [log_name [log_mode]] | |
1089 |
|
1088 | |||
1090 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1089 | If no name is given, it defaults to a file named 'ipython_log.py' in your | |
1091 | current directory, in 'rotate' mode (see below). |
|
1090 | current directory, in 'rotate' mode (see below). | |
1092 |
|
1091 | |||
1093 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1092 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
1094 | history up to that point and then continues logging. |
|
1093 | history up to that point and then continues logging. | |
1095 |
|
1094 | |||
1096 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1095 | %logstart takes a second optional parameter: logging mode. This can be one | |
1097 | of (note that the modes are given unquoted):\\ |
|
1096 | of (note that the modes are given unquoted):\\ | |
1098 | append: well, that says it.\\ |
|
1097 | append: well, that says it.\\ | |
1099 | backup: rename (if exists) to name~ and start name.\\ |
|
1098 | backup: rename (if exists) to name~ and start name.\\ | |
1100 | global: single logfile in your home dir, appended to.\\ |
|
1099 | global: single logfile in your home dir, appended to.\\ | |
1101 | over : overwrite existing log.\\ |
|
1100 | over : overwrite existing log.\\ | |
1102 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1101 | rotate: create rotating logs name.1~, name.2~, etc. | |
1103 |
|
1102 | |||
1104 | Options: |
|
1103 | Options: | |
1105 |
|
1104 | |||
1106 | -o: log also IPython's output. In this mode, all commands which |
|
1105 | -o: log also IPython's output. In this mode, all commands which | |
1107 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1106 | generate an Out[NN] prompt are recorded to the logfile, right after | |
1108 | their corresponding input line. The output lines are always |
|
1107 | their corresponding input line. The output lines are always | |
1109 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1108 | prepended with a '#[Out]# ' marker, so that the log remains valid | |
1110 | Python code. |
|
1109 | Python code. | |
1111 |
|
1110 | |||
1112 | Since this marker is always the same, filtering only the output from |
|
1111 | Since this marker is always the same, filtering only the output from | |
1113 | a log is very easy, using for example a simple awk call: |
|
1112 | a log is very easy, using for example a simple awk call: | |
1114 |
|
1113 | |||
1115 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1114 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py | |
1116 |
|
1115 | |||
1117 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1116 | -r: log 'raw' input. Normally, IPython's logs contain the processed | |
1118 | input, so that user lines are logged in their final form, converted |
|
1117 | input, so that user lines are logged in their final form, converted | |
1119 | into valid Python. For example, %Exit is logged as |
|
1118 | into valid Python. For example, %Exit is logged as | |
1120 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1119 | '_ip.magic("Exit"). If the -r flag is given, all input is logged | |
1121 | exactly as typed, with no transformations applied. |
|
1120 | exactly as typed, with no transformations applied. | |
1122 |
|
1121 | |||
1123 | -t: put timestamps before each input line logged (these are put in |
|
1122 | -t: put timestamps before each input line logged (these are put in | |
1124 | comments).""" |
|
1123 | comments).""" | |
1125 |
|
1124 | |||
1126 | opts,par = self.parse_options(parameter_s,'ort') |
|
1125 | opts,par = self.parse_options(parameter_s,'ort') | |
1127 | log_output = 'o' in opts |
|
1126 | log_output = 'o' in opts | |
1128 | log_raw_input = 'r' in opts |
|
1127 | log_raw_input = 'r' in opts | |
1129 | timestamp = 't' in opts |
|
1128 | timestamp = 't' in opts | |
1130 |
|
1129 | |||
1131 | rc = self.shell.rc |
|
1130 | rc = self.shell.rc | |
1132 | logger = self.shell.logger |
|
1131 | logger = self.shell.logger | |
1133 |
|
1132 | |||
1134 | # if no args are given, the defaults set in the logger constructor by |
|
1133 | # if no args are given, the defaults set in the logger constructor by | |
1135 | # ipytohn remain valid |
|
1134 | # ipytohn remain valid | |
1136 | if par: |
|
1135 | if par: | |
1137 | try: |
|
1136 | try: | |
1138 | logfname,logmode = par.split() |
|
1137 | logfname,logmode = par.split() | |
1139 | except: |
|
1138 | except: | |
1140 | logfname = par |
|
1139 | logfname = par | |
1141 | logmode = 'backup' |
|
1140 | logmode = 'backup' | |
1142 | else: |
|
1141 | else: | |
1143 | logfname = logger.logfname |
|
1142 | logfname = logger.logfname | |
1144 | logmode = logger.logmode |
|
1143 | logmode = logger.logmode | |
1145 | # put logfname into rc struct as if it had been called on the command |
|
1144 | # put logfname into rc struct as if it had been called on the command | |
1146 | # line, so it ends up saved in the log header Save it in case we need |
|
1145 | # line, so it ends up saved in the log header Save it in case we need | |
1147 | # to restore it... |
|
1146 | # to restore it... | |
1148 | old_logfile = rc.opts.get('logfile','') |
|
1147 | old_logfile = rc.opts.get('logfile','') | |
1149 | if logfname: |
|
1148 | if logfname: | |
1150 | logfname = os.path.expanduser(logfname) |
|
1149 | logfname = os.path.expanduser(logfname) | |
1151 | rc.opts.logfile = logfname |
|
1150 | rc.opts.logfile = logfname | |
1152 | loghead = self.shell.loghead_tpl % (rc.opts,rc.args) |
|
1151 | loghead = self.shell.loghead_tpl % (rc.opts,rc.args) | |
1153 | try: |
|
1152 | try: | |
1154 | started = logger.logstart(logfname,loghead,logmode, |
|
1153 | started = logger.logstart(logfname,loghead,logmode, | |
1155 | log_output,timestamp,log_raw_input) |
|
1154 | log_output,timestamp,log_raw_input) | |
1156 | except: |
|
1155 | except: | |
1157 | rc.opts.logfile = old_logfile |
|
1156 | rc.opts.logfile = old_logfile | |
1158 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1157 | warn("Couldn't start log: %s" % sys.exc_info()[1]) | |
1159 | else: |
|
1158 | else: | |
1160 | # log input history up to this point, optionally interleaving |
|
1159 | # log input history up to this point, optionally interleaving | |
1161 | # output if requested |
|
1160 | # output if requested | |
1162 |
|
1161 | |||
1163 | if timestamp: |
|
1162 | if timestamp: | |
1164 | # disable timestamping for the previous history, since we've |
|
1163 | # disable timestamping for the previous history, since we've | |
1165 | # lost those already (no time machine here). |
|
1164 | # lost those already (no time machine here). | |
1166 | logger.timestamp = False |
|
1165 | logger.timestamp = False | |
1167 |
|
1166 | |||
1168 | if log_raw_input: |
|
1167 | if log_raw_input: | |
1169 | input_hist = self.shell.input_hist_raw |
|
1168 | input_hist = self.shell.input_hist_raw | |
1170 | else: |
|
1169 | else: | |
1171 | input_hist = self.shell.input_hist |
|
1170 | input_hist = self.shell.input_hist | |
1172 |
|
1171 | |||
1173 | if log_output: |
|
1172 | if log_output: | |
1174 | log_write = logger.log_write |
|
1173 | log_write = logger.log_write | |
1175 | output_hist = self.shell.output_hist |
|
1174 | output_hist = self.shell.output_hist | |
1176 | for n in range(1,len(input_hist)-1): |
|
1175 | for n in range(1,len(input_hist)-1): | |
1177 | log_write(input_hist[n].rstrip()) |
|
1176 | log_write(input_hist[n].rstrip()) | |
1178 | if n in output_hist: |
|
1177 | if n in output_hist: | |
1179 | log_write(repr(output_hist[n]),'output') |
|
1178 | log_write(repr(output_hist[n]),'output') | |
1180 | else: |
|
1179 | else: | |
1181 | logger.log_write(input_hist[1:]) |
|
1180 | logger.log_write(input_hist[1:]) | |
1182 | if timestamp: |
|
1181 | if timestamp: | |
1183 | # re-enable timestamping |
|
1182 | # re-enable timestamping | |
1184 | logger.timestamp = True |
|
1183 | logger.timestamp = True | |
1185 |
|
1184 | |||
1186 | print ('Activating auto-logging. ' |
|
1185 | print ('Activating auto-logging. ' | |
1187 | 'Current session state plus future input saved.') |
|
1186 | 'Current session state plus future input saved.') | |
1188 | logger.logstate() |
|
1187 | logger.logstate() | |
1189 |
|
1188 | |||
1190 | def magic_logstop(self,parameter_s=''): |
|
1189 | def magic_logstop(self,parameter_s=''): | |
1191 | """Fully stop logging and close log file. |
|
1190 | """Fully stop logging and close log file. | |
1192 |
|
1191 | |||
1193 | In order to start logging again, a new %logstart call needs to be made, |
|
1192 | In order to start logging again, a new %logstart call needs to be made, | |
1194 | possibly (though not necessarily) with a new filename, mode and other |
|
1193 | possibly (though not necessarily) with a new filename, mode and other | |
1195 | options.""" |
|
1194 | options.""" | |
1196 | self.logger.logstop() |
|
1195 | self.logger.logstop() | |
1197 |
|
1196 | |||
1198 | def magic_logoff(self,parameter_s=''): |
|
1197 | def magic_logoff(self,parameter_s=''): | |
1199 | """Temporarily stop logging. |
|
1198 | """Temporarily stop logging. | |
1200 |
|
1199 | |||
1201 | You must have previously started logging.""" |
|
1200 | You must have previously started logging.""" | |
1202 | self.shell.logger.switch_log(0) |
|
1201 | self.shell.logger.switch_log(0) | |
1203 |
|
1202 | |||
1204 | def magic_logon(self,parameter_s=''): |
|
1203 | def magic_logon(self,parameter_s=''): | |
1205 | """Restart logging. |
|
1204 | """Restart logging. | |
1206 |
|
1205 | |||
1207 | This function is for restarting logging which you've temporarily |
|
1206 | This function is for restarting logging which you've temporarily | |
1208 | stopped with %logoff. For starting logging for the first time, you |
|
1207 | stopped with %logoff. For starting logging for the first time, you | |
1209 | must use the %logstart function, which allows you to specify an |
|
1208 | must use the %logstart function, which allows you to specify an | |
1210 | optional log filename.""" |
|
1209 | optional log filename.""" | |
1211 |
|
1210 | |||
1212 | self.shell.logger.switch_log(1) |
|
1211 | self.shell.logger.switch_log(1) | |
1213 |
|
1212 | |||
1214 | def magic_logstate(self,parameter_s=''): |
|
1213 | def magic_logstate(self,parameter_s=''): | |
1215 | """Print the status of the logging system.""" |
|
1214 | """Print the status of the logging system.""" | |
1216 |
|
1215 | |||
1217 | self.shell.logger.logstate() |
|
1216 | self.shell.logger.logstate() | |
1218 |
|
1217 | |||
1219 | def magic_pdb(self, parameter_s=''): |
|
1218 | def magic_pdb(self, parameter_s=''): | |
1220 | """Control the automatic calling of the pdb interactive debugger. |
|
1219 | """Control the automatic calling of the pdb interactive debugger. | |
1221 |
|
1220 | |||
1222 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1221 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
1223 | argument it works as a toggle. |
|
1222 | argument it works as a toggle. | |
1224 |
|
1223 | |||
1225 | When an exception is triggered, IPython can optionally call the |
|
1224 | When an exception is triggered, IPython can optionally call the | |
1226 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1225 | interactive pdb debugger after the traceback printout. %pdb toggles | |
1227 | this feature on and off. |
|
1226 | this feature on and off. | |
1228 |
|
1227 | |||
1229 | The initial state of this feature is set in your ipythonrc |
|
1228 | The initial state of this feature is set in your ipythonrc | |
1230 | configuration file (the variable is called 'pdb'). |
|
1229 | configuration file (the variable is called 'pdb'). | |
1231 |
|
1230 | |||
1232 | If you want to just activate the debugger AFTER an exception has fired, |
|
1231 | If you want to just activate the debugger AFTER an exception has fired, | |
1233 | without having to type '%pdb on' and rerunning your code, you can use |
|
1232 | without having to type '%pdb on' and rerunning your code, you can use | |
1234 | the %debug magic.""" |
|
1233 | the %debug magic.""" | |
1235 |
|
1234 | |||
1236 | par = parameter_s.strip().lower() |
|
1235 | par = parameter_s.strip().lower() | |
1237 |
|
1236 | |||
1238 | if par: |
|
1237 | if par: | |
1239 | try: |
|
1238 | try: | |
1240 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1239 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] | |
1241 | except KeyError: |
|
1240 | except KeyError: | |
1242 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1241 | print ('Incorrect argument. Use on/1, off/0, ' | |
1243 | 'or nothing for a toggle.') |
|
1242 | 'or nothing for a toggle.') | |
1244 | return |
|
1243 | return | |
1245 | else: |
|
1244 | else: | |
1246 | # toggle |
|
1245 | # toggle | |
1247 | new_pdb = not self.shell.call_pdb |
|
1246 | new_pdb = not self.shell.call_pdb | |
1248 |
|
1247 | |||
1249 | # set on the shell |
|
1248 | # set on the shell | |
1250 | self.shell.call_pdb = new_pdb |
|
1249 | self.shell.call_pdb = new_pdb | |
1251 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1250 | print 'Automatic pdb calling has been turned',on_off(new_pdb) | |
1252 |
|
1251 | |||
1253 | def magic_debug(self, parameter_s=''): |
|
1252 | def magic_debug(self, parameter_s=''): | |
1254 | """Activate the interactive debugger in post-mortem mode. |
|
1253 | """Activate the interactive debugger in post-mortem mode. | |
1255 |
|
1254 | |||
1256 | If an exception has just occurred, this lets you inspect its stack |
|
1255 | If an exception has just occurred, this lets you inspect its stack | |
1257 | frames interactively. Note that this will always work only on the last |
|
1256 | frames interactively. Note that this will always work only on the last | |
1258 | traceback that occurred, so you must call this quickly after an |
|
1257 | traceback that occurred, so you must call this quickly after an | |
1259 | exception that you wish to inspect has fired, because if another one |
|
1258 | exception that you wish to inspect has fired, because if another one | |
1260 | occurs, it clobbers the previous one. |
|
1259 | occurs, it clobbers the previous one. | |
1261 |
|
1260 | |||
1262 | If you want IPython to automatically do this on every exception, see |
|
1261 | If you want IPython to automatically do this on every exception, see | |
1263 | the %pdb magic for more details. |
|
1262 | the %pdb magic for more details. | |
1264 | """ |
|
1263 | """ | |
1265 |
|
1264 | |||
1266 | self.shell.debugger(force=True) |
|
1265 | self.shell.debugger(force=True) | |
1267 |
|
1266 | |||
1268 | @testdec.skip_doctest |
|
1267 | @testdec.skip_doctest | |
1269 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1268 | def magic_prun(self, parameter_s ='',user_mode=1, | |
1270 | opts=None,arg_lst=None,prog_ns=None): |
|
1269 | opts=None,arg_lst=None,prog_ns=None): | |
1271 |
|
1270 | |||
1272 | """Run a statement through the python code profiler. |
|
1271 | """Run a statement through the python code profiler. | |
1273 |
|
1272 | |||
1274 | Usage: |
|
1273 | Usage: | |
1275 | %prun [options] statement |
|
1274 | %prun [options] statement | |
1276 |
|
1275 | |||
1277 | The given statement (which doesn't require quote marks) is run via the |
|
1276 | The given statement (which doesn't require quote marks) is run via the | |
1278 | python profiler in a manner similar to the profile.run() function. |
|
1277 | python profiler in a manner similar to the profile.run() function. | |
1279 | Namespaces are internally managed to work correctly; profile.run |
|
1278 | Namespaces are internally managed to work correctly; profile.run | |
1280 | cannot be used in IPython because it makes certain assumptions about |
|
1279 | cannot be used in IPython because it makes certain assumptions about | |
1281 | namespaces which do not hold under IPython. |
|
1280 | namespaces which do not hold under IPython. | |
1282 |
|
1281 | |||
1283 | Options: |
|
1282 | Options: | |
1284 |
|
1283 | |||
1285 | -l <limit>: you can place restrictions on what or how much of the |
|
1284 | -l <limit>: you can place restrictions on what or how much of the | |
1286 | profile gets printed. The limit value can be: |
|
1285 | profile gets printed. The limit value can be: | |
1287 |
|
1286 | |||
1288 | * A string: only information for function names containing this string |
|
1287 | * A string: only information for function names containing this string | |
1289 | is printed. |
|
1288 | is printed. | |
1290 |
|
1289 | |||
1291 | * An integer: only these many lines are printed. |
|
1290 | * An integer: only these many lines are printed. | |
1292 |
|
1291 | |||
1293 | * A float (between 0 and 1): this fraction of the report is printed |
|
1292 | * A float (between 0 and 1): this fraction of the report is printed | |
1294 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1293 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
1295 |
|
1294 | |||
1296 | You can combine several limits with repeated use of the option. For |
|
1295 | You can combine several limits with repeated use of the option. For | |
1297 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1296 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
1298 | information about class constructors. |
|
1297 | information about class constructors. | |
1299 |
|
1298 | |||
1300 | -r: return the pstats.Stats object generated by the profiling. This |
|
1299 | -r: return the pstats.Stats object generated by the profiling. This | |
1301 | object has all the information about the profile in it, and you can |
|
1300 | object has all the information about the profile in it, and you can | |
1302 | later use it for further analysis or in other functions. |
|
1301 | later use it for further analysis or in other functions. | |
1303 |
|
1302 | |||
1304 | -s <key>: sort profile by given key. You can provide more than one key |
|
1303 | -s <key>: sort profile by given key. You can provide more than one key | |
1305 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1304 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
1306 | default sorting key is 'time'. |
|
1305 | default sorting key is 'time'. | |
1307 |
|
1306 | |||
1308 | The following is copied verbatim from the profile documentation |
|
1307 | The following is copied verbatim from the profile documentation | |
1309 | referenced below: |
|
1308 | referenced below: | |
1310 |
|
1309 | |||
1311 | When more than one key is provided, additional keys are used as |
|
1310 | When more than one key is provided, additional keys are used as | |
1312 | secondary criteria when the there is equality in all keys selected |
|
1311 | secondary criteria when the there is equality in all keys selected | |
1313 | before them. |
|
1312 | before them. | |
1314 |
|
1313 | |||
1315 | Abbreviations can be used for any key names, as long as the |
|
1314 | Abbreviations can be used for any key names, as long as the | |
1316 | abbreviation is unambiguous. The following are the keys currently |
|
1315 | abbreviation is unambiguous. The following are the keys currently | |
1317 | defined: |
|
1316 | defined: | |
1318 |
|
1317 | |||
1319 | Valid Arg Meaning |
|
1318 | Valid Arg Meaning | |
1320 | "calls" call count |
|
1319 | "calls" call count | |
1321 | "cumulative" cumulative time |
|
1320 | "cumulative" cumulative time | |
1322 | "file" file name |
|
1321 | "file" file name | |
1323 | "module" file name |
|
1322 | "module" file name | |
1324 | "pcalls" primitive call count |
|
1323 | "pcalls" primitive call count | |
1325 | "line" line number |
|
1324 | "line" line number | |
1326 | "name" function name |
|
1325 | "name" function name | |
1327 | "nfl" name/file/line |
|
1326 | "nfl" name/file/line | |
1328 | "stdname" standard name |
|
1327 | "stdname" standard name | |
1329 | "time" internal time |
|
1328 | "time" internal time | |
1330 |
|
1329 | |||
1331 | Note that all sorts on statistics are in descending order (placing |
|
1330 | Note that all sorts on statistics are in descending order (placing | |
1332 | most time consuming items first), where as name, file, and line number |
|
1331 | most time consuming items first), where as name, file, and line number | |
1333 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1332 | searches are in ascending order (i.e., alphabetical). The subtle | |
1334 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1333 | distinction between "nfl" and "stdname" is that the standard name is a | |
1335 | sort of the name as printed, which means that the embedded line |
|
1334 | sort of the name as printed, which means that the embedded line | |
1336 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1335 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
1337 | would (if the file names were the same) appear in the string order |
|
1336 | would (if the file names were the same) appear in the string order | |
1338 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1337 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
1339 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1338 | line numbers. In fact, sort_stats("nfl") is the same as | |
1340 | sort_stats("name", "file", "line"). |
|
1339 | sort_stats("name", "file", "line"). | |
1341 |
|
1340 | |||
1342 | -T <filename>: save profile results as shown on screen to a text |
|
1341 | -T <filename>: save profile results as shown on screen to a text | |
1343 | file. The profile is still shown on screen. |
|
1342 | file. The profile is still shown on screen. | |
1344 |
|
1343 | |||
1345 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1344 | -D <filename>: save (via dump_stats) profile statistics to given | |
1346 | filename. This data is in a format understod by the pstats module, and |
|
1345 | filename. This data is in a format understod by the pstats module, and | |
1347 | is generated by a call to the dump_stats() method of profile |
|
1346 | is generated by a call to the dump_stats() method of profile | |
1348 | objects. The profile is still shown on screen. |
|
1347 | objects. The profile is still shown on screen. | |
1349 |
|
1348 | |||
1350 | If you want to run complete programs under the profiler's control, use |
|
1349 | If you want to run complete programs under the profiler's control, use | |
1351 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1350 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
1352 | contains profiler specific options as described here. |
|
1351 | contains profiler specific options as described here. | |
1353 |
|
1352 | |||
1354 | You can read the complete documentation for the profile module with:: |
|
1353 | You can read the complete documentation for the profile module with:: | |
1355 |
|
1354 | |||
1356 | In [1]: import profile; profile.help() |
|
1355 | In [1]: import profile; profile.help() | |
1357 | """ |
|
1356 | """ | |
1358 |
|
1357 | |||
1359 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1358 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) | |
1360 | # protect user quote marks |
|
1359 | # protect user quote marks | |
1361 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1360 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") | |
1362 |
|
1361 | |||
1363 | if user_mode: # regular user call |
|
1362 | if user_mode: # regular user call | |
1364 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1363 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', | |
1365 | list_all=1) |
|
1364 | list_all=1) | |
1366 | namespace = self.shell.user_ns |
|
1365 | namespace = self.shell.user_ns | |
1367 | else: # called to run a program by %run -p |
|
1366 | else: # called to run a program by %run -p | |
1368 | try: |
|
1367 | try: | |
1369 | filename = get_py_filename(arg_lst[0]) |
|
1368 | filename = get_py_filename(arg_lst[0]) | |
1370 | except IOError,msg: |
|
1369 | except IOError,msg: | |
1371 | error(msg) |
|
1370 | error(msg) | |
1372 | return |
|
1371 | return | |
1373 |
|
1372 | |||
1374 | arg_str = 'execfile(filename,prog_ns)' |
|
1373 | arg_str = 'execfile(filename,prog_ns)' | |
1375 | namespace = locals() |
|
1374 | namespace = locals() | |
1376 |
|
1375 | |||
1377 | opts.merge(opts_def) |
|
1376 | opts.merge(opts_def) | |
1378 |
|
1377 | |||
1379 | prof = profile.Profile() |
|
1378 | prof = profile.Profile() | |
1380 | try: |
|
1379 | try: | |
1381 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1380 | prof = prof.runctx(arg_str,namespace,namespace) | |
1382 | sys_exit = '' |
|
1381 | sys_exit = '' | |
1383 | except SystemExit: |
|
1382 | except SystemExit: | |
1384 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1383 | sys_exit = """*** SystemExit exception caught in code being profiled.""" | |
1385 |
|
1384 | |||
1386 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1385 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) | |
1387 |
|
1386 | |||
1388 | lims = opts.l |
|
1387 | lims = opts.l | |
1389 | if lims: |
|
1388 | if lims: | |
1390 | lims = [] # rebuild lims with ints/floats/strings |
|
1389 | lims = [] # rebuild lims with ints/floats/strings | |
1391 | for lim in opts.l: |
|
1390 | for lim in opts.l: | |
1392 | try: |
|
1391 | try: | |
1393 | lims.append(int(lim)) |
|
1392 | lims.append(int(lim)) | |
1394 | except ValueError: |
|
1393 | except ValueError: | |
1395 | try: |
|
1394 | try: | |
1396 | lims.append(float(lim)) |
|
1395 | lims.append(float(lim)) | |
1397 | except ValueError: |
|
1396 | except ValueError: | |
1398 | lims.append(lim) |
|
1397 | lims.append(lim) | |
1399 |
|
1398 | |||
1400 | # Trap output. |
|
1399 | # Trap output. | |
1401 | stdout_trap = StringIO() |
|
1400 | stdout_trap = StringIO() | |
1402 |
|
1401 | |||
1403 | if hasattr(stats,'stream'): |
|
1402 | if hasattr(stats,'stream'): | |
1404 | # In newer versions of python, the stats object has a 'stream' |
|
1403 | # In newer versions of python, the stats object has a 'stream' | |
1405 | # attribute to write into. |
|
1404 | # attribute to write into. | |
1406 | stats.stream = stdout_trap |
|
1405 | stats.stream = stdout_trap | |
1407 | stats.print_stats(*lims) |
|
1406 | stats.print_stats(*lims) | |
1408 | else: |
|
1407 | else: | |
1409 | # For older versions, we manually redirect stdout during printing |
|
1408 | # For older versions, we manually redirect stdout during printing | |
1410 | sys_stdout = sys.stdout |
|
1409 | sys_stdout = sys.stdout | |
1411 | try: |
|
1410 | try: | |
1412 | sys.stdout = stdout_trap |
|
1411 | sys.stdout = stdout_trap | |
1413 | stats.print_stats(*lims) |
|
1412 | stats.print_stats(*lims) | |
1414 | finally: |
|
1413 | finally: | |
1415 | sys.stdout = sys_stdout |
|
1414 | sys.stdout = sys_stdout | |
1416 |
|
1415 | |||
1417 | output = stdout_trap.getvalue() |
|
1416 | output = stdout_trap.getvalue() | |
1418 | output = output.rstrip() |
|
1417 | output = output.rstrip() | |
1419 |
|
1418 | |||
1420 | page(output,screen_lines=self.shell.rc.screen_length) |
|
1419 | page(output,screen_lines=self.shell.rc.screen_length) | |
1421 | print sys_exit, |
|
1420 | print sys_exit, | |
1422 |
|
1421 | |||
1423 | dump_file = opts.D[0] |
|
1422 | dump_file = opts.D[0] | |
1424 | text_file = opts.T[0] |
|
1423 | text_file = opts.T[0] | |
1425 | if dump_file: |
|
1424 | if dump_file: | |
1426 | prof.dump_stats(dump_file) |
|
1425 | prof.dump_stats(dump_file) | |
1427 | print '\n*** Profile stats marshalled to file',\ |
|
1426 | print '\n*** Profile stats marshalled to file',\ | |
1428 | `dump_file`+'.',sys_exit |
|
1427 | `dump_file`+'.',sys_exit | |
1429 | if text_file: |
|
1428 | if text_file: | |
1430 | pfile = file(text_file,'w') |
|
1429 | pfile = file(text_file,'w') | |
1431 | pfile.write(output) |
|
1430 | pfile.write(output) | |
1432 | pfile.close() |
|
1431 | pfile.close() | |
1433 | print '\n*** Profile printout saved to text file',\ |
|
1432 | print '\n*** Profile printout saved to text file',\ | |
1434 | `text_file`+'.',sys_exit |
|
1433 | `text_file`+'.',sys_exit | |
1435 |
|
1434 | |||
1436 | if opts.has_key('r'): |
|
1435 | if opts.has_key('r'): | |
1437 | return stats |
|
1436 | return stats | |
1438 | else: |
|
1437 | else: | |
1439 | return None |
|
1438 | return None | |
1440 |
|
1439 | |||
1441 | @testdec.skip_doctest |
|
1440 | @testdec.skip_doctest | |
1442 | def magic_run(self, parameter_s ='',runner=None, |
|
1441 | def magic_run(self, parameter_s ='',runner=None, | |
1443 | file_finder=get_py_filename): |
|
1442 | file_finder=get_py_filename): | |
1444 | """Run the named file inside IPython as a program. |
|
1443 | """Run the named file inside IPython as a program. | |
1445 |
|
1444 | |||
1446 | Usage:\\ |
|
1445 | Usage:\\ | |
1447 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1446 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] | |
1448 |
|
1447 | |||
1449 | Parameters after the filename are passed as command-line arguments to |
|
1448 | Parameters after the filename are passed as command-line arguments to | |
1450 | the program (put in sys.argv). Then, control returns to IPython's |
|
1449 | the program (put in sys.argv). Then, control returns to IPython's | |
1451 | prompt. |
|
1450 | prompt. | |
1452 |
|
1451 | |||
1453 | This is similar to running at a system prompt:\\ |
|
1452 | This is similar to running at a system prompt:\\ | |
1454 | $ python file args\\ |
|
1453 | $ python file args\\ | |
1455 | but with the advantage of giving you IPython's tracebacks, and of |
|
1454 | but with the advantage of giving you IPython's tracebacks, and of | |
1456 | loading all variables into your interactive namespace for further use |
|
1455 | loading all variables into your interactive namespace for further use | |
1457 | (unless -p is used, see below). |
|
1456 | (unless -p is used, see below). | |
1458 |
|
1457 | |||
1459 | The file is executed in a namespace initially consisting only of |
|
1458 | The file is executed in a namespace initially consisting only of | |
1460 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1459 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
1461 | sees its environment as if it were being run as a stand-alone program |
|
1460 | sees its environment as if it were being run as a stand-alone program | |
1462 | (except for sharing global objects such as previously imported |
|
1461 | (except for sharing global objects such as previously imported | |
1463 | modules). But after execution, the IPython interactive namespace gets |
|
1462 | modules). But after execution, the IPython interactive namespace gets | |
1464 | updated with all variables defined in the program (except for __name__ |
|
1463 | updated with all variables defined in the program (except for __name__ | |
1465 | and sys.argv). This allows for very convenient loading of code for |
|
1464 | and sys.argv). This allows for very convenient loading of code for | |
1466 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1465 | interactive work, while giving each program a 'clean sheet' to run in. | |
1467 |
|
1466 | |||
1468 | Options: |
|
1467 | Options: | |
1469 |
|
1468 | |||
1470 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1469 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
1471 | without extension (as python does under import). This allows running |
|
1470 | without extension (as python does under import). This allows running | |
1472 | scripts and reloading the definitions in them without calling code |
|
1471 | scripts and reloading the definitions in them without calling code | |
1473 | protected by an ' if __name__ == "__main__" ' clause. |
|
1472 | protected by an ' if __name__ == "__main__" ' clause. | |
1474 |
|
1473 | |||
1475 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1474 | -i: run the file in IPython's namespace instead of an empty one. This | |
1476 | is useful if you are experimenting with code written in a text editor |
|
1475 | is useful if you are experimenting with code written in a text editor | |
1477 | which depends on variables defined interactively. |
|
1476 | which depends on variables defined interactively. | |
1478 |
|
1477 | |||
1479 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1478 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
1480 | being run. This is particularly useful if IPython is being used to |
|
1479 | being run. This is particularly useful if IPython is being used to | |
1481 | run unittests, which always exit with a sys.exit() call. In such |
|
1480 | run unittests, which always exit with a sys.exit() call. In such | |
1482 | cases you are interested in the output of the test results, not in |
|
1481 | cases you are interested in the output of the test results, not in | |
1483 | seeing a traceback of the unittest module. |
|
1482 | seeing a traceback of the unittest module. | |
1484 |
|
1483 | |||
1485 | -t: print timing information at the end of the run. IPython will give |
|
1484 | -t: print timing information at the end of the run. IPython will give | |
1486 | you an estimated CPU time consumption for your script, which under |
|
1485 | you an estimated CPU time consumption for your script, which under | |
1487 | Unix uses the resource module to avoid the wraparound problems of |
|
1486 | Unix uses the resource module to avoid the wraparound problems of | |
1488 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1487 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
1489 | is also given (for Windows platforms this is reported as 0.0). |
|
1488 | is also given (for Windows platforms this is reported as 0.0). | |
1490 |
|
1489 | |||
1491 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1490 | If -t is given, an additional -N<N> option can be given, where <N> | |
1492 | must be an integer indicating how many times you want the script to |
|
1491 | must be an integer indicating how many times you want the script to | |
1493 | run. The final timing report will include total and per run results. |
|
1492 | run. The final timing report will include total and per run results. | |
1494 |
|
1493 | |||
1495 | For example (testing the script uniq_stable.py): |
|
1494 | For example (testing the script uniq_stable.py): | |
1496 |
|
1495 | |||
1497 | In [1]: run -t uniq_stable |
|
1496 | In [1]: run -t uniq_stable | |
1498 |
|
1497 | |||
1499 | IPython CPU timings (estimated):\\ |
|
1498 | IPython CPU timings (estimated):\\ | |
1500 | User : 0.19597 s.\\ |
|
1499 | User : 0.19597 s.\\ | |
1501 | System: 0.0 s.\\ |
|
1500 | System: 0.0 s.\\ | |
1502 |
|
1501 | |||
1503 | In [2]: run -t -N5 uniq_stable |
|
1502 | In [2]: run -t -N5 uniq_stable | |
1504 |
|
1503 | |||
1505 | IPython CPU timings (estimated):\\ |
|
1504 | IPython CPU timings (estimated):\\ | |
1506 | Total runs performed: 5\\ |
|
1505 | Total runs performed: 5\\ | |
1507 | Times : Total Per run\\ |
|
1506 | Times : Total Per run\\ | |
1508 | User : 0.910862 s, 0.1821724 s.\\ |
|
1507 | User : 0.910862 s, 0.1821724 s.\\ | |
1509 | System: 0.0 s, 0.0 s. |
|
1508 | System: 0.0 s, 0.0 s. | |
1510 |
|
1509 | |||
1511 | -d: run your program under the control of pdb, the Python debugger. |
|
1510 | -d: run your program under the control of pdb, the Python debugger. | |
1512 | This allows you to execute your program step by step, watch variables, |
|
1511 | This allows you to execute your program step by step, watch variables, | |
1513 | etc. Internally, what IPython does is similar to calling: |
|
1512 | etc. Internally, what IPython does is similar to calling: | |
1514 |
|
1513 | |||
1515 | pdb.run('execfile("YOURFILENAME")') |
|
1514 | pdb.run('execfile("YOURFILENAME")') | |
1516 |
|
1515 | |||
1517 | with a breakpoint set on line 1 of your file. You can change the line |
|
1516 | with a breakpoint set on line 1 of your file. You can change the line | |
1518 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1517 | number for this automatic breakpoint to be <N> by using the -bN option | |
1519 | (where N must be an integer). For example: |
|
1518 | (where N must be an integer). For example: | |
1520 |
|
1519 | |||
1521 | %run -d -b40 myscript |
|
1520 | %run -d -b40 myscript | |
1522 |
|
1521 | |||
1523 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1522 | will set the first breakpoint at line 40 in myscript.py. Note that | |
1524 | the first breakpoint must be set on a line which actually does |
|
1523 | the first breakpoint must be set on a line which actually does | |
1525 | something (not a comment or docstring) for it to stop execution. |
|
1524 | something (not a comment or docstring) for it to stop execution. | |
1526 |
|
1525 | |||
1527 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1526 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
1528 | first enter 'c' (without qoutes) to start execution up to the first |
|
1527 | first enter 'c' (without qoutes) to start execution up to the first | |
1529 | breakpoint. |
|
1528 | breakpoint. | |
1530 |
|
1529 | |||
1531 | Entering 'help' gives information about the use of the debugger. You |
|
1530 | Entering 'help' gives information about the use of the debugger. You | |
1532 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1531 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
1533 | at a prompt. |
|
1532 | at a prompt. | |
1534 |
|
1533 | |||
1535 | -p: run program under the control of the Python profiler module (which |
|
1534 | -p: run program under the control of the Python profiler module (which | |
1536 | prints a detailed report of execution times, function calls, etc). |
|
1535 | prints a detailed report of execution times, function calls, etc). | |
1537 |
|
1536 | |||
1538 | You can pass other options after -p which affect the behavior of the |
|
1537 | You can pass other options after -p which affect the behavior of the | |
1539 | profiler itself. See the docs for %prun for details. |
|
1538 | profiler itself. See the docs for %prun for details. | |
1540 |
|
1539 | |||
1541 | In this mode, the program's variables do NOT propagate back to the |
|
1540 | In this mode, the program's variables do NOT propagate back to the | |
1542 | IPython interactive namespace (because they remain in the namespace |
|
1541 | IPython interactive namespace (because they remain in the namespace | |
1543 | where the profiler executes them). |
|
1542 | where the profiler executes them). | |
1544 |
|
1543 | |||
1545 | Internally this triggers a call to %prun, see its documentation for |
|
1544 | Internally this triggers a call to %prun, see its documentation for | |
1546 | details on the options available specifically for profiling. |
|
1545 | details on the options available specifically for profiling. | |
1547 |
|
1546 | |||
1548 | There is one special usage for which the text above doesn't apply: |
|
1547 | There is one special usage for which the text above doesn't apply: | |
1549 | if the filename ends with .ipy, the file is run as ipython script, |
|
1548 | if the filename ends with .ipy, the file is run as ipython script, | |
1550 | just as if the commands were written on IPython prompt. |
|
1549 | just as if the commands were written on IPython prompt. | |
1551 | """ |
|
1550 | """ | |
1552 |
|
1551 | |||
1553 | # get arguments and set sys.argv for program to be run. |
|
1552 | # get arguments and set sys.argv for program to be run. | |
1554 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1553 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', | |
1555 | mode='list',list_all=1) |
|
1554 | mode='list',list_all=1) | |
1556 |
|
1555 | |||
1557 | try: |
|
1556 | try: | |
1558 | filename = file_finder(arg_lst[0]) |
|
1557 | filename = file_finder(arg_lst[0]) | |
1559 | except IndexError: |
|
1558 | except IndexError: | |
1560 | warn('you must provide at least a filename.') |
|
1559 | warn('you must provide at least a filename.') | |
1561 | print '\n%run:\n',OInspect.getdoc(self.magic_run) |
|
1560 | print '\n%run:\n',OInspect.getdoc(self.magic_run) | |
1562 | return |
|
1561 | return | |
1563 | except IOError,msg: |
|
1562 | except IOError,msg: | |
1564 | error(msg) |
|
1563 | error(msg) | |
1565 | return |
|
1564 | return | |
1566 |
|
1565 | |||
1567 | if filename.lower().endswith('.ipy'): |
|
1566 | if filename.lower().endswith('.ipy'): | |
1568 | self.api.runlines(open(filename).read()) |
|
1567 | self.api.runlines(open(filename).read()) | |
1569 | return |
|
1568 | return | |
1570 |
|
1569 | |||
1571 | # Control the response to exit() calls made by the script being run |
|
1570 | # Control the response to exit() calls made by the script being run | |
1572 | exit_ignore = opts.has_key('e') |
|
1571 | exit_ignore = opts.has_key('e') | |
1573 |
|
1572 | |||
1574 | # Make sure that the running script gets a proper sys.argv as if it |
|
1573 | # Make sure that the running script gets a proper sys.argv as if it | |
1575 | # were run from a system shell. |
|
1574 | # were run from a system shell. | |
1576 | save_argv = sys.argv # save it for later restoring |
|
1575 | save_argv = sys.argv # save it for later restoring | |
1577 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1576 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename | |
1578 |
|
1577 | |||
1579 | if opts.has_key('i'): |
|
1578 | if opts.has_key('i'): | |
1580 | # Run in user's interactive namespace |
|
1579 | # Run in user's interactive namespace | |
1581 | prog_ns = self.shell.user_ns |
|
1580 | prog_ns = self.shell.user_ns | |
1582 | __name__save = self.shell.user_ns['__name__'] |
|
1581 | __name__save = self.shell.user_ns['__name__'] | |
1583 | prog_ns['__name__'] = '__main__' |
|
1582 | prog_ns['__name__'] = '__main__' | |
1584 | main_mod = FakeModule(prog_ns) |
|
1583 | main_mod = FakeModule(prog_ns) | |
1585 | else: |
|
1584 | else: | |
1586 | # Run in a fresh, empty namespace |
|
1585 | # Run in a fresh, empty namespace | |
1587 | if opts.has_key('n'): |
|
1586 | if opts.has_key('n'): | |
1588 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1587 | name = os.path.splitext(os.path.basename(filename))[0] | |
1589 | else: |
|
1588 | else: | |
1590 | name = '__main__' |
|
1589 | name = '__main__' | |
1591 | main_mod = FakeModule() |
|
1590 | main_mod = FakeModule() | |
1592 | prog_ns = main_mod.__dict__ |
|
1591 | prog_ns = main_mod.__dict__ | |
1593 | prog_ns['__name__'] = name |
|
1592 | prog_ns['__name__'] = name | |
1594 |
|
1593 | |||
1595 | # The shell MUST hold a reference to main_mod so after %run exits, |
|
1594 | # The shell MUST hold a reference to main_mod so after %run exits, | |
1596 | # the python deletion mechanism doesn't zero it out (leaving |
|
1595 | # the python deletion mechanism doesn't zero it out (leaving | |
1597 | # dangling references). However, we should drop old versions of |
|
1596 | # dangling references). However, we should drop old versions of | |
1598 | # main_mod. There is now a proper API to manage this caching in |
|
1597 | # main_mod. There is now a proper API to manage this caching in | |
1599 | # the main shell object, we use that. |
|
1598 | # the main shell object, we use that. | |
1600 | self.shell.cache_main_mod(main_mod) |
|
1599 | self.shell.cache_main_mod(main_mod) | |
1601 |
|
1600 | |||
1602 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1601 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must | |
1603 | # set the __file__ global in the script's namespace |
|
1602 | # set the __file__ global in the script's namespace | |
1604 | prog_ns['__file__'] = filename |
|
1603 | prog_ns['__file__'] = filename | |
1605 |
|
1604 | |||
1606 | # pickle fix. See iplib for an explanation. But we need to make sure |
|
1605 | # pickle fix. See iplib for an explanation. But we need to make sure | |
1607 | # that, if we overwrite __main__, we replace it at the end |
|
1606 | # that, if we overwrite __main__, we replace it at the end | |
1608 | main_mod_name = prog_ns['__name__'] |
|
1607 | main_mod_name = prog_ns['__name__'] | |
1609 |
|
1608 | |||
1610 | if main_mod_name == '__main__': |
|
1609 | if main_mod_name == '__main__': | |
1611 | restore_main = sys.modules['__main__'] |
|
1610 | restore_main = sys.modules['__main__'] | |
1612 | else: |
|
1611 | else: | |
1613 | restore_main = False |
|
1612 | restore_main = False | |
1614 |
|
1613 | |||
1615 | # This needs to be undone at the end to prevent holding references to |
|
1614 | # This needs to be undone at the end to prevent holding references to | |
1616 | # every single object ever created. |
|
1615 | # every single object ever created. | |
1617 | sys.modules[main_mod_name] = main_mod |
|
1616 | sys.modules[main_mod_name] = main_mod | |
1618 |
|
1617 | |||
1619 | stats = None |
|
1618 | stats = None | |
1620 | try: |
|
1619 | try: | |
1621 | self.shell.savehist() |
|
1620 | self.shell.savehist() | |
1622 |
|
1621 | |||
1623 | if opts.has_key('p'): |
|
1622 | if opts.has_key('p'): | |
1624 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1623 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) | |
1625 | else: |
|
1624 | else: | |
1626 | if opts.has_key('d'): |
|
1625 | if opts.has_key('d'): | |
1627 | deb = Debugger.Pdb(self.shell.rc.colors) |
|
1626 | deb = Debugger.Pdb(self.shell.rc.colors) | |
1628 | # reset Breakpoint state, which is moronically kept |
|
1627 | # reset Breakpoint state, which is moronically kept | |
1629 | # in a class |
|
1628 | # in a class | |
1630 | bdb.Breakpoint.next = 1 |
|
1629 | bdb.Breakpoint.next = 1 | |
1631 | bdb.Breakpoint.bplist = {} |
|
1630 | bdb.Breakpoint.bplist = {} | |
1632 | bdb.Breakpoint.bpbynumber = [None] |
|
1631 | bdb.Breakpoint.bpbynumber = [None] | |
1633 | # Set an initial breakpoint to stop execution |
|
1632 | # Set an initial breakpoint to stop execution | |
1634 | maxtries = 10 |
|
1633 | maxtries = 10 | |
1635 | bp = int(opts.get('b',[1])[0]) |
|
1634 | bp = int(opts.get('b',[1])[0]) | |
1636 | checkline = deb.checkline(filename,bp) |
|
1635 | checkline = deb.checkline(filename,bp) | |
1637 | if not checkline: |
|
1636 | if not checkline: | |
1638 | for bp in range(bp+1,bp+maxtries+1): |
|
1637 | for bp in range(bp+1,bp+maxtries+1): | |
1639 | if deb.checkline(filename,bp): |
|
1638 | if deb.checkline(filename,bp): | |
1640 | break |
|
1639 | break | |
1641 | else: |
|
1640 | else: | |
1642 | msg = ("\nI failed to find a valid line to set " |
|
1641 | msg = ("\nI failed to find a valid line to set " | |
1643 | "a breakpoint\n" |
|
1642 | "a breakpoint\n" | |
1644 | "after trying up to line: %s.\n" |
|
1643 | "after trying up to line: %s.\n" | |
1645 | "Please set a valid breakpoint manually " |
|
1644 | "Please set a valid breakpoint manually " | |
1646 | "with the -b option." % bp) |
|
1645 | "with the -b option." % bp) | |
1647 | error(msg) |
|
1646 | error(msg) | |
1648 | return |
|
1647 | return | |
1649 | # if we find a good linenumber, set the breakpoint |
|
1648 | # if we find a good linenumber, set the breakpoint | |
1650 | deb.do_break('%s:%s' % (filename,bp)) |
|
1649 | deb.do_break('%s:%s' % (filename,bp)) | |
1651 | # Start file run |
|
1650 | # Start file run | |
1652 | print "NOTE: Enter 'c' at the", |
|
1651 | print "NOTE: Enter 'c' at the", | |
1653 | print "%s prompt to start your script." % deb.prompt |
|
1652 | print "%s prompt to start your script." % deb.prompt | |
1654 | try: |
|
1653 | try: | |
1655 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1654 | deb.run('execfile("%s")' % filename,prog_ns) | |
1656 |
|
1655 | |||
1657 | except: |
|
1656 | except: | |
1658 | etype, value, tb = sys.exc_info() |
|
1657 | etype, value, tb = sys.exc_info() | |
1659 | # Skip three frames in the traceback: the %run one, |
|
1658 | # Skip three frames in the traceback: the %run one, | |
1660 | # one inside bdb.py, and the command-line typed by the |
|
1659 | # one inside bdb.py, and the command-line typed by the | |
1661 | # user (run by exec in pdb itself). |
|
1660 | # user (run by exec in pdb itself). | |
1662 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1661 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) | |
1663 | else: |
|
1662 | else: | |
1664 | if runner is None: |
|
1663 | if runner is None: | |
1665 | runner = self.shell.safe_execfile |
|
1664 | runner = self.shell.safe_execfile | |
1666 | if opts.has_key('t'): |
|
1665 | if opts.has_key('t'): | |
1667 | # timed execution |
|
1666 | # timed execution | |
1668 | try: |
|
1667 | try: | |
1669 | nruns = int(opts['N'][0]) |
|
1668 | nruns = int(opts['N'][0]) | |
1670 | if nruns < 1: |
|
1669 | if nruns < 1: | |
1671 | error('Number of runs must be >=1') |
|
1670 | error('Number of runs must be >=1') | |
1672 | return |
|
1671 | return | |
1673 | except (KeyError): |
|
1672 | except (KeyError): | |
1674 | nruns = 1 |
|
1673 | nruns = 1 | |
1675 | if nruns == 1: |
|
1674 | if nruns == 1: | |
1676 | t0 = clock2() |
|
1675 | t0 = clock2() | |
1677 | runner(filename,prog_ns,prog_ns, |
|
1676 | runner(filename,prog_ns,prog_ns, | |
1678 | exit_ignore=exit_ignore) |
|
1677 | exit_ignore=exit_ignore) | |
1679 | t1 = clock2() |
|
1678 | t1 = clock2() | |
1680 | t_usr = t1[0]-t0[0] |
|
1679 | t_usr = t1[0]-t0[0] | |
1681 | t_sys = t1[1]-t1[1] |
|
1680 | t_sys = t1[1]-t1[1] | |
1682 | print "\nIPython CPU timings (estimated):" |
|
1681 | print "\nIPython CPU timings (estimated):" | |
1683 | print " User : %10s s." % t_usr |
|
1682 | print " User : %10s s." % t_usr | |
1684 | print " System: %10s s." % t_sys |
|
1683 | print " System: %10s s." % t_sys | |
1685 | else: |
|
1684 | else: | |
1686 | runs = range(nruns) |
|
1685 | runs = range(nruns) | |
1687 | t0 = clock2() |
|
1686 | t0 = clock2() | |
1688 | for nr in runs: |
|
1687 | for nr in runs: | |
1689 | runner(filename,prog_ns,prog_ns, |
|
1688 | runner(filename,prog_ns,prog_ns, | |
1690 | exit_ignore=exit_ignore) |
|
1689 | exit_ignore=exit_ignore) | |
1691 | t1 = clock2() |
|
1690 | t1 = clock2() | |
1692 | t_usr = t1[0]-t0[0] |
|
1691 | t_usr = t1[0]-t0[0] | |
1693 | t_sys = t1[1]-t1[1] |
|
1692 | t_sys = t1[1]-t1[1] | |
1694 | print "\nIPython CPU timings (estimated):" |
|
1693 | print "\nIPython CPU timings (estimated):" | |
1695 | print "Total runs performed:",nruns |
|
1694 | print "Total runs performed:",nruns | |
1696 | print " Times : %10s %10s" % ('Total','Per run') |
|
1695 | print " Times : %10s %10s" % ('Total','Per run') | |
1697 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1696 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) | |
1698 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1697 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) | |
1699 |
|
1698 | |||
1700 | else: |
|
1699 | else: | |
1701 | # regular execution |
|
1700 | # regular execution | |
1702 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1701 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1703 | if opts.has_key('i'): |
|
1702 | if opts.has_key('i'): | |
1704 | self.shell.user_ns['__name__'] = __name__save |
|
1703 | self.shell.user_ns['__name__'] = __name__save | |
1705 | else: |
|
1704 | else: | |
1706 | # update IPython interactive namespace |
|
1705 | # update IPython interactive namespace | |
1707 | del prog_ns['__name__'] |
|
1706 | del prog_ns['__name__'] | |
1708 | self.shell.user_ns.update(prog_ns) |
|
1707 | self.shell.user_ns.update(prog_ns) | |
1709 | finally: |
|
1708 | finally: | |
1710 | # Ensure key global structures are restored |
|
1709 | # Ensure key global structures are restored | |
1711 | sys.argv = save_argv |
|
1710 | sys.argv = save_argv | |
1712 | if restore_main: |
|
1711 | if restore_main: | |
1713 | sys.modules['__main__'] = restore_main |
|
1712 | sys.modules['__main__'] = restore_main | |
1714 | else: |
|
1713 | else: | |
1715 | # Remove from sys.modules the reference to main_mod we'd |
|
1714 | # Remove from sys.modules the reference to main_mod we'd | |
1716 | # added. Otherwise it will trap references to objects |
|
1715 | # added. Otherwise it will trap references to objects | |
1717 | # contained therein. |
|
1716 | # contained therein. | |
1718 | del sys.modules[main_mod_name] |
|
1717 | del sys.modules[main_mod_name] | |
1719 | self.shell.reloadhist() |
|
1718 | self.shell.reloadhist() | |
1720 |
|
1719 | |||
1721 | return stats |
|
1720 | return stats | |
1722 |
|
1721 | |||
1723 | def magic_runlog(self, parameter_s =''): |
|
1722 | def magic_runlog(self, parameter_s =''): | |
1724 | """Run files as logs. |
|
1723 | """Run files as logs. | |
1725 |
|
1724 | |||
1726 | Usage:\\ |
|
1725 | Usage:\\ | |
1727 | %runlog file1 file2 ... |
|
1726 | %runlog file1 file2 ... | |
1728 |
|
1727 | |||
1729 | Run the named files (treating them as log files) in sequence inside |
|
1728 | Run the named files (treating them as log files) in sequence inside | |
1730 | the interpreter, and return to the prompt. This is much slower than |
|
1729 | the interpreter, and return to the prompt. This is much slower than | |
1731 | %run because each line is executed in a try/except block, but it |
|
1730 | %run because each line is executed in a try/except block, but it | |
1732 | allows running files with syntax errors in them. |
|
1731 | allows running files with syntax errors in them. | |
1733 |
|
1732 | |||
1734 | Normally IPython will guess when a file is one of its own logfiles, so |
|
1733 | Normally IPython will guess when a file is one of its own logfiles, so | |
1735 | you can typically use %run even for logs. This shorthand allows you to |
|
1734 | you can typically use %run even for logs. This shorthand allows you to | |
1736 | force any file to be treated as a log file.""" |
|
1735 | force any file to be treated as a log file.""" | |
1737 |
|
1736 | |||
1738 | for f in parameter_s.split(): |
|
1737 | for f in parameter_s.split(): | |
1739 | self.shell.safe_execfile(f,self.shell.user_ns, |
|
1738 | self.shell.safe_execfile(f,self.shell.user_ns, | |
1740 | self.shell.user_ns,islog=1) |
|
1739 | self.shell.user_ns,islog=1) | |
1741 |
|
1740 | |||
1742 | @testdec.skip_doctest |
|
1741 | @testdec.skip_doctest | |
1743 | def magic_timeit(self, parameter_s =''): |
|
1742 | def magic_timeit(self, parameter_s =''): | |
1744 | """Time execution of a Python statement or expression |
|
1743 | """Time execution of a Python statement or expression | |
1745 |
|
1744 | |||
1746 | Usage:\\ |
|
1745 | Usage:\\ | |
1747 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1746 | %timeit [-n<N> -r<R> [-t|-c]] statement | |
1748 |
|
1747 | |||
1749 | Time execution of a Python statement or expression using the timeit |
|
1748 | Time execution of a Python statement or expression using the timeit | |
1750 | module. |
|
1749 | module. | |
1751 |
|
1750 | |||
1752 | Options: |
|
1751 | Options: | |
1753 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1752 | -n<N>: execute the given statement <N> times in a loop. If this value | |
1754 | is not given, a fitting value is chosen. |
|
1753 | is not given, a fitting value is chosen. | |
1755 |
|
1754 | |||
1756 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1755 | -r<R>: repeat the loop iteration <R> times and take the best result. | |
1757 | Default: 3 |
|
1756 | Default: 3 | |
1758 |
|
1757 | |||
1759 | -t: use time.time to measure the time, which is the default on Unix. |
|
1758 | -t: use time.time to measure the time, which is the default on Unix. | |
1760 | This function measures wall time. |
|
1759 | This function measures wall time. | |
1761 |
|
1760 | |||
1762 | -c: use time.clock to measure the time, which is the default on |
|
1761 | -c: use time.clock to measure the time, which is the default on | |
1763 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1762 | Windows and measures wall time. On Unix, resource.getrusage is used | |
1764 | instead and returns the CPU user time. |
|
1763 | instead and returns the CPU user time. | |
1765 |
|
1764 | |||
1766 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1765 | -p<P>: use a precision of <P> digits to display the timing result. | |
1767 | Default: 3 |
|
1766 | Default: 3 | |
1768 |
|
1767 | |||
1769 |
|
1768 | |||
1770 | Examples: |
|
1769 | Examples: | |
1771 |
|
1770 | |||
1772 | In [1]: %timeit pass |
|
1771 | In [1]: %timeit pass | |
1773 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1772 | 10000000 loops, best of 3: 53.3 ns per loop | |
1774 |
|
1773 | |||
1775 | In [2]: u = None |
|
1774 | In [2]: u = None | |
1776 |
|
1775 | |||
1777 | In [3]: %timeit u is None |
|
1776 | In [3]: %timeit u is None | |
1778 | 10000000 loops, best of 3: 184 ns per loop |
|
1777 | 10000000 loops, best of 3: 184 ns per loop | |
1779 |
|
1778 | |||
1780 | In [4]: %timeit -r 4 u == None |
|
1779 | In [4]: %timeit -r 4 u == None | |
1781 | 1000000 loops, best of 4: 242 ns per loop |
|
1780 | 1000000 loops, best of 4: 242 ns per loop | |
1782 |
|
1781 | |||
1783 | In [5]: import time |
|
1782 | In [5]: import time | |
1784 |
|
1783 | |||
1785 | In [6]: %timeit -n1 time.sleep(2) |
|
1784 | In [6]: %timeit -n1 time.sleep(2) | |
1786 | 1 loops, best of 3: 2 s per loop |
|
1785 | 1 loops, best of 3: 2 s per loop | |
1787 |
|
1786 | |||
1788 |
|
1787 | |||
1789 | The times reported by %timeit will be slightly higher than those |
|
1788 | The times reported by %timeit will be slightly higher than those | |
1790 | reported by the timeit.py script when variables are accessed. This is |
|
1789 | reported by the timeit.py script when variables are accessed. This is | |
1791 | due to the fact that %timeit executes the statement in the namespace |
|
1790 | due to the fact that %timeit executes the statement in the namespace | |
1792 | of the shell, compared with timeit.py, which uses a single setup |
|
1791 | of the shell, compared with timeit.py, which uses a single setup | |
1793 | statement to import function or create variables. Generally, the bias |
|
1792 | statement to import function or create variables. Generally, the bias | |
1794 | does not matter as long as results from timeit.py are not mixed with |
|
1793 | does not matter as long as results from timeit.py are not mixed with | |
1795 | those from %timeit.""" |
|
1794 | those from %timeit.""" | |
1796 |
|
1795 | |||
1797 | import timeit |
|
1796 | import timeit | |
1798 | import math |
|
1797 | import math | |
1799 |
|
1798 | |||
1800 | units = [u"s", u"ms", u"\xb5s", u"ns"] |
|
1799 | units = [u"s", u"ms", u"\xb5s", u"ns"] | |
1801 | scaling = [1, 1e3, 1e6, 1e9] |
|
1800 | scaling = [1, 1e3, 1e6, 1e9] | |
1802 |
|
1801 | |||
1803 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1802 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', | |
1804 | posix=False) |
|
1803 | posix=False) | |
1805 | if stmt == "": |
|
1804 | if stmt == "": | |
1806 | return |
|
1805 | return | |
1807 | timefunc = timeit.default_timer |
|
1806 | timefunc = timeit.default_timer | |
1808 | number = int(getattr(opts, "n", 0)) |
|
1807 | number = int(getattr(opts, "n", 0)) | |
1809 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1808 | repeat = int(getattr(opts, "r", timeit.default_repeat)) | |
1810 | precision = int(getattr(opts, "p", 3)) |
|
1809 | precision = int(getattr(opts, "p", 3)) | |
1811 | if hasattr(opts, "t"): |
|
1810 | if hasattr(opts, "t"): | |
1812 | timefunc = time.time |
|
1811 | timefunc = time.time | |
1813 | if hasattr(opts, "c"): |
|
1812 | if hasattr(opts, "c"): | |
1814 | timefunc = clock |
|
1813 | timefunc = clock | |
1815 |
|
1814 | |||
1816 | timer = timeit.Timer(timer=timefunc) |
|
1815 | timer = timeit.Timer(timer=timefunc) | |
1817 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1816 | # this code has tight coupling to the inner workings of timeit.Timer, | |
1818 | # but is there a better way to achieve that the code stmt has access |
|
1817 | # but is there a better way to achieve that the code stmt has access | |
1819 | # to the shell namespace? |
|
1818 | # to the shell namespace? | |
1820 |
|
1819 | |||
1821 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1820 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), | |
1822 | 'setup': "pass"} |
|
1821 | 'setup': "pass"} | |
1823 | # Track compilation time so it can be reported if too long |
|
1822 | # Track compilation time so it can be reported if too long | |
1824 | # Minimum time above which compilation time will be reported |
|
1823 | # Minimum time above which compilation time will be reported | |
1825 | tc_min = 0.1 |
|
1824 | tc_min = 0.1 | |
1826 |
|
1825 | |||
1827 | t0 = clock() |
|
1826 | t0 = clock() | |
1828 | code = compile(src, "<magic-timeit>", "exec") |
|
1827 | code = compile(src, "<magic-timeit>", "exec") | |
1829 | tc = clock()-t0 |
|
1828 | tc = clock()-t0 | |
1830 |
|
1829 | |||
1831 | ns = {} |
|
1830 | ns = {} | |
1832 | exec code in self.shell.user_ns, ns |
|
1831 | exec code in self.shell.user_ns, ns | |
1833 | timer.inner = ns["inner"] |
|
1832 | timer.inner = ns["inner"] | |
1834 |
|
1833 | |||
1835 | if number == 0: |
|
1834 | if number == 0: | |
1836 | # determine number so that 0.2 <= total time < 2.0 |
|
1835 | # determine number so that 0.2 <= total time < 2.0 | |
1837 | number = 1 |
|
1836 | number = 1 | |
1838 | for i in range(1, 10): |
|
1837 | for i in range(1, 10): | |
1839 | number *= 10 |
|
1838 | number *= 10 | |
1840 | if timer.timeit(number) >= 0.2: |
|
1839 | if timer.timeit(number) >= 0.2: | |
1841 | break |
|
1840 | break | |
1842 |
|
1841 | |||
1843 | best = min(timer.repeat(repeat, number)) / number |
|
1842 | best = min(timer.repeat(repeat, number)) / number | |
1844 |
|
1843 | |||
1845 | if best > 0.0: |
|
1844 | if best > 0.0: | |
1846 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1845 | order = min(-int(math.floor(math.log10(best)) // 3), 3) | |
1847 | else: |
|
1846 | else: | |
1848 | order = 3 |
|
1847 | order = 3 | |
1849 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1848 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, | |
1850 | precision, |
|
1849 | precision, | |
1851 | best * scaling[order], |
|
1850 | best * scaling[order], | |
1852 | units[order]) |
|
1851 | units[order]) | |
1853 | if tc > tc_min: |
|
1852 | if tc > tc_min: | |
1854 | print "Compiler time: %.2f s" % tc |
|
1853 | print "Compiler time: %.2f s" % tc | |
1855 |
|
1854 | |||
1856 | @testdec.skip_doctest |
|
1855 | @testdec.skip_doctest | |
1857 | def magic_time(self,parameter_s = ''): |
|
1856 | def magic_time(self,parameter_s = ''): | |
1858 | """Time execution of a Python statement or expression. |
|
1857 | """Time execution of a Python statement or expression. | |
1859 |
|
1858 | |||
1860 | The CPU and wall clock times are printed, and the value of the |
|
1859 | The CPU and wall clock times are printed, and the value of the | |
1861 | expression (if any) is returned. Note that under Win32, system time |
|
1860 | expression (if any) is returned. Note that under Win32, system time | |
1862 | is always reported as 0, since it can not be measured. |
|
1861 | is always reported as 0, since it can not be measured. | |
1863 |
|
1862 | |||
1864 | This function provides very basic timing functionality. In Python |
|
1863 | This function provides very basic timing functionality. In Python | |
1865 | 2.3, the timeit module offers more control and sophistication, so this |
|
1864 | 2.3, the timeit module offers more control and sophistication, so this | |
1866 | could be rewritten to use it (patches welcome). |
|
1865 | could be rewritten to use it (patches welcome). | |
1867 |
|
1866 | |||
1868 | Some examples: |
|
1867 | Some examples: | |
1869 |
|
1868 | |||
1870 | In [1]: time 2**128 |
|
1869 | In [1]: time 2**128 | |
1871 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1870 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1872 | Wall time: 0.00 |
|
1871 | Wall time: 0.00 | |
1873 | Out[1]: 340282366920938463463374607431768211456L |
|
1872 | Out[1]: 340282366920938463463374607431768211456L | |
1874 |
|
1873 | |||
1875 | In [2]: n = 1000000 |
|
1874 | In [2]: n = 1000000 | |
1876 |
|
1875 | |||
1877 | In [3]: time sum(range(n)) |
|
1876 | In [3]: time sum(range(n)) | |
1878 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1877 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
1879 | Wall time: 1.37 |
|
1878 | Wall time: 1.37 | |
1880 | Out[3]: 499999500000L |
|
1879 | Out[3]: 499999500000L | |
1881 |
|
1880 | |||
1882 | In [4]: time print 'hello world' |
|
1881 | In [4]: time print 'hello world' | |
1883 | hello world |
|
1882 | hello world | |
1884 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1883 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1885 | Wall time: 0.00 |
|
1884 | Wall time: 0.00 | |
1886 |
|
1885 | |||
1887 | Note that the time needed by Python to compile the given expression |
|
1886 | Note that the time needed by Python to compile the given expression | |
1888 | will be reported if it is more than 0.1s. In this example, the |
|
1887 | will be reported if it is more than 0.1s. In this example, the | |
1889 | actual exponentiation is done by Python at compilation time, so while |
|
1888 | actual exponentiation is done by Python at compilation time, so while | |
1890 | the expression can take a noticeable amount of time to compute, that |
|
1889 | the expression can take a noticeable amount of time to compute, that | |
1891 | time is purely due to the compilation: |
|
1890 | time is purely due to the compilation: | |
1892 |
|
1891 | |||
1893 | In [5]: time 3**9999; |
|
1892 | In [5]: time 3**9999; | |
1894 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1893 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1895 | Wall time: 0.00 s |
|
1894 | Wall time: 0.00 s | |
1896 |
|
1895 | |||
1897 | In [6]: time 3**999999; |
|
1896 | In [6]: time 3**999999; | |
1898 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1897 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1899 | Wall time: 0.00 s |
|
1898 | Wall time: 0.00 s | |
1900 | Compiler : 0.78 s |
|
1899 | Compiler : 0.78 s | |
1901 | """ |
|
1900 | """ | |
1902 |
|
1901 | |||
1903 | # fail immediately if the given expression can't be compiled |
|
1902 | # fail immediately if the given expression can't be compiled | |
1904 |
|
1903 | |||
1905 | expr = self.shell.prefilter(parameter_s,False) |
|
1904 | expr = self.shell.prefilter(parameter_s,False) | |
1906 |
|
1905 | |||
1907 | # Minimum time above which compilation time will be reported |
|
1906 | # Minimum time above which compilation time will be reported | |
1908 | tc_min = 0.1 |
|
1907 | tc_min = 0.1 | |
1909 |
|
1908 | |||
1910 | try: |
|
1909 | try: | |
1911 | mode = 'eval' |
|
1910 | mode = 'eval' | |
1912 | t0 = clock() |
|
1911 | t0 = clock() | |
1913 | code = compile(expr,'<timed eval>',mode) |
|
1912 | code = compile(expr,'<timed eval>',mode) | |
1914 | tc = clock()-t0 |
|
1913 | tc = clock()-t0 | |
1915 | except SyntaxError: |
|
1914 | except SyntaxError: | |
1916 | mode = 'exec' |
|
1915 | mode = 'exec' | |
1917 | t0 = clock() |
|
1916 | t0 = clock() | |
1918 | code = compile(expr,'<timed exec>',mode) |
|
1917 | code = compile(expr,'<timed exec>',mode) | |
1919 | tc = clock()-t0 |
|
1918 | tc = clock()-t0 | |
1920 | # skew measurement as little as possible |
|
1919 | # skew measurement as little as possible | |
1921 | glob = self.shell.user_ns |
|
1920 | glob = self.shell.user_ns | |
1922 | clk = clock2 |
|
1921 | clk = clock2 | |
1923 | wtime = time.time |
|
1922 | wtime = time.time | |
1924 | # time execution |
|
1923 | # time execution | |
1925 | wall_st = wtime() |
|
1924 | wall_st = wtime() | |
1926 | if mode=='eval': |
|
1925 | if mode=='eval': | |
1927 | st = clk() |
|
1926 | st = clk() | |
1928 | out = eval(code,glob) |
|
1927 | out = eval(code,glob) | |
1929 | end = clk() |
|
1928 | end = clk() | |
1930 | else: |
|
1929 | else: | |
1931 | st = clk() |
|
1930 | st = clk() | |
1932 | exec code in glob |
|
1931 | exec code in glob | |
1933 | end = clk() |
|
1932 | end = clk() | |
1934 | out = None |
|
1933 | out = None | |
1935 | wall_end = wtime() |
|
1934 | wall_end = wtime() | |
1936 | # Compute actual times and report |
|
1935 | # Compute actual times and report | |
1937 | wall_time = wall_end-wall_st |
|
1936 | wall_time = wall_end-wall_st | |
1938 | cpu_user = end[0]-st[0] |
|
1937 | cpu_user = end[0]-st[0] | |
1939 | cpu_sys = end[1]-st[1] |
|
1938 | cpu_sys = end[1]-st[1] | |
1940 | cpu_tot = cpu_user+cpu_sys |
|
1939 | cpu_tot = cpu_user+cpu_sys | |
1941 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1940 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ | |
1942 | (cpu_user,cpu_sys,cpu_tot) |
|
1941 | (cpu_user,cpu_sys,cpu_tot) | |
1943 | print "Wall time: %.2f s" % wall_time |
|
1942 | print "Wall time: %.2f s" % wall_time | |
1944 | if tc > tc_min: |
|
1943 | if tc > tc_min: | |
1945 | print "Compiler : %.2f s" % tc |
|
1944 | print "Compiler : %.2f s" % tc | |
1946 | return out |
|
1945 | return out | |
1947 |
|
1946 | |||
1948 | @testdec.skip_doctest |
|
1947 | @testdec.skip_doctest | |
1949 | def magic_macro(self,parameter_s = ''): |
|
1948 | def magic_macro(self,parameter_s = ''): | |
1950 | """Define a set of input lines as a macro for future re-execution. |
|
1949 | """Define a set of input lines as a macro for future re-execution. | |
1951 |
|
1950 | |||
1952 | Usage:\\ |
|
1951 | Usage:\\ | |
1953 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1952 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... | |
1954 |
|
1953 | |||
1955 | Options: |
|
1954 | Options: | |
1956 |
|
1955 | |||
1957 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1956 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1958 | so that magics are loaded in their transformed version to valid |
|
1957 | so that magics are loaded in their transformed version to valid | |
1959 | Python. If this option is given, the raw input as typed as the |
|
1958 | Python. If this option is given, the raw input as typed as the | |
1960 | command line is used instead. |
|
1959 | command line is used instead. | |
1961 |
|
1960 | |||
1962 | This will define a global variable called `name` which is a string |
|
1961 | This will define a global variable called `name` which is a string | |
1963 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1962 | made of joining the slices and lines you specify (n1,n2,... numbers | |
1964 | above) from your input history into a single string. This variable |
|
1963 | above) from your input history into a single string. This variable | |
1965 | acts like an automatic function which re-executes those lines as if |
|
1964 | acts like an automatic function which re-executes those lines as if | |
1966 | you had typed them. You just type 'name' at the prompt and the code |
|
1965 | you had typed them. You just type 'name' at the prompt and the code | |
1967 | executes. |
|
1966 | executes. | |
1968 |
|
1967 | |||
1969 | The notation for indicating number ranges is: n1-n2 means 'use line |
|
1968 | The notation for indicating number ranges is: n1-n2 means 'use line | |
1970 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means |
|
1969 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means | |
1971 | using the lines numbered 5,6 and 7. |
|
1970 | using the lines numbered 5,6 and 7. | |
1972 |
|
1971 | |||
1973 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1972 | Note: as a 'hidden' feature, you can also use traditional python slice | |
1974 | notation, where N:M means numbers N through M-1. |
|
1973 | notation, where N:M means numbers N through M-1. | |
1975 |
|
1974 | |||
1976 | For example, if your history contains (%hist prints it): |
|
1975 | For example, if your history contains (%hist prints it): | |
1977 |
|
1976 | |||
1978 | 44: x=1 |
|
1977 | 44: x=1 | |
1979 | 45: y=3 |
|
1978 | 45: y=3 | |
1980 | 46: z=x+y |
|
1979 | 46: z=x+y | |
1981 | 47: print x |
|
1980 | 47: print x | |
1982 | 48: a=5 |
|
1981 | 48: a=5 | |
1983 | 49: print 'x',x,'y',y |
|
1982 | 49: print 'x',x,'y',y | |
1984 |
|
1983 | |||
1985 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1984 | you can create a macro with lines 44 through 47 (included) and line 49 | |
1986 | called my_macro with: |
|
1985 | called my_macro with: | |
1987 |
|
1986 | |||
1988 | In [55]: %macro my_macro 44-47 49 |
|
1987 | In [55]: %macro my_macro 44-47 49 | |
1989 |
|
1988 | |||
1990 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1989 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
1991 | in one pass. |
|
1990 | in one pass. | |
1992 |
|
1991 | |||
1993 | You don't need to give the line-numbers in order, and any given line |
|
1992 | You don't need to give the line-numbers in order, and any given line | |
1994 | number can appear multiple times. You can assemble macros with any |
|
1993 | number can appear multiple times. You can assemble macros with any | |
1995 | lines from your input history in any order. |
|
1994 | lines from your input history in any order. | |
1996 |
|
1995 | |||
1997 | The macro is a simple object which holds its value in an attribute, |
|
1996 | The macro is a simple object which holds its value in an attribute, | |
1998 | but IPython's display system checks for macros and executes them as |
|
1997 | but IPython's display system checks for macros and executes them as | |
1999 | code instead of printing them when you type their name. |
|
1998 | code instead of printing them when you type their name. | |
2000 |
|
1999 | |||
2001 | You can view a macro's contents by explicitly printing it with: |
|
2000 | You can view a macro's contents by explicitly printing it with: | |
2002 |
|
2001 | |||
2003 | 'print macro_name'. |
|
2002 | 'print macro_name'. | |
2004 |
|
2003 | |||
2005 | For one-off cases which DON'T contain magic function calls in them you |
|
2004 | For one-off cases which DON'T contain magic function calls in them you | |
2006 | can obtain similar results by explicitly executing slices from your |
|
2005 | can obtain similar results by explicitly executing slices from your | |
2007 | input history with: |
|
2006 | input history with: | |
2008 |
|
2007 | |||
2009 | In [60]: exec In[44:48]+In[49]""" |
|
2008 | In [60]: exec In[44:48]+In[49]""" | |
2010 |
|
2009 | |||
2011 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2010 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2012 | if not args: |
|
2011 | if not args: | |
2013 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] |
|
2012 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] | |
2014 | macs.sort() |
|
2013 | macs.sort() | |
2015 | return macs |
|
2014 | return macs | |
2016 | if len(args) == 1: |
|
2015 | if len(args) == 1: | |
2017 | raise UsageError( |
|
2016 | raise UsageError( | |
2018 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
2017 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") | |
2019 | name,ranges = args[0], args[1:] |
|
2018 | name,ranges = args[0], args[1:] | |
2020 |
|
2019 | |||
2021 | #print 'rng',ranges # dbg |
|
2020 | #print 'rng',ranges # dbg | |
2022 | lines = self.extract_input_slices(ranges,opts.has_key('r')) |
|
2021 | lines = self.extract_input_slices(ranges,opts.has_key('r')) | |
2023 | macro = Macro(lines) |
|
2022 | macro = Macro(lines) | |
2024 | self.shell.user_ns.update({name:macro}) |
|
2023 | self.shell.user_ns.update({name:macro}) | |
2025 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
2024 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name | |
2026 | print 'Macro contents:' |
|
2025 | print 'Macro contents:' | |
2027 | print macro, |
|
2026 | print macro, | |
2028 |
|
2027 | |||
2029 | def magic_save(self,parameter_s = ''): |
|
2028 | def magic_save(self,parameter_s = ''): | |
2030 | """Save a set of lines to a given filename. |
|
2029 | """Save a set of lines to a given filename. | |
2031 |
|
2030 | |||
2032 | Usage:\\ |
|
2031 | Usage:\\ | |
2033 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
2032 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... | |
2034 |
|
2033 | |||
2035 | Options: |
|
2034 | Options: | |
2036 |
|
2035 | |||
2037 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
2036 | -r: use 'raw' input. By default, the 'processed' history is used, | |
2038 | so that magics are loaded in their transformed version to valid |
|
2037 | so that magics are loaded in their transformed version to valid | |
2039 | Python. If this option is given, the raw input as typed as the |
|
2038 | Python. If this option is given, the raw input as typed as the | |
2040 | command line is used instead. |
|
2039 | command line is used instead. | |
2041 |
|
2040 | |||
2042 | This function uses the same syntax as %macro for line extraction, but |
|
2041 | This function uses the same syntax as %macro for line extraction, but | |
2043 | instead of creating a macro it saves the resulting string to the |
|
2042 | instead of creating a macro it saves the resulting string to the | |
2044 | filename you specify. |
|
2043 | filename you specify. | |
2045 |
|
2044 | |||
2046 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
2045 | It adds a '.py' extension to the file if you don't do so yourself, and | |
2047 | it asks for confirmation before overwriting existing files.""" |
|
2046 | it asks for confirmation before overwriting existing files.""" | |
2048 |
|
2047 | |||
2049 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2048 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2050 | fname,ranges = args[0], args[1:] |
|
2049 | fname,ranges = args[0], args[1:] | |
2051 | if not fname.endswith('.py'): |
|
2050 | if not fname.endswith('.py'): | |
2052 | fname += '.py' |
|
2051 | fname += '.py' | |
2053 | if os.path.isfile(fname): |
|
2052 | if os.path.isfile(fname): | |
2054 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
2053 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) | |
2055 | if ans.lower() not in ['y','yes']: |
|
2054 | if ans.lower() not in ['y','yes']: | |
2056 | print 'Operation cancelled.' |
|
2055 | print 'Operation cancelled.' | |
2057 | return |
|
2056 | return | |
2058 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) |
|
2057 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) | |
2059 | f = file(fname,'w') |
|
2058 | f = file(fname,'w') | |
2060 | f.write(cmds) |
|
2059 | f.write(cmds) | |
2061 | f.close() |
|
2060 | f.close() | |
2062 | print 'The following commands were written to file `%s`:' % fname |
|
2061 | print 'The following commands were written to file `%s`:' % fname | |
2063 | print cmds |
|
2062 | print cmds | |
2064 |
|
2063 | |||
2065 | def _edit_macro(self,mname,macro): |
|
2064 | def _edit_macro(self,mname,macro): | |
2066 | """open an editor with the macro data in a file""" |
|
2065 | """open an editor with the macro data in a file""" | |
2067 | filename = self.shell.mktempfile(macro.value) |
|
2066 | filename = self.shell.mktempfile(macro.value) | |
2068 | self.shell.hooks.editor(filename) |
|
2067 | self.shell.hooks.editor(filename) | |
2069 |
|
2068 | |||
2070 | # and make a new macro object, to replace the old one |
|
2069 | # and make a new macro object, to replace the old one | |
2071 | mfile = open(filename) |
|
2070 | mfile = open(filename) | |
2072 | mvalue = mfile.read() |
|
2071 | mvalue = mfile.read() | |
2073 | mfile.close() |
|
2072 | mfile.close() | |
2074 | self.shell.user_ns[mname] = Macro(mvalue) |
|
2073 | self.shell.user_ns[mname] = Macro(mvalue) | |
2075 |
|
2074 | |||
2076 | def magic_ed(self,parameter_s=''): |
|
2075 | def magic_ed(self,parameter_s=''): | |
2077 | """Alias to %edit.""" |
|
2076 | """Alias to %edit.""" | |
2078 | return self.magic_edit(parameter_s) |
|
2077 | return self.magic_edit(parameter_s) | |
2079 |
|
2078 | |||
2080 | @testdec.skip_doctest |
|
2079 | @testdec.skip_doctest | |
2081 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
2080 | def magic_edit(self,parameter_s='',last_call=['','']): | |
2082 | """Bring up an editor and execute the resulting code. |
|
2081 | """Bring up an editor and execute the resulting code. | |
2083 |
|
2082 | |||
2084 | Usage: |
|
2083 | Usage: | |
2085 | %edit [options] [args] |
|
2084 | %edit [options] [args] | |
2086 |
|
2085 | |||
2087 | %edit runs IPython's editor hook. The default version of this hook is |
|
2086 | %edit runs IPython's editor hook. The default version of this hook is | |
2088 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
2087 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
2089 | environment variable $EDITOR. If this isn't found, it will default to |
|
2088 | environment variable $EDITOR. If this isn't found, it will default to | |
2090 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
2089 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
2091 | docstring for how to change the editor hook. |
|
2090 | docstring for how to change the editor hook. | |
2092 |
|
2091 | |||
2093 | You can also set the value of this editor via the command line option |
|
2092 | You can also set the value of this editor via the command line option | |
2094 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
2093 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
2095 | specifically for IPython an editor different from your typical default |
|
2094 | specifically for IPython an editor different from your typical default | |
2096 | (and for Windows users who typically don't set environment variables). |
|
2095 | (and for Windows users who typically don't set environment variables). | |
2097 |
|
2096 | |||
2098 | This command allows you to conveniently edit multi-line code right in |
|
2097 | This command allows you to conveniently edit multi-line code right in | |
2099 | your IPython session. |
|
2098 | your IPython session. | |
2100 |
|
2099 | |||
2101 | If called without arguments, %edit opens up an empty editor with a |
|
2100 | If called without arguments, %edit opens up an empty editor with a | |
2102 | temporary file and will execute the contents of this file when you |
|
2101 | temporary file and will execute the contents of this file when you | |
2103 | close it (don't forget to save it!). |
|
2102 | close it (don't forget to save it!). | |
2104 |
|
2103 | |||
2105 |
|
2104 | |||
2106 | Options: |
|
2105 | Options: | |
2107 |
|
2106 | |||
2108 | -n <number>: open the editor at a specified line number. By default, |
|
2107 | -n <number>: open the editor at a specified line number. By default, | |
2109 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2108 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
2110 | you can configure this by providing your own modified hook if your |
|
2109 | you can configure this by providing your own modified hook if your | |
2111 | favorite editor supports line-number specifications with a different |
|
2110 | favorite editor supports line-number specifications with a different | |
2112 | syntax. |
|
2111 | syntax. | |
2113 |
|
2112 | |||
2114 | -p: this will call the editor with the same data as the previous time |
|
2113 | -p: this will call the editor with the same data as the previous time | |
2115 | it was used, regardless of how long ago (in your current session) it |
|
2114 | it was used, regardless of how long ago (in your current session) it | |
2116 | was. |
|
2115 | was. | |
2117 |
|
2116 | |||
2118 | -r: use 'raw' input. This option only applies to input taken from the |
|
2117 | -r: use 'raw' input. This option only applies to input taken from the | |
2119 | user's history. By default, the 'processed' history is used, so that |
|
2118 | user's history. By default, the 'processed' history is used, so that | |
2120 | magics are loaded in their transformed version to valid Python. If |
|
2119 | magics are loaded in their transformed version to valid Python. If | |
2121 | this option is given, the raw input as typed as the command line is |
|
2120 | this option is given, the raw input as typed as the command line is | |
2122 | used instead. When you exit the editor, it will be executed by |
|
2121 | used instead. When you exit the editor, it will be executed by | |
2123 | IPython's own processor. |
|
2122 | IPython's own processor. | |
2124 |
|
2123 | |||
2125 | -x: do not execute the edited code immediately upon exit. This is |
|
2124 | -x: do not execute the edited code immediately upon exit. This is | |
2126 | mainly useful if you are editing programs which need to be called with |
|
2125 | mainly useful if you are editing programs which need to be called with | |
2127 | command line arguments, which you can then do using %run. |
|
2126 | command line arguments, which you can then do using %run. | |
2128 |
|
2127 | |||
2129 |
|
2128 | |||
2130 | Arguments: |
|
2129 | Arguments: | |
2131 |
|
2130 | |||
2132 | If arguments are given, the following possibilites exist: |
|
2131 | If arguments are given, the following possibilites exist: | |
2133 |
|
2132 | |||
2134 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
2133 | - The arguments are numbers or pairs of colon-separated numbers (like | |
2135 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
2134 | 1 4:8 9). These are interpreted as lines of previous input to be | |
2136 | loaded into the editor. The syntax is the same of the %macro command. |
|
2135 | loaded into the editor. The syntax is the same of the %macro command. | |
2137 |
|
2136 | |||
2138 | - If the argument doesn't start with a number, it is evaluated as a |
|
2137 | - If the argument doesn't start with a number, it is evaluated as a | |
2139 | variable and its contents loaded into the editor. You can thus edit |
|
2138 | variable and its contents loaded into the editor. You can thus edit | |
2140 | any string which contains python code (including the result of |
|
2139 | any string which contains python code (including the result of | |
2141 | previous edits). |
|
2140 | previous edits). | |
2142 |
|
2141 | |||
2143 | - If the argument is the name of an object (other than a string), |
|
2142 | - If the argument is the name of an object (other than a string), | |
2144 | IPython will try to locate the file where it was defined and open the |
|
2143 | IPython will try to locate the file where it was defined and open the | |
2145 | editor at the point where it is defined. You can use `%edit function` |
|
2144 | editor at the point where it is defined. You can use `%edit function` | |
2146 | to load an editor exactly at the point where 'function' is defined, |
|
2145 | to load an editor exactly at the point where 'function' is defined, | |
2147 | edit it and have the file be executed automatically. |
|
2146 | edit it and have the file be executed automatically. | |
2148 |
|
2147 | |||
2149 | If the object is a macro (see %macro for details), this opens up your |
|
2148 | If the object is a macro (see %macro for details), this opens up your | |
2150 | specified editor with a temporary file containing the macro's data. |
|
2149 | specified editor with a temporary file containing the macro's data. | |
2151 | Upon exit, the macro is reloaded with the contents of the file. |
|
2150 | Upon exit, the macro is reloaded with the contents of the file. | |
2152 |
|
2151 | |||
2153 | Note: opening at an exact line is only supported under Unix, and some |
|
2152 | Note: opening at an exact line is only supported under Unix, and some | |
2154 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2153 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
2155 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2154 | '+NUMBER' parameter necessary for this feature. Good editors like | |
2156 | (X)Emacs, vi, jed, pico and joe all do. |
|
2155 | (X)Emacs, vi, jed, pico and joe all do. | |
2157 |
|
2156 | |||
2158 | - If the argument is not found as a variable, IPython will look for a |
|
2157 | - If the argument is not found as a variable, IPython will look for a | |
2159 | file with that name (adding .py if necessary) and load it into the |
|
2158 | file with that name (adding .py if necessary) and load it into the | |
2160 | editor. It will execute its contents with execfile() when you exit, |
|
2159 | editor. It will execute its contents with execfile() when you exit, | |
2161 | loading any code in the file into your interactive namespace. |
|
2160 | loading any code in the file into your interactive namespace. | |
2162 |
|
2161 | |||
2163 | After executing your code, %edit will return as output the code you |
|
2162 | After executing your code, %edit will return as output the code you | |
2164 | typed in the editor (except when it was an existing file). This way |
|
2163 | typed in the editor (except when it was an existing file). This way | |
2165 | you can reload the code in further invocations of %edit as a variable, |
|
2164 | you can reload the code in further invocations of %edit as a variable, | |
2166 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2165 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
2167 | the output. |
|
2166 | the output. | |
2168 |
|
2167 | |||
2169 | Note that %edit is also available through the alias %ed. |
|
2168 | Note that %edit is also available through the alias %ed. | |
2170 |
|
2169 | |||
2171 | This is an example of creating a simple function inside the editor and |
|
2170 | This is an example of creating a simple function inside the editor and | |
2172 | then modifying it. First, start up the editor: |
|
2171 | then modifying it. First, start up the editor: | |
2173 |
|
2172 | |||
2174 | In [1]: ed |
|
2173 | In [1]: ed | |
2175 | Editing... done. Executing edited code... |
|
2174 | Editing... done. Executing edited code... | |
2176 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
2175 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' | |
2177 |
|
2176 | |||
2178 | We can then call the function foo(): |
|
2177 | We can then call the function foo(): | |
2179 |
|
2178 | |||
2180 | In [2]: foo() |
|
2179 | In [2]: foo() | |
2181 | foo() was defined in an editing session |
|
2180 | foo() was defined in an editing session | |
2182 |
|
2181 | |||
2183 | Now we edit foo. IPython automatically loads the editor with the |
|
2182 | Now we edit foo. IPython automatically loads the editor with the | |
2184 | (temporary) file where foo() was previously defined: |
|
2183 | (temporary) file where foo() was previously defined: | |
2185 |
|
2184 | |||
2186 | In [3]: ed foo |
|
2185 | In [3]: ed foo | |
2187 | Editing... done. Executing edited code... |
|
2186 | Editing... done. Executing edited code... | |
2188 |
|
2187 | |||
2189 | And if we call foo() again we get the modified version: |
|
2188 | And if we call foo() again we get the modified version: | |
2190 |
|
2189 | |||
2191 | In [4]: foo() |
|
2190 | In [4]: foo() | |
2192 | foo() has now been changed! |
|
2191 | foo() has now been changed! | |
2193 |
|
2192 | |||
2194 | Here is an example of how to edit a code snippet successive |
|
2193 | Here is an example of how to edit a code snippet successive | |
2195 | times. First we call the editor: |
|
2194 | times. First we call the editor: | |
2196 |
|
2195 | |||
2197 | In [5]: ed |
|
2196 | In [5]: ed | |
2198 | Editing... done. Executing edited code... |
|
2197 | Editing... done. Executing edited code... | |
2199 | hello |
|
2198 | hello | |
2200 | Out[5]: "print 'hello'n" |
|
2199 | Out[5]: "print 'hello'n" | |
2201 |
|
2200 | |||
2202 | Now we call it again with the previous output (stored in _): |
|
2201 | Now we call it again with the previous output (stored in _): | |
2203 |
|
2202 | |||
2204 | In [6]: ed _ |
|
2203 | In [6]: ed _ | |
2205 | Editing... done. Executing edited code... |
|
2204 | Editing... done. Executing edited code... | |
2206 | hello world |
|
2205 | hello world | |
2207 | Out[6]: "print 'hello world'n" |
|
2206 | Out[6]: "print 'hello world'n" | |
2208 |
|
2207 | |||
2209 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2208 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
2210 |
|
2209 | |||
2211 | In [7]: ed _8 |
|
2210 | In [7]: ed _8 | |
2212 | Editing... done. Executing edited code... |
|
2211 | Editing... done. Executing edited code... | |
2213 | hello again |
|
2212 | hello again | |
2214 | Out[7]: "print 'hello again'n" |
|
2213 | Out[7]: "print 'hello again'n" | |
2215 |
|
2214 | |||
2216 |
|
2215 | |||
2217 | Changing the default editor hook: |
|
2216 | Changing the default editor hook: | |
2218 |
|
2217 | |||
2219 | If you wish to write your own editor hook, you can put it in a |
|
2218 | If you wish to write your own editor hook, you can put it in a | |
2220 | configuration file which you load at startup time. The default hook |
|
2219 | configuration file which you load at startup time. The default hook | |
2221 | is defined in the IPython.hooks module, and you can use that as a |
|
2220 | is defined in the IPython.hooks module, and you can use that as a | |
2222 | starting example for further modifications. That file also has |
|
2221 | starting example for further modifications. That file also has | |
2223 | general instructions on how to set a new hook for use once you've |
|
2222 | general instructions on how to set a new hook for use once you've | |
2224 | defined it.""" |
|
2223 | defined it.""" | |
2225 |
|
2224 | |||
2226 | # FIXME: This function has become a convoluted mess. It needs a |
|
2225 | # FIXME: This function has become a convoluted mess. It needs a | |
2227 | # ground-up rewrite with clean, simple logic. |
|
2226 | # ground-up rewrite with clean, simple logic. | |
2228 |
|
2227 | |||
2229 | def make_filename(arg): |
|
2228 | def make_filename(arg): | |
2230 | "Make a filename from the given args" |
|
2229 | "Make a filename from the given args" | |
2231 | try: |
|
2230 | try: | |
2232 | filename = get_py_filename(arg) |
|
2231 | filename = get_py_filename(arg) | |
2233 | except IOError: |
|
2232 | except IOError: | |
2234 | if args.endswith('.py'): |
|
2233 | if args.endswith('.py'): | |
2235 | filename = arg |
|
2234 | filename = arg | |
2236 | else: |
|
2235 | else: | |
2237 | filename = None |
|
2236 | filename = None | |
2238 | return filename |
|
2237 | return filename | |
2239 |
|
2238 | |||
2240 | # custom exceptions |
|
2239 | # custom exceptions | |
2241 | class DataIsObject(Exception): pass |
|
2240 | class DataIsObject(Exception): pass | |
2242 |
|
2241 | |||
2243 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2242 | opts,args = self.parse_options(parameter_s,'prxn:') | |
2244 | # Set a few locals from the options for convenience: |
|
2243 | # Set a few locals from the options for convenience: | |
2245 | opts_p = opts.has_key('p') |
|
2244 | opts_p = opts.has_key('p') | |
2246 | opts_r = opts.has_key('r') |
|
2245 | opts_r = opts.has_key('r') | |
2247 |
|
2246 | |||
2248 | # Default line number value |
|
2247 | # Default line number value | |
2249 | lineno = opts.get('n',None) |
|
2248 | lineno = opts.get('n',None) | |
2250 |
|
2249 | |||
2251 | if opts_p: |
|
2250 | if opts_p: | |
2252 | args = '_%s' % last_call[0] |
|
2251 | args = '_%s' % last_call[0] | |
2253 | if not self.shell.user_ns.has_key(args): |
|
2252 | if not self.shell.user_ns.has_key(args): | |
2254 | args = last_call[1] |
|
2253 | args = last_call[1] | |
2255 |
|
2254 | |||
2256 | # use last_call to remember the state of the previous call, but don't |
|
2255 | # use last_call to remember the state of the previous call, but don't | |
2257 | # let it be clobbered by successive '-p' calls. |
|
2256 | # let it be clobbered by successive '-p' calls. | |
2258 | try: |
|
2257 | try: | |
2259 | last_call[0] = self.shell.outputcache.prompt_count |
|
2258 | last_call[0] = self.shell.outputcache.prompt_count | |
2260 | if not opts_p: |
|
2259 | if not opts_p: | |
2261 | last_call[1] = parameter_s |
|
2260 | last_call[1] = parameter_s | |
2262 | except: |
|
2261 | except: | |
2263 | pass |
|
2262 | pass | |
2264 |
|
2263 | |||
2265 | # by default this is done with temp files, except when the given |
|
2264 | # by default this is done with temp files, except when the given | |
2266 | # arg is a filename |
|
2265 | # arg is a filename | |
2267 | use_temp = 1 |
|
2266 | use_temp = 1 | |
2268 |
|
2267 | |||
2269 | if re.match(r'\d',args): |
|
2268 | if re.match(r'\d',args): | |
2270 | # Mode where user specifies ranges of lines, like in %macro. |
|
2269 | # Mode where user specifies ranges of lines, like in %macro. | |
2271 | # This means that you can't edit files whose names begin with |
|
2270 | # This means that you can't edit files whose names begin with | |
2272 | # numbers this way. Tough. |
|
2271 | # numbers this way. Tough. | |
2273 | ranges = args.split() |
|
2272 | ranges = args.split() | |
2274 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
2273 | data = ''.join(self.extract_input_slices(ranges,opts_r)) | |
2275 | elif args.endswith('.py'): |
|
2274 | elif args.endswith('.py'): | |
2276 | filename = make_filename(args) |
|
2275 | filename = make_filename(args) | |
2277 | data = '' |
|
2276 | data = '' | |
2278 | use_temp = 0 |
|
2277 | use_temp = 0 | |
2279 | elif args: |
|
2278 | elif args: | |
2280 | try: |
|
2279 | try: | |
2281 | # Load the parameter given as a variable. If not a string, |
|
2280 | # Load the parameter given as a variable. If not a string, | |
2282 | # process it as an object instead (below) |
|
2281 | # process it as an object instead (below) | |
2283 |
|
2282 | |||
2284 | #print '*** args',args,'type',type(args) # dbg |
|
2283 | #print '*** args',args,'type',type(args) # dbg | |
2285 | data = eval(args,self.shell.user_ns) |
|
2284 | data = eval(args,self.shell.user_ns) | |
2286 | if not type(data) in StringTypes: |
|
2285 | if not type(data) in StringTypes: | |
2287 | raise DataIsObject |
|
2286 | raise DataIsObject | |
2288 |
|
2287 | |||
2289 | except (NameError,SyntaxError): |
|
2288 | except (NameError,SyntaxError): | |
2290 | # given argument is not a variable, try as a filename |
|
2289 | # given argument is not a variable, try as a filename | |
2291 | filename = make_filename(args) |
|
2290 | filename = make_filename(args) | |
2292 | if filename is None: |
|
2291 | if filename is None: | |
2293 | warn("Argument given (%s) can't be found as a variable " |
|
2292 | warn("Argument given (%s) can't be found as a variable " | |
2294 | "or as a filename." % args) |
|
2293 | "or as a filename." % args) | |
2295 | return |
|
2294 | return | |
2296 |
|
2295 | |||
2297 | data = '' |
|
2296 | data = '' | |
2298 | use_temp = 0 |
|
2297 | use_temp = 0 | |
2299 | except DataIsObject: |
|
2298 | except DataIsObject: | |
2300 |
|
2299 | |||
2301 | # macros have a special edit function |
|
2300 | # macros have a special edit function | |
2302 | if isinstance(data,Macro): |
|
2301 | if isinstance(data,Macro): | |
2303 | self._edit_macro(args,data) |
|
2302 | self._edit_macro(args,data) | |
2304 | return |
|
2303 | return | |
2305 |
|
2304 | |||
2306 | # For objects, try to edit the file where they are defined |
|
2305 | # For objects, try to edit the file where they are defined | |
2307 | try: |
|
2306 | try: | |
2308 | filename = inspect.getabsfile(data) |
|
2307 | filename = inspect.getabsfile(data) | |
2309 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
2308 | if 'fakemodule' in filename.lower() and inspect.isclass(data): | |
2310 | # class created by %edit? Try to find source |
|
2309 | # class created by %edit? Try to find source | |
2311 | # by looking for method definitions instead, the |
|
2310 | # by looking for method definitions instead, the | |
2312 | # __module__ in those classes is FakeModule. |
|
2311 | # __module__ in those classes is FakeModule. | |
2313 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
2312 | attrs = [getattr(data, aname) for aname in dir(data)] | |
2314 | for attr in attrs: |
|
2313 | for attr in attrs: | |
2315 | if not inspect.ismethod(attr): |
|
2314 | if not inspect.ismethod(attr): | |
2316 | continue |
|
2315 | continue | |
2317 | filename = inspect.getabsfile(attr) |
|
2316 | filename = inspect.getabsfile(attr) | |
2318 | if filename and 'fakemodule' not in filename.lower(): |
|
2317 | if filename and 'fakemodule' not in filename.lower(): | |
2319 | # change the attribute to be the edit target instead |
|
2318 | # change the attribute to be the edit target instead | |
2320 | data = attr |
|
2319 | data = attr | |
2321 | break |
|
2320 | break | |
2322 |
|
2321 | |||
2323 | datafile = 1 |
|
2322 | datafile = 1 | |
2324 | except TypeError: |
|
2323 | except TypeError: | |
2325 | filename = make_filename(args) |
|
2324 | filename = make_filename(args) | |
2326 | datafile = 1 |
|
2325 | datafile = 1 | |
2327 | warn('Could not find file where `%s` is defined.\n' |
|
2326 | warn('Could not find file where `%s` is defined.\n' | |
2328 | 'Opening a file named `%s`' % (args,filename)) |
|
2327 | 'Opening a file named `%s`' % (args,filename)) | |
2329 | # Now, make sure we can actually read the source (if it was in |
|
2328 | # Now, make sure we can actually read the source (if it was in | |
2330 | # a temp file it's gone by now). |
|
2329 | # a temp file it's gone by now). | |
2331 | if datafile: |
|
2330 | if datafile: | |
2332 | try: |
|
2331 | try: | |
2333 | if lineno is None: |
|
2332 | if lineno is None: | |
2334 | lineno = inspect.getsourcelines(data)[1] |
|
2333 | lineno = inspect.getsourcelines(data)[1] | |
2335 | except IOError: |
|
2334 | except IOError: | |
2336 | filename = make_filename(args) |
|
2335 | filename = make_filename(args) | |
2337 | if filename is None: |
|
2336 | if filename is None: | |
2338 | warn('The file `%s` where `%s` was defined cannot ' |
|
2337 | warn('The file `%s` where `%s` was defined cannot ' | |
2339 | 'be read.' % (filename,data)) |
|
2338 | 'be read.' % (filename,data)) | |
2340 | return |
|
2339 | return | |
2341 | use_temp = 0 |
|
2340 | use_temp = 0 | |
2342 | else: |
|
2341 | else: | |
2343 | data = '' |
|
2342 | data = '' | |
2344 |
|
2343 | |||
2345 | if use_temp: |
|
2344 | if use_temp: | |
2346 | filename = self.shell.mktempfile(data) |
|
2345 | filename = self.shell.mktempfile(data) | |
2347 | print 'IPython will make a temporary file named:',filename |
|
2346 | print 'IPython will make a temporary file named:',filename | |
2348 |
|
2347 | |||
2349 | # do actual editing here |
|
2348 | # do actual editing here | |
2350 | print 'Editing...', |
|
2349 | print 'Editing...', | |
2351 | sys.stdout.flush() |
|
2350 | sys.stdout.flush() | |
2352 | self.shell.hooks.editor(filename,lineno) |
|
2351 | self.shell.hooks.editor(filename,lineno) | |
2353 |
|
2352 | |||
2354 | # XXX TODO: should this be generalized for all string vars? |
|
2353 | # XXX TODO: should this be generalized for all string vars? | |
2355 | # For now, this is special-cased to blocks created by cpaste |
|
2354 | # For now, this is special-cased to blocks created by cpaste | |
2356 | if args.strip() == 'pasted_block': |
|
2355 | if args.strip() == 'pasted_block': | |
2357 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
2356 | self.shell.user_ns['pasted_block'] = file_read(filename) | |
2358 |
|
2357 | |||
2359 | if opts.has_key('x'): # -x prevents actual execution |
|
2358 | if opts.has_key('x'): # -x prevents actual execution | |
2360 |
|
2359 | |||
2361 | else: |
|
2360 | else: | |
2362 | print 'done. Executing edited code...' |
|
2361 | print 'done. Executing edited code...' | |
2363 | if opts_r: |
|
2362 | if opts_r: | |
2364 | self.shell.runlines(file_read(filename)) |
|
2363 | self.shell.runlines(file_read(filename)) | |
2365 | else: |
|
2364 | else: | |
2366 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2365 | self.shell.safe_execfile(filename,self.shell.user_ns, | |
2367 | self.shell.user_ns) |
|
2366 | self.shell.user_ns) | |
2368 |
|
2367 | |||
2369 |
|
2368 | |||
2370 | if use_temp: |
|
2369 | if use_temp: | |
2371 | try: |
|
2370 | try: | |
2372 | return open(filename).read() |
|
2371 | return open(filename).read() | |
2373 | except IOError,msg: |
|
2372 | except IOError,msg: | |
2374 | if msg.filename == filename: |
|
2373 | if msg.filename == filename: | |
2375 | warn('File not found. Did you forget to save?') |
|
2374 | warn('File not found. Did you forget to save?') | |
2376 | return |
|
2375 | return | |
2377 | else: |
|
2376 | else: | |
2378 | self.shell.showtraceback() |
|
2377 | self.shell.showtraceback() | |
2379 |
|
2378 | |||
2380 | def magic_xmode(self,parameter_s = ''): |
|
2379 | def magic_xmode(self,parameter_s = ''): | |
2381 | """Switch modes for the exception handlers. |
|
2380 | """Switch modes for the exception handlers. | |
2382 |
|
2381 | |||
2383 | Valid modes: Plain, Context and Verbose. |
|
2382 | Valid modes: Plain, Context and Verbose. | |
2384 |
|
2383 | |||
2385 | If called without arguments, acts as a toggle.""" |
|
2384 | If called without arguments, acts as a toggle.""" | |
2386 |
|
2385 | |||
2387 | def xmode_switch_err(name): |
|
2386 | def xmode_switch_err(name): | |
2388 | warn('Error changing %s exception modes.\n%s' % |
|
2387 | warn('Error changing %s exception modes.\n%s' % | |
2389 | (name,sys.exc_info()[1])) |
|
2388 | (name,sys.exc_info()[1])) | |
2390 |
|
2389 | |||
2391 | shell = self.shell |
|
2390 | shell = self.shell | |
2392 | new_mode = parameter_s.strip().capitalize() |
|
2391 | new_mode = parameter_s.strip().capitalize() | |
2393 | try: |
|
2392 | try: | |
2394 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2393 | shell.InteractiveTB.set_mode(mode=new_mode) | |
2395 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2394 | print 'Exception reporting mode:',shell.InteractiveTB.mode | |
2396 | except: |
|
2395 | except: | |
2397 | xmode_switch_err('user') |
|
2396 | xmode_switch_err('user') | |
2398 |
|
2397 | |||
2399 | # threaded shells use a special handler in sys.excepthook |
|
2398 | # threaded shells use a special handler in sys.excepthook | |
2400 | if shell.isthreaded: |
|
2399 | if shell.isthreaded: | |
2401 | try: |
|
2400 | try: | |
2402 | shell.sys_excepthook.set_mode(mode=new_mode) |
|
2401 | shell.sys_excepthook.set_mode(mode=new_mode) | |
2403 | except: |
|
2402 | except: | |
2404 | xmode_switch_err('threaded') |
|
2403 | xmode_switch_err('threaded') | |
2405 |
|
2404 | |||
2406 | def magic_colors(self,parameter_s = ''): |
|
2405 | def magic_colors(self,parameter_s = ''): | |
2407 | """Switch color scheme for prompts, info system and exception handlers. |
|
2406 | """Switch color scheme for prompts, info system and exception handlers. | |
2408 |
|
2407 | |||
2409 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2408 | Currently implemented schemes: NoColor, Linux, LightBG. | |
2410 |
|
2409 | |||
2411 | Color scheme names are not case-sensitive.""" |
|
2410 | Color scheme names are not case-sensitive.""" | |
2412 |
|
2411 | |||
2413 | def color_switch_err(name): |
|
2412 | def color_switch_err(name): | |
2414 | warn('Error changing %s color schemes.\n%s' % |
|
2413 | warn('Error changing %s color schemes.\n%s' % | |
2415 | (name,sys.exc_info()[1])) |
|
2414 | (name,sys.exc_info()[1])) | |
2416 |
|
2415 | |||
2417 |
|
2416 | |||
2418 | new_scheme = parameter_s.strip() |
|
2417 | new_scheme = parameter_s.strip() | |
2419 | if not new_scheme: |
|
2418 | if not new_scheme: | |
2420 | raise UsageError( |
|
2419 | raise UsageError( | |
2421 | "%colors: you must specify a color scheme. See '%colors?'") |
|
2420 | "%colors: you must specify a color scheme. See '%colors?'") | |
2422 | return |
|
2421 | return | |
2423 | # local shortcut |
|
2422 | # local shortcut | |
2424 | shell = self.shell |
|
2423 | shell = self.shell | |
2425 |
|
2424 | |||
2426 | import IPython.rlineimpl as readline |
|
2425 | import IPython.rlineimpl as readline | |
2427 |
|
2426 | |||
2428 | if not readline.have_readline and sys.platform == "win32": |
|
2427 | if not readline.have_readline and sys.platform == "win32": | |
2429 | msg = """\ |
|
2428 | msg = """\ | |
2430 | Proper color support under MS Windows requires the pyreadline library. |
|
2429 | Proper color support under MS Windows requires the pyreadline library. | |
2431 | You can find it at: |
|
2430 | You can find it at: | |
2432 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2431 | http://ipython.scipy.org/moin/PyReadline/Intro | |
2433 | Gary's readline needs the ctypes module, from: |
|
2432 | Gary's readline needs the ctypes module, from: | |
2434 | http://starship.python.net/crew/theller/ctypes |
|
2433 | http://starship.python.net/crew/theller/ctypes | |
2435 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2434 | (Note that ctypes is already part of Python versions 2.5 and newer). | |
2436 |
|
2435 | |||
2437 | Defaulting color scheme to 'NoColor'""" |
|
2436 | Defaulting color scheme to 'NoColor'""" | |
2438 | new_scheme = 'NoColor' |
|
2437 | new_scheme = 'NoColor' | |
2439 | warn(msg) |
|
2438 | warn(msg) | |
2440 |
|
2439 | |||
2441 | # readline option is 0 |
|
2440 | # readline option is 0 | |
2442 | if not shell.has_readline: |
|
2441 | if not shell.has_readline: | |
2443 | new_scheme = 'NoColor' |
|
2442 | new_scheme = 'NoColor' | |
2444 |
|
2443 | |||
2445 | # Set prompt colors |
|
2444 | # Set prompt colors | |
2446 | try: |
|
2445 | try: | |
2447 | shell.outputcache.set_colors(new_scheme) |
|
2446 | shell.outputcache.set_colors(new_scheme) | |
2448 | except: |
|
2447 | except: | |
2449 | color_switch_err('prompt') |
|
2448 | color_switch_err('prompt') | |
2450 | else: |
|
2449 | else: | |
2451 | shell.rc.colors = \ |
|
2450 | shell.rc.colors = \ | |
2452 | shell.outputcache.color_table.active_scheme_name |
|
2451 | shell.outputcache.color_table.active_scheme_name | |
2453 | # Set exception colors |
|
2452 | # Set exception colors | |
2454 | try: |
|
2453 | try: | |
2455 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2454 | shell.InteractiveTB.set_colors(scheme = new_scheme) | |
2456 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2455 | shell.SyntaxTB.set_colors(scheme = new_scheme) | |
2457 | except: |
|
2456 | except: | |
2458 | color_switch_err('exception') |
|
2457 | color_switch_err('exception') | |
2459 |
|
2458 | |||
2460 | # threaded shells use a verbose traceback in sys.excepthook |
|
2459 | # threaded shells use a verbose traceback in sys.excepthook | |
2461 | if shell.isthreaded: |
|
2460 | if shell.isthreaded: | |
2462 | try: |
|
2461 | try: | |
2463 | shell.sys_excepthook.set_colors(scheme=new_scheme) |
|
2462 | shell.sys_excepthook.set_colors(scheme=new_scheme) | |
2464 | except: |
|
2463 | except: | |
2465 | color_switch_err('system exception handler') |
|
2464 | color_switch_err('system exception handler') | |
2466 |
|
2465 | |||
2467 | # Set info (for 'object?') colors |
|
2466 | # Set info (for 'object?') colors | |
2468 | if shell.rc.color_info: |
|
2467 | if shell.rc.color_info: | |
2469 | try: |
|
2468 | try: | |
2470 | shell.inspector.set_active_scheme(new_scheme) |
|
2469 | shell.inspector.set_active_scheme(new_scheme) | |
2471 | except: |
|
2470 | except: | |
2472 | color_switch_err('object inspector') |
|
2471 | color_switch_err('object inspector') | |
2473 | else: |
|
2472 | else: | |
2474 | shell.inspector.set_active_scheme('NoColor') |
|
2473 | shell.inspector.set_active_scheme('NoColor') | |
2475 |
|
2474 | |||
2476 | def magic_color_info(self,parameter_s = ''): |
|
2475 | def magic_color_info(self,parameter_s = ''): | |
2477 | """Toggle color_info. |
|
2476 | """Toggle color_info. | |
2478 |
|
2477 | |||
2479 | The color_info configuration parameter controls whether colors are |
|
2478 | The color_info configuration parameter controls whether colors are | |
2480 | used for displaying object details (by things like %psource, %pfile or |
|
2479 | used for displaying object details (by things like %psource, %pfile or | |
2481 | the '?' system). This function toggles this value with each call. |
|
2480 | the '?' system). This function toggles this value with each call. | |
2482 |
|
2481 | |||
2483 | Note that unless you have a fairly recent pager (less works better |
|
2482 | Note that unless you have a fairly recent pager (less works better | |
2484 | than more) in your system, using colored object information displays |
|
2483 | than more) in your system, using colored object information displays | |
2485 | will not work properly. Test it and see.""" |
|
2484 | will not work properly. Test it and see.""" | |
2486 |
|
2485 | |||
2487 | self.shell.rc.color_info = 1 - self.shell.rc.color_info |
|
2486 | self.shell.rc.color_info = 1 - self.shell.rc.color_info | |
2488 | self.magic_colors(self.shell.rc.colors) |
|
2487 | self.magic_colors(self.shell.rc.colors) | |
2489 | print 'Object introspection functions have now coloring:', |
|
2488 | print 'Object introspection functions have now coloring:', | |
2490 | print ['OFF','ON'][self.shell.rc.color_info] |
|
2489 | print ['OFF','ON'][self.shell.rc.color_info] | |
2491 |
|
2490 | |||
2492 | def magic_Pprint(self, parameter_s=''): |
|
2491 | def magic_Pprint(self, parameter_s=''): | |
2493 | """Toggle pretty printing on/off.""" |
|
2492 | """Toggle pretty printing on/off.""" | |
2494 |
|
2493 | |||
2495 | self.shell.rc.pprint = 1 - self.shell.rc.pprint |
|
2494 | self.shell.rc.pprint = 1 - self.shell.rc.pprint | |
2496 | print 'Pretty printing has been turned', \ |
|
2495 | print 'Pretty printing has been turned', \ | |
2497 | ['OFF','ON'][self.shell.rc.pprint] |
|
2496 | ['OFF','ON'][self.shell.rc.pprint] | |
2498 |
|
2497 | |||
2499 | def magic_exit(self, parameter_s=''): |
|
2498 | def magic_exit(self, parameter_s=''): | |
2500 | """Exit IPython, confirming if configured to do so. |
|
2499 | """Exit IPython, confirming if configured to do so. | |
2501 |
|
2500 | |||
2502 | You can configure whether IPython asks for confirmation upon exit by |
|
2501 | You can configure whether IPython asks for confirmation upon exit by | |
2503 | setting the confirm_exit flag in the ipythonrc file.""" |
|
2502 | setting the confirm_exit flag in the ipythonrc file.""" | |
2504 |
|
2503 | |||
2505 | self.shell.exit() |
|
2504 | self.shell.exit() | |
2506 |
|
2505 | |||
2507 | def magic_quit(self, parameter_s=''): |
|
2506 | def magic_quit(self, parameter_s=''): | |
2508 | """Exit IPython, confirming if configured to do so (like %exit)""" |
|
2507 | """Exit IPython, confirming if configured to do so (like %exit)""" | |
2509 |
|
2508 | |||
2510 | self.shell.exit() |
|
2509 | self.shell.exit() | |
2511 |
|
2510 | |||
2512 | def magic_Exit(self, parameter_s=''): |
|
2511 | def magic_Exit(self, parameter_s=''): | |
2513 | """Exit IPython without confirmation.""" |
|
2512 | """Exit IPython without confirmation.""" | |
2514 |
|
2513 | |||
2515 | self.shell.ask_exit() |
|
2514 | self.shell.ask_exit() | |
2516 |
|
2515 | |||
2517 | #...................................................................... |
|
2516 | #...................................................................... | |
2518 | # Functions to implement unix shell-type things |
|
2517 | # Functions to implement unix shell-type things | |
2519 |
|
2518 | |||
2520 | @testdec.skip_doctest |
|
2519 | @testdec.skip_doctest | |
2521 | def magic_alias(self, parameter_s = ''): |
|
2520 | def magic_alias(self, parameter_s = ''): | |
2522 | """Define an alias for a system command. |
|
2521 | """Define an alias for a system command. | |
2523 |
|
2522 | |||
2524 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2523 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
2525 |
|
2524 | |||
2526 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2525 | Then, typing 'alias_name params' will execute the system command 'cmd | |
2527 | params' (from your underlying operating system). |
|
2526 | params' (from your underlying operating system). | |
2528 |
|
2527 | |||
2529 | Aliases have lower precedence than magic functions and Python normal |
|
2528 | Aliases have lower precedence than magic functions and Python normal | |
2530 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2529 | variables, so if 'foo' is both a Python variable and an alias, the | |
2531 | alias can not be executed until 'del foo' removes the Python variable. |
|
2530 | alias can not be executed until 'del foo' removes the Python variable. | |
2532 |
|
2531 | |||
2533 | You can use the %l specifier in an alias definition to represent the |
|
2532 | You can use the %l specifier in an alias definition to represent the | |
2534 | whole line when the alias is called. For example: |
|
2533 | whole line when the alias is called. For example: | |
2535 |
|
2534 | |||
2536 | In [2]: alias all echo "Input in brackets: <%l>" |
|
2535 | In [2]: alias all echo "Input in brackets: <%l>" | |
2537 | In [3]: all hello world |
|
2536 | In [3]: all hello world | |
2538 | Input in brackets: <hello world> |
|
2537 | Input in brackets: <hello world> | |
2539 |
|
2538 | |||
2540 | You can also define aliases with parameters using %s specifiers (one |
|
2539 | You can also define aliases with parameters using %s specifiers (one | |
2541 | per parameter): |
|
2540 | per parameter): | |
2542 |
|
2541 | |||
2543 | In [1]: alias parts echo first %s second %s |
|
2542 | In [1]: alias parts echo first %s second %s | |
2544 | In [2]: %parts A B |
|
2543 | In [2]: %parts A B | |
2545 | first A second B |
|
2544 | first A second B | |
2546 | In [3]: %parts A |
|
2545 | In [3]: %parts A | |
2547 | Incorrect number of arguments: 2 expected. |
|
2546 | Incorrect number of arguments: 2 expected. | |
2548 | parts is an alias to: 'echo first %s second %s' |
|
2547 | parts is an alias to: 'echo first %s second %s' | |
2549 |
|
2548 | |||
2550 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2549 | Note that %l and %s are mutually exclusive. You can only use one or | |
2551 | the other in your aliases. |
|
2550 | the other in your aliases. | |
2552 |
|
2551 | |||
2553 | Aliases expand Python variables just like system calls using ! or !! |
|
2552 | Aliases expand Python variables just like system calls using ! or !! | |
2554 | do: all expressions prefixed with '$' get expanded. For details of |
|
2553 | do: all expressions prefixed with '$' get expanded. For details of | |
2555 | the semantic rules, see PEP-215: |
|
2554 | the semantic rules, see PEP-215: | |
2556 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2555 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
2557 | IPython for variable expansion. If you want to access a true shell |
|
2556 | IPython for variable expansion. If you want to access a true shell | |
2558 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2557 | variable, an extra $ is necessary to prevent its expansion by IPython: | |
2559 |
|
2558 | |||
2560 | In [6]: alias show echo |
|
2559 | In [6]: alias show echo | |
2561 | In [7]: PATH='A Python string' |
|
2560 | In [7]: PATH='A Python string' | |
2562 | In [8]: show $PATH |
|
2561 | In [8]: show $PATH | |
2563 | A Python string |
|
2562 | A Python string | |
2564 | In [9]: show $$PATH |
|
2563 | In [9]: show $$PATH | |
2565 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2564 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
2566 |
|
2565 | |||
2567 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2566 | You can use the alias facility to acess all of $PATH. See the %rehash | |
2568 | and %rehashx functions, which automatically create aliases for the |
|
2567 | and %rehashx functions, which automatically create aliases for the | |
2569 | contents of your $PATH. |
|
2568 | contents of your $PATH. | |
2570 |
|
2569 | |||
2571 | If called with no parameters, %alias prints the current alias table.""" |
|
2570 | If called with no parameters, %alias prints the current alias table.""" | |
2572 |
|
2571 | |||
2573 | par = parameter_s.strip() |
|
2572 | par = parameter_s.strip() | |
2574 | if not par: |
|
2573 | if not par: | |
2575 | stored = self.db.get('stored_aliases', {} ) |
|
2574 | stored = self.db.get('stored_aliases', {} ) | |
2576 | atab = self.shell.alias_table |
|
2575 | atab = self.shell.alias_table | |
2577 | aliases = atab.keys() |
|
2576 | aliases = atab.keys() | |
2578 | aliases.sort() |
|
2577 | aliases.sort() | |
2579 | res = [] |
|
2578 | res = [] | |
2580 | showlast = [] |
|
2579 | showlast = [] | |
2581 | for alias in aliases: |
|
2580 | for alias in aliases: | |
2582 | special = False |
|
2581 | special = False | |
2583 | try: |
|
2582 | try: | |
2584 | tgt = atab[alias][1] |
|
2583 | tgt = atab[alias][1] | |
2585 | except (TypeError, AttributeError): |
|
2584 | except (TypeError, AttributeError): | |
2586 | # unsubscriptable? probably a callable |
|
2585 | # unsubscriptable? probably a callable | |
2587 | tgt = atab[alias] |
|
2586 | tgt = atab[alias] | |
2588 | special = True |
|
2587 | special = True | |
2589 | # 'interesting' aliases |
|
2588 | # 'interesting' aliases | |
2590 | if (alias in stored or |
|
2589 | if (alias in stored or | |
2591 | special or |
|
2590 | special or | |
2592 | alias.lower() != os.path.splitext(tgt)[0].lower() or |
|
2591 | alias.lower() != os.path.splitext(tgt)[0].lower() or | |
2593 | ' ' in tgt): |
|
2592 | ' ' in tgt): | |
2594 | showlast.append((alias, tgt)) |
|
2593 | showlast.append((alias, tgt)) | |
2595 | else: |
|
2594 | else: | |
2596 | res.append((alias, tgt )) |
|
2595 | res.append((alias, tgt )) | |
2597 |
|
2596 | |||
2598 | # show most interesting aliases last |
|
2597 | # show most interesting aliases last | |
2599 | res.extend(showlast) |
|
2598 | res.extend(showlast) | |
2600 | print "Total number of aliases:",len(aliases) |
|
2599 | print "Total number of aliases:",len(aliases) | |
2601 | return res |
|
2600 | return res | |
2602 | try: |
|
2601 | try: | |
2603 | alias,cmd = par.split(None,1) |
|
2602 | alias,cmd = par.split(None,1) | |
2604 | except: |
|
2603 | except: | |
2605 | print OInspect.getdoc(self.magic_alias) |
|
2604 | print OInspect.getdoc(self.magic_alias) | |
2606 | else: |
|
2605 | else: | |
2607 | nargs = cmd.count('%s') |
|
2606 | nargs = cmd.count('%s') | |
2608 | if nargs>0 and cmd.find('%l')>=0: |
|
2607 | if nargs>0 and cmd.find('%l')>=0: | |
2609 | error('The %s and %l specifiers are mutually exclusive ' |
|
2608 | error('The %s and %l specifiers are mutually exclusive ' | |
2610 | 'in alias definitions.') |
|
2609 | 'in alias definitions.') | |
2611 | else: # all looks OK |
|
2610 | else: # all looks OK | |
2612 | self.shell.alias_table[alias] = (nargs,cmd) |
|
2611 | self.shell.alias_table[alias] = (nargs,cmd) | |
2613 | self.shell.alias_table_validate(verbose=0) |
|
2612 | self.shell.alias_table_validate(verbose=0) | |
2614 | # end magic_alias |
|
2613 | # end magic_alias | |
2615 |
|
2614 | |||
2616 | def magic_unalias(self, parameter_s = ''): |
|
2615 | def magic_unalias(self, parameter_s = ''): | |
2617 | """Remove an alias""" |
|
2616 | """Remove an alias""" | |
2618 |
|
2617 | |||
2619 | aname = parameter_s.strip() |
|
2618 | aname = parameter_s.strip() | |
2620 | if aname in self.shell.alias_table: |
|
2619 | if aname in self.shell.alias_table: | |
2621 | del self.shell.alias_table[aname] |
|
2620 | del self.shell.alias_table[aname] | |
2622 | stored = self.db.get('stored_aliases', {} ) |
|
2621 | stored = self.db.get('stored_aliases', {} ) | |
2623 | if aname in stored: |
|
2622 | if aname in stored: | |
2624 | print "Removing %stored alias",aname |
|
2623 | print "Removing %stored alias",aname | |
2625 | del stored[aname] |
|
2624 | del stored[aname] | |
2626 | self.db['stored_aliases'] = stored |
|
2625 | self.db['stored_aliases'] = stored | |
2627 |
|
2626 | |||
2628 |
|
2627 | |||
2629 | def magic_rehashx(self, parameter_s = ''): |
|
2628 | def magic_rehashx(self, parameter_s = ''): | |
2630 | """Update the alias table with all executable files in $PATH. |
|
2629 | """Update the alias table with all executable files in $PATH. | |
2631 |
|
2630 | |||
2632 | This version explicitly checks that every entry in $PATH is a file |
|
2631 | This version explicitly checks that every entry in $PATH is a file | |
2633 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2632 | with execute access (os.X_OK), so it is much slower than %rehash. | |
2634 |
|
2633 | |||
2635 | Under Windows, it checks executability as a match agains a |
|
2634 | Under Windows, it checks executability as a match agains a | |
2636 | '|'-separated string of extensions, stored in the IPython config |
|
2635 | '|'-separated string of extensions, stored in the IPython config | |
2637 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2636 | variable win_exec_ext. This defaults to 'exe|com|bat'. | |
2638 |
|
2637 | |||
2639 | This function also resets the root module cache of module completer, |
|
2638 | This function also resets the root module cache of module completer, | |
2640 | used on slow filesystems. |
|
2639 | used on slow filesystems. | |
2641 | """ |
|
2640 | """ | |
2642 |
|
2641 | |||
2643 |
|
2642 | |||
2644 | ip = self.api |
|
2643 | ip = self.api | |
2645 |
|
2644 | |||
2646 | # for the benefit of module completer in ipy_completers.py |
|
2645 | # for the benefit of module completer in ipy_completers.py | |
2647 | del ip.db['rootmodules'] |
|
2646 | del ip.db['rootmodules'] | |
2648 |
|
2647 | |||
2649 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2648 | path = [os.path.abspath(os.path.expanduser(p)) for p in | |
2650 | os.environ.get('PATH','').split(os.pathsep)] |
|
2649 | os.environ.get('PATH','').split(os.pathsep)] | |
2651 | path = filter(os.path.isdir,path) |
|
2650 | path = filter(os.path.isdir,path) | |
2652 |
|
2651 | |||
2653 | alias_table = self.shell.alias_table |
|
2652 | alias_table = self.shell.alias_table | |
2654 | syscmdlist = [] |
|
2653 | syscmdlist = [] | |
2655 | if os.name == 'posix': |
|
2654 | if os.name == 'posix': | |
2656 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2655 | isexec = lambda fname:os.path.isfile(fname) and \ | |
2657 | os.access(fname,os.X_OK) |
|
2656 | os.access(fname,os.X_OK) | |
2658 | else: |
|
2657 | else: | |
2659 |
|
2658 | |||
2660 | try: |
|
2659 | try: | |
2661 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2660 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
2662 | except KeyError: |
|
2661 | except KeyError: | |
2663 | winext = 'exe|com|bat|py' |
|
2662 | winext = 'exe|com|bat|py' | |
2664 | if 'py' not in winext: |
|
2663 | if 'py' not in winext: | |
2665 | winext += '|py' |
|
2664 | winext += '|py' | |
2666 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2665 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
2667 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2666 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
2668 | savedir = os.getcwd() |
|
2667 | savedir = os.getcwd() | |
2669 | try: |
|
2668 | try: | |
2670 | # write the whole loop for posix/Windows so we don't have an if in |
|
2669 | # write the whole loop for posix/Windows so we don't have an if in | |
2671 | # the innermost part |
|
2670 | # the innermost part | |
2672 | if os.name == 'posix': |
|
2671 | if os.name == 'posix': | |
2673 | for pdir in path: |
|
2672 | for pdir in path: | |
2674 | os.chdir(pdir) |
|
2673 | os.chdir(pdir) | |
2675 | for ff in os.listdir(pdir): |
|
2674 | for ff in os.listdir(pdir): | |
2676 | if isexec(ff) and ff not in self.shell.no_alias: |
|
2675 | if isexec(ff) and ff not in self.shell.no_alias: | |
2677 | # each entry in the alias table must be (N,name), |
|
2676 | # each entry in the alias table must be (N,name), | |
2678 | # where N is the number of positional arguments of the |
|
2677 | # where N is the number of positional arguments of the | |
2679 | # alias. |
|
2678 | # alias. | |
2680 | # Dots will be removed from alias names, since ipython |
|
2679 | # Dots will be removed from alias names, since ipython | |
2681 | # assumes names with dots to be python code |
|
2680 | # assumes names with dots to be python code | |
2682 | alias_table[ff.replace('.','')] = (0,ff) |
|
2681 | alias_table[ff.replace('.','')] = (0,ff) | |
2683 | syscmdlist.append(ff) |
|
2682 | syscmdlist.append(ff) | |
2684 | else: |
|
2683 | else: | |
2685 | for pdir in path: |
|
2684 | for pdir in path: | |
2686 | os.chdir(pdir) |
|
2685 | os.chdir(pdir) | |
2687 | for ff in os.listdir(pdir): |
|
2686 | for ff in os.listdir(pdir): | |
2688 | base, ext = os.path.splitext(ff) |
|
2687 | base, ext = os.path.splitext(ff) | |
2689 | if isexec(ff) and base.lower() not in self.shell.no_alias: |
|
2688 | if isexec(ff) and base.lower() not in self.shell.no_alias: | |
2690 | if ext.lower() == '.exe': |
|
2689 | if ext.lower() == '.exe': | |
2691 | ff = base |
|
2690 | ff = base | |
2692 | alias_table[base.lower().replace('.','')] = (0,ff) |
|
2691 | alias_table[base.lower().replace('.','')] = (0,ff) | |
2693 | syscmdlist.append(ff) |
|
2692 | syscmdlist.append(ff) | |
2694 | # Make sure the alias table doesn't contain keywords or builtins |
|
2693 | # Make sure the alias table doesn't contain keywords or builtins | |
2695 | self.shell.alias_table_validate() |
|
2694 | self.shell.alias_table_validate() | |
2696 | # Call again init_auto_alias() so we get 'rm -i' and other |
|
2695 | # Call again init_auto_alias() so we get 'rm -i' and other | |
2697 | # modified aliases since %rehashx will probably clobber them |
|
2696 | # modified aliases since %rehashx will probably clobber them | |
2698 |
|
2697 | |||
2699 | # no, we don't want them. if %rehashx clobbers them, good, |
|
2698 | # no, we don't want them. if %rehashx clobbers them, good, | |
2700 | # we'll probably get better versions |
|
2699 | # we'll probably get better versions | |
2701 | # self.shell.init_auto_alias() |
|
2700 | # self.shell.init_auto_alias() | |
2702 | db = ip.db |
|
2701 | db = ip.db | |
2703 | db['syscmdlist'] = syscmdlist |
|
2702 | db['syscmdlist'] = syscmdlist | |
2704 | finally: |
|
2703 | finally: | |
2705 | os.chdir(savedir) |
|
2704 | os.chdir(savedir) | |
2706 |
|
2705 | |||
2707 | def magic_pwd(self, parameter_s = ''): |
|
2706 | def magic_pwd(self, parameter_s = ''): | |
2708 | """Return the current working directory path.""" |
|
2707 | """Return the current working directory path.""" | |
2709 | return os.getcwd() |
|
2708 | return os.getcwd() | |
2710 |
|
2709 | |||
2711 | def magic_cd(self, parameter_s=''): |
|
2710 | def magic_cd(self, parameter_s=''): | |
2712 | """Change the current working directory. |
|
2711 | """Change the current working directory. | |
2713 |
|
2712 | |||
2714 | This command automatically maintains an internal list of directories |
|
2713 | This command automatically maintains an internal list of directories | |
2715 | you visit during your IPython session, in the variable _dh. The |
|
2714 | you visit during your IPython session, in the variable _dh. The | |
2716 | command %dhist shows this history nicely formatted. You can also |
|
2715 | command %dhist shows this history nicely formatted. You can also | |
2717 | do 'cd -<tab>' to see directory history conveniently. |
|
2716 | do 'cd -<tab>' to see directory history conveniently. | |
2718 |
|
2717 | |||
2719 | Usage: |
|
2718 | Usage: | |
2720 |
|
2719 | |||
2721 | cd 'dir': changes to directory 'dir'. |
|
2720 | cd 'dir': changes to directory 'dir'. | |
2722 |
|
2721 | |||
2723 | cd -: changes to the last visited directory. |
|
2722 | cd -: changes to the last visited directory. | |
2724 |
|
2723 | |||
2725 | cd -<n>: changes to the n-th directory in the directory history. |
|
2724 | cd -<n>: changes to the n-th directory in the directory history. | |
2726 |
|
2725 | |||
2727 | cd --foo: change to directory that matches 'foo' in history |
|
2726 | cd --foo: change to directory that matches 'foo' in history | |
2728 |
|
2727 | |||
2729 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2728 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
2730 | (note: cd <bookmark_name> is enough if there is no |
|
2729 | (note: cd <bookmark_name> is enough if there is no | |
2731 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2730 | directory <bookmark_name>, but a bookmark with the name exists.) | |
2732 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2731 | 'cd -b <tab>' allows you to tab-complete bookmark names. | |
2733 |
|
2732 | |||
2734 | Options: |
|
2733 | Options: | |
2735 |
|
2734 | |||
2736 | -q: quiet. Do not print the working directory after the cd command is |
|
2735 | -q: quiet. Do not print the working directory after the cd command is | |
2737 | executed. By default IPython's cd command does print this directory, |
|
2736 | executed. By default IPython's cd command does print this directory, | |
2738 | since the default prompts do not display path information. |
|
2737 | since the default prompts do not display path information. | |
2739 |
|
2738 | |||
2740 | Note that !cd doesn't work for this purpose because the shell where |
|
2739 | Note that !cd doesn't work for this purpose because the shell where | |
2741 | !command runs is immediately discarded after executing 'command'.""" |
|
2740 | !command runs is immediately discarded after executing 'command'.""" | |
2742 |
|
2741 | |||
2743 | parameter_s = parameter_s.strip() |
|
2742 | parameter_s = parameter_s.strip() | |
2744 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2743 | #bkms = self.shell.persist.get("bookmarks",{}) | |
2745 |
|
2744 | |||
2746 | oldcwd = os.getcwd() |
|
2745 | oldcwd = os.getcwd() | |
2747 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2746 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
2748 | # jump in directory history by number |
|
2747 | # jump in directory history by number | |
2749 | if numcd: |
|
2748 | if numcd: | |
2750 | nn = int(numcd.group(2)) |
|
2749 | nn = int(numcd.group(2)) | |
2751 | try: |
|
2750 | try: | |
2752 | ps = self.shell.user_ns['_dh'][nn] |
|
2751 | ps = self.shell.user_ns['_dh'][nn] | |
2753 | except IndexError: |
|
2752 | except IndexError: | |
2754 | print 'The requested directory does not exist in history.' |
|
2753 | print 'The requested directory does not exist in history.' | |
2755 | return |
|
2754 | return | |
2756 | else: |
|
2755 | else: | |
2757 | opts = {} |
|
2756 | opts = {} | |
2758 | elif parameter_s.startswith('--'): |
|
2757 | elif parameter_s.startswith('--'): | |
2759 | ps = None |
|
2758 | ps = None | |
2760 | fallback = None |
|
2759 | fallback = None | |
2761 | pat = parameter_s[2:] |
|
2760 | pat = parameter_s[2:] | |
2762 | dh = self.shell.user_ns['_dh'] |
|
2761 | dh = self.shell.user_ns['_dh'] | |
2763 | # first search only by basename (last component) |
|
2762 | # first search only by basename (last component) | |
2764 | for ent in reversed(dh): |
|
2763 | for ent in reversed(dh): | |
2765 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
2764 | if pat in os.path.basename(ent) and os.path.isdir(ent): | |
2766 | ps = ent |
|
2765 | ps = ent | |
2767 | break |
|
2766 | break | |
2768 |
|
2767 | |||
2769 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
2768 | if fallback is None and pat in ent and os.path.isdir(ent): | |
2770 | fallback = ent |
|
2769 | fallback = ent | |
2771 |
|
2770 | |||
2772 | # if we have no last part match, pick the first full path match |
|
2771 | # if we have no last part match, pick the first full path match | |
2773 | if ps is None: |
|
2772 | if ps is None: | |
2774 | ps = fallback |
|
2773 | ps = fallback | |
2775 |
|
2774 | |||
2776 | if ps is None: |
|
2775 | if ps is None: | |
2777 | print "No matching entry in directory history" |
|
2776 | print "No matching entry in directory history" | |
2778 | return |
|
2777 | return | |
2779 | else: |
|
2778 | else: | |
2780 | opts = {} |
|
2779 | opts = {} | |
2781 |
|
2780 | |||
2782 |
|
2781 | |||
2783 | else: |
|
2782 | else: | |
2784 | #turn all non-space-escaping backslashes to slashes, |
|
2783 | #turn all non-space-escaping backslashes to slashes, | |
2785 | # for c:\windows\directory\names\ |
|
2784 | # for c:\windows\directory\names\ | |
2786 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2785 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) | |
2787 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2786 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
2788 | # jump to previous |
|
2787 | # jump to previous | |
2789 | if ps == '-': |
|
2788 | if ps == '-': | |
2790 | try: |
|
2789 | try: | |
2791 | ps = self.shell.user_ns['_dh'][-2] |
|
2790 | ps = self.shell.user_ns['_dh'][-2] | |
2792 | except IndexError: |
|
2791 | except IndexError: | |
2793 | raise UsageError('%cd -: No previous directory to change to.') |
|
2792 | raise UsageError('%cd -: No previous directory to change to.') | |
2794 | # jump to bookmark if needed |
|
2793 | # jump to bookmark if needed | |
2795 | else: |
|
2794 | else: | |
2796 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2795 | if not os.path.isdir(ps) or opts.has_key('b'): | |
2797 | bkms = self.db.get('bookmarks', {}) |
|
2796 | bkms = self.db.get('bookmarks', {}) | |
2798 |
|
2797 | |||
2799 | if bkms.has_key(ps): |
|
2798 | if bkms.has_key(ps): | |
2800 | target = bkms[ps] |
|
2799 | target = bkms[ps] | |
2801 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2800 | print '(bookmark:%s) -> %s' % (ps,target) | |
2802 | ps = target |
|
2801 | ps = target | |
2803 | else: |
|
2802 | else: | |
2804 | if opts.has_key('b'): |
|
2803 | if opts.has_key('b'): | |
2805 | raise UsageError("Bookmark '%s' not found. " |
|
2804 | raise UsageError("Bookmark '%s' not found. " | |
2806 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2805 | "Use '%%bookmark -l' to see your bookmarks." % ps) | |
2807 |
|
2806 | |||
2808 | # at this point ps should point to the target dir |
|
2807 | # at this point ps should point to the target dir | |
2809 | if ps: |
|
2808 | if ps: | |
2810 | try: |
|
2809 | try: | |
2811 | os.chdir(os.path.expanduser(ps)) |
|
2810 | os.chdir(os.path.expanduser(ps)) | |
2812 | if self.shell.rc.term_title: |
|
2811 | if self.shell.rc.term_title: | |
2813 | #print 'set term title:',self.shell.rc.term_title # dbg |
|
2812 | #print 'set term title:',self.shell.rc.term_title # dbg | |
2814 | platutils.set_term_title('IPy ' + abbrev_cwd()) |
|
2813 | platutils.set_term_title('IPy ' + abbrev_cwd()) | |
2815 | except OSError: |
|
2814 | except OSError: | |
2816 | print sys.exc_info()[1] |
|
2815 | print sys.exc_info()[1] | |
2817 | else: |
|
2816 | else: | |
2818 | cwd = os.getcwd() |
|
2817 | cwd = os.getcwd() | |
2819 | dhist = self.shell.user_ns['_dh'] |
|
2818 | dhist = self.shell.user_ns['_dh'] | |
2820 | if oldcwd != cwd: |
|
2819 | if oldcwd != cwd: | |
2821 | dhist.append(cwd) |
|
2820 | dhist.append(cwd) | |
2822 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2821 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2823 |
|
2822 | |||
2824 | else: |
|
2823 | else: | |
2825 | os.chdir(self.shell.home_dir) |
|
2824 | os.chdir(self.shell.home_dir) | |
2826 | if self.shell.rc.term_title: |
|
2825 | if self.shell.rc.term_title: | |
2827 | platutils.set_term_title("IPy ~") |
|
2826 | platutils.set_term_title("IPy ~") | |
2828 | cwd = os.getcwd() |
|
2827 | cwd = os.getcwd() | |
2829 | dhist = self.shell.user_ns['_dh'] |
|
2828 | dhist = self.shell.user_ns['_dh'] | |
2830 |
|
2829 | |||
2831 | if oldcwd != cwd: |
|
2830 | if oldcwd != cwd: | |
2832 | dhist.append(cwd) |
|
2831 | dhist.append(cwd) | |
2833 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2832 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2834 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
2833 | if not 'q' in opts and self.shell.user_ns['_dh']: | |
2835 | print self.shell.user_ns['_dh'][-1] |
|
2834 | print self.shell.user_ns['_dh'][-1] | |
2836 |
|
2835 | |||
2837 |
|
2836 | |||
2838 | def magic_env(self, parameter_s=''): |
|
2837 | def magic_env(self, parameter_s=''): | |
2839 | """List environment variables.""" |
|
2838 | """List environment variables.""" | |
2840 |
|
2839 | |||
2841 | return os.environ.data |
|
2840 | return os.environ.data | |
2842 |
|
2841 | |||
2843 | def magic_pushd(self, parameter_s=''): |
|
2842 | def magic_pushd(self, parameter_s=''): | |
2844 | """Place the current dir on stack and change directory. |
|
2843 | """Place the current dir on stack and change directory. | |
2845 |
|
2844 | |||
2846 | Usage:\\ |
|
2845 | Usage:\\ | |
2847 | %pushd ['dirname'] |
|
2846 | %pushd ['dirname'] | |
2848 | """ |
|
2847 | """ | |
2849 |
|
2848 | |||
2850 | dir_s = self.shell.dir_stack |
|
2849 | dir_s = self.shell.dir_stack | |
2851 | tgt = os.path.expanduser(parameter_s) |
|
2850 | tgt = os.path.expanduser(parameter_s) | |
2852 | cwd = os.getcwd().replace(self.home_dir,'~') |
|
2851 | cwd = os.getcwd().replace(self.home_dir,'~') | |
2853 | if tgt: |
|
2852 | if tgt: | |
2854 | self.magic_cd(parameter_s) |
|
2853 | self.magic_cd(parameter_s) | |
2855 | dir_s.insert(0,cwd) |
|
2854 | dir_s.insert(0,cwd) | |
2856 | return self.magic_dirs() |
|
2855 | return self.magic_dirs() | |
2857 |
|
2856 | |||
2858 | def magic_popd(self, parameter_s=''): |
|
2857 | def magic_popd(self, parameter_s=''): | |
2859 | """Change to directory popped off the top of the stack. |
|
2858 | """Change to directory popped off the top of the stack. | |
2860 | """ |
|
2859 | """ | |
2861 | if not self.shell.dir_stack: |
|
2860 | if not self.shell.dir_stack: | |
2862 | raise UsageError("%popd on empty stack") |
|
2861 | raise UsageError("%popd on empty stack") | |
2863 | top = self.shell.dir_stack.pop(0) |
|
2862 | top = self.shell.dir_stack.pop(0) | |
2864 | self.magic_cd(top) |
|
2863 | self.magic_cd(top) | |
2865 | print "popd ->",top |
|
2864 | print "popd ->",top | |
2866 |
|
2865 | |||
2867 | def magic_dirs(self, parameter_s=''): |
|
2866 | def magic_dirs(self, parameter_s=''): | |
2868 | """Return the current directory stack.""" |
|
2867 | """Return the current directory stack.""" | |
2869 |
|
2868 | |||
2870 | return self.shell.dir_stack |
|
2869 | return self.shell.dir_stack | |
2871 |
|
2870 | |||
2872 | def magic_dhist(self, parameter_s=''): |
|
2871 | def magic_dhist(self, parameter_s=''): | |
2873 | """Print your history of visited directories. |
|
2872 | """Print your history of visited directories. | |
2874 |
|
2873 | |||
2875 | %dhist -> print full history\\ |
|
2874 | %dhist -> print full history\\ | |
2876 | %dhist n -> print last n entries only\\ |
|
2875 | %dhist n -> print last n entries only\\ | |
2877 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2876 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |
2878 |
|
2877 | |||
2879 | This history is automatically maintained by the %cd command, and |
|
2878 | This history is automatically maintained by the %cd command, and | |
2880 | always available as the global list variable _dh. You can use %cd -<n> |
|
2879 | always available as the global list variable _dh. You can use %cd -<n> | |
2881 | to go to directory number <n>. |
|
2880 | to go to directory number <n>. | |
2882 |
|
2881 | |||
2883 | Note that most of time, you should view directory history by entering |
|
2882 | Note that most of time, you should view directory history by entering | |
2884 | cd -<TAB>. |
|
2883 | cd -<TAB>. | |
2885 |
|
2884 | |||
2886 | """ |
|
2885 | """ | |
2887 |
|
2886 | |||
2888 | dh = self.shell.user_ns['_dh'] |
|
2887 | dh = self.shell.user_ns['_dh'] | |
2889 | if parameter_s: |
|
2888 | if parameter_s: | |
2890 | try: |
|
2889 | try: | |
2891 | args = map(int,parameter_s.split()) |
|
2890 | args = map(int,parameter_s.split()) | |
2892 | except: |
|
2891 | except: | |
2893 | self.arg_err(Magic.magic_dhist) |
|
2892 | self.arg_err(Magic.magic_dhist) | |
2894 | return |
|
2893 | return | |
2895 | if len(args) == 1: |
|
2894 | if len(args) == 1: | |
2896 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2895 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |
2897 | elif len(args) == 2: |
|
2896 | elif len(args) == 2: | |
2898 | ini,fin = args |
|
2897 | ini,fin = args | |
2899 | else: |
|
2898 | else: | |
2900 | self.arg_err(Magic.magic_dhist) |
|
2899 | self.arg_err(Magic.magic_dhist) | |
2901 | return |
|
2900 | return | |
2902 | else: |
|
2901 | else: | |
2903 | ini,fin = 0,len(dh) |
|
2902 | ini,fin = 0,len(dh) | |
2904 | nlprint(dh, |
|
2903 | nlprint(dh, | |
2905 | header = 'Directory history (kept in _dh)', |
|
2904 | header = 'Directory history (kept in _dh)', | |
2906 | start=ini,stop=fin) |
|
2905 | start=ini,stop=fin) | |
2907 |
|
2906 | |||
2908 | @testdec.skip_doctest |
|
2907 | @testdec.skip_doctest | |
2909 | def magic_sc(self, parameter_s=''): |
|
2908 | def magic_sc(self, parameter_s=''): | |
2910 | """Shell capture - execute a shell command and capture its output. |
|
2909 | """Shell capture - execute a shell command and capture its output. | |
2911 |
|
2910 | |||
2912 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2911 | DEPRECATED. Suboptimal, retained for backwards compatibility. | |
2913 |
|
2912 | |||
2914 | You should use the form 'var = !command' instead. Example: |
|
2913 | You should use the form 'var = !command' instead. Example: | |
2915 |
|
2914 | |||
2916 | "%sc -l myfiles = ls ~" should now be written as |
|
2915 | "%sc -l myfiles = ls ~" should now be written as | |
2917 |
|
2916 | |||
2918 | "myfiles = !ls ~" |
|
2917 | "myfiles = !ls ~" | |
2919 |
|
2918 | |||
2920 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2919 | myfiles.s, myfiles.l and myfiles.n still apply as documented | |
2921 | below. |
|
2920 | below. | |
2922 |
|
2921 | |||
2923 | -- |
|
2922 | -- | |
2924 | %sc [options] varname=command |
|
2923 | %sc [options] varname=command | |
2925 |
|
2924 | |||
2926 | IPython will run the given command using commands.getoutput(), and |
|
2925 | IPython will run the given command using commands.getoutput(), and | |
2927 | will then update the user's interactive namespace with a variable |
|
2926 | will then update the user's interactive namespace with a variable | |
2928 | called varname, containing the value of the call. Your command can |
|
2927 | called varname, containing the value of the call. Your command can | |
2929 | contain shell wildcards, pipes, etc. |
|
2928 | contain shell wildcards, pipes, etc. | |
2930 |
|
2929 | |||
2931 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2930 | The '=' sign in the syntax is mandatory, and the variable name you | |
2932 | supply must follow Python's standard conventions for valid names. |
|
2931 | supply must follow Python's standard conventions for valid names. | |
2933 |
|
2932 | |||
2934 | (A special format without variable name exists for internal use) |
|
2933 | (A special format without variable name exists for internal use) | |
2935 |
|
2934 | |||
2936 | Options: |
|
2935 | Options: | |
2937 |
|
2936 | |||
2938 | -l: list output. Split the output on newlines into a list before |
|
2937 | -l: list output. Split the output on newlines into a list before | |
2939 | assigning it to the given variable. By default the output is stored |
|
2938 | assigning it to the given variable. By default the output is stored | |
2940 | as a single string. |
|
2939 | as a single string. | |
2941 |
|
2940 | |||
2942 | -v: verbose. Print the contents of the variable. |
|
2941 | -v: verbose. Print the contents of the variable. | |
2943 |
|
2942 | |||
2944 | In most cases you should not need to split as a list, because the |
|
2943 | In most cases you should not need to split as a list, because the | |
2945 | returned value is a special type of string which can automatically |
|
2944 | returned value is a special type of string which can automatically | |
2946 | provide its contents either as a list (split on newlines) or as a |
|
2945 | provide its contents either as a list (split on newlines) or as a | |
2947 | space-separated string. These are convenient, respectively, either |
|
2946 | space-separated string. These are convenient, respectively, either | |
2948 | for sequential processing or to be passed to a shell command. |
|
2947 | for sequential processing or to be passed to a shell command. | |
2949 |
|
2948 | |||
2950 | For example: |
|
2949 | For example: | |
2951 |
|
2950 | |||
2952 | # all-random |
|
2951 | # all-random | |
2953 |
|
2952 | |||
2954 | # Capture into variable a |
|
2953 | # Capture into variable a | |
2955 | In [1]: sc a=ls *py |
|
2954 | In [1]: sc a=ls *py | |
2956 |
|
2955 | |||
2957 | # a is a string with embedded newlines |
|
2956 | # a is a string with embedded newlines | |
2958 | In [2]: a |
|
2957 | In [2]: a | |
2959 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
2958 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' | |
2960 |
|
2959 | |||
2961 | # which can be seen as a list: |
|
2960 | # which can be seen as a list: | |
2962 | In [3]: a.l |
|
2961 | In [3]: a.l | |
2963 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
2962 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] | |
2964 |
|
2963 | |||
2965 | # or as a whitespace-separated string: |
|
2964 | # or as a whitespace-separated string: | |
2966 | In [4]: a.s |
|
2965 | In [4]: a.s | |
2967 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
2966 | Out[4]: 'setup.py win32_manual_post_install.py' | |
2968 |
|
2967 | |||
2969 | # a.s is useful to pass as a single command line: |
|
2968 | # a.s is useful to pass as a single command line: | |
2970 | In [5]: !wc -l $a.s |
|
2969 | In [5]: !wc -l $a.s | |
2971 | 146 setup.py |
|
2970 | 146 setup.py | |
2972 | 130 win32_manual_post_install.py |
|
2971 | 130 win32_manual_post_install.py | |
2973 | 276 total |
|
2972 | 276 total | |
2974 |
|
2973 | |||
2975 | # while the list form is useful to loop over: |
|
2974 | # while the list form is useful to loop over: | |
2976 | In [6]: for f in a.l: |
|
2975 | In [6]: for f in a.l: | |
2977 | ...: !wc -l $f |
|
2976 | ...: !wc -l $f | |
2978 | ...: |
|
2977 | ...: | |
2979 | 146 setup.py |
|
2978 | 146 setup.py | |
2980 | 130 win32_manual_post_install.py |
|
2979 | 130 win32_manual_post_install.py | |
2981 |
|
2980 | |||
2982 | Similiarly, the lists returned by the -l option are also special, in |
|
2981 | Similiarly, the lists returned by the -l option are also special, in | |
2983 | the sense that you can equally invoke the .s attribute on them to |
|
2982 | the sense that you can equally invoke the .s attribute on them to | |
2984 | automatically get a whitespace-separated string from their contents: |
|
2983 | automatically get a whitespace-separated string from their contents: | |
2985 |
|
2984 | |||
2986 | In [7]: sc -l b=ls *py |
|
2985 | In [7]: sc -l b=ls *py | |
2987 |
|
2986 | |||
2988 | In [8]: b |
|
2987 | In [8]: b | |
2989 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
2988 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] | |
2990 |
|
2989 | |||
2991 | In [9]: b.s |
|
2990 | In [9]: b.s | |
2992 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
2991 | Out[9]: 'setup.py win32_manual_post_install.py' | |
2993 |
|
2992 | |||
2994 | In summary, both the lists and strings used for ouptut capture have |
|
2993 | In summary, both the lists and strings used for ouptut capture have | |
2995 | the following special attributes: |
|
2994 | the following special attributes: | |
2996 |
|
2995 | |||
2997 | .l (or .list) : value as list. |
|
2996 | .l (or .list) : value as list. | |
2998 | .n (or .nlstr): value as newline-separated string. |
|
2997 | .n (or .nlstr): value as newline-separated string. | |
2999 | .s (or .spstr): value as space-separated string. |
|
2998 | .s (or .spstr): value as space-separated string. | |
3000 | """ |
|
2999 | """ | |
3001 |
|
3000 | |||
3002 | opts,args = self.parse_options(parameter_s,'lv') |
|
3001 | opts,args = self.parse_options(parameter_s,'lv') | |
3003 | # Try to get a variable name and command to run |
|
3002 | # Try to get a variable name and command to run | |
3004 | try: |
|
3003 | try: | |
3005 | # the variable name must be obtained from the parse_options |
|
3004 | # the variable name must be obtained from the parse_options | |
3006 | # output, which uses shlex.split to strip options out. |
|
3005 | # output, which uses shlex.split to strip options out. | |
3007 | var,_ = args.split('=',1) |
|
3006 | var,_ = args.split('=',1) | |
3008 | var = var.strip() |
|
3007 | var = var.strip() | |
3009 | # But the the command has to be extracted from the original input |
|
3008 | # But the the command has to be extracted from the original input | |
3010 | # parameter_s, not on what parse_options returns, to avoid the |
|
3009 | # parameter_s, not on what parse_options returns, to avoid the | |
3011 | # quote stripping which shlex.split performs on it. |
|
3010 | # quote stripping which shlex.split performs on it. | |
3012 | _,cmd = parameter_s.split('=',1) |
|
3011 | _,cmd = parameter_s.split('=',1) | |
3013 | except ValueError: |
|
3012 | except ValueError: | |
3014 | var,cmd = '','' |
|
3013 | var,cmd = '','' | |
3015 | # If all looks ok, proceed |
|
3014 | # If all looks ok, proceed | |
3016 | out,err = self.shell.getoutputerror(cmd) |
|
3015 | out,err = self.shell.getoutputerror(cmd) | |
3017 | if err: |
|
3016 | if err: | |
3018 | print >> Term.cerr,err |
|
3017 | print >> Term.cerr,err | |
3019 | if opts.has_key('l'): |
|
3018 | if opts.has_key('l'): | |
3020 | out = SList(out.split('\n')) |
|
3019 | out = SList(out.split('\n')) | |
3021 | else: |
|
3020 | else: | |
3022 | out = LSString(out) |
|
3021 | out = LSString(out) | |
3023 | if opts.has_key('v'): |
|
3022 | if opts.has_key('v'): | |
3024 | print '%s ==\n%s' % (var,pformat(out)) |
|
3023 | print '%s ==\n%s' % (var,pformat(out)) | |
3025 | if var: |
|
3024 | if var: | |
3026 | self.shell.user_ns.update({var:out}) |
|
3025 | self.shell.user_ns.update({var:out}) | |
3027 | else: |
|
3026 | else: | |
3028 | return out |
|
3027 | return out | |
3029 |
|
3028 | |||
3030 | def magic_sx(self, parameter_s=''): |
|
3029 | def magic_sx(self, parameter_s=''): | |
3031 | """Shell execute - run a shell command and capture its output. |
|
3030 | """Shell execute - run a shell command and capture its output. | |
3032 |
|
3031 | |||
3033 | %sx command |
|
3032 | %sx command | |
3034 |
|
3033 | |||
3035 | IPython will run the given command using commands.getoutput(), and |
|
3034 | IPython will run the given command using commands.getoutput(), and | |
3036 | return the result formatted as a list (split on '\\n'). Since the |
|
3035 | return the result formatted as a list (split on '\\n'). Since the | |
3037 | output is _returned_, it will be stored in ipython's regular output |
|
3036 | output is _returned_, it will be stored in ipython's regular output | |
3038 | cache Out[N] and in the '_N' automatic variables. |
|
3037 | cache Out[N] and in the '_N' automatic variables. | |
3039 |
|
3038 | |||
3040 | Notes: |
|
3039 | Notes: | |
3041 |
|
3040 | |||
3042 | 1) If an input line begins with '!!', then %sx is automatically |
|
3041 | 1) If an input line begins with '!!', then %sx is automatically | |
3043 | invoked. That is, while: |
|
3042 | invoked. That is, while: | |
3044 | !ls |
|
3043 | !ls | |
3045 | causes ipython to simply issue system('ls'), typing |
|
3044 | causes ipython to simply issue system('ls'), typing | |
3046 | !!ls |
|
3045 | !!ls | |
3047 | is a shorthand equivalent to: |
|
3046 | is a shorthand equivalent to: | |
3048 | %sx ls |
|
3047 | %sx ls | |
3049 |
|
3048 | |||
3050 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
3049 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
3051 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
3050 | like '%sc -l'. The reason for this is to make it as easy as possible | |
3052 | to process line-oriented shell output via further python commands. |
|
3051 | to process line-oriented shell output via further python commands. | |
3053 | %sc is meant to provide much finer control, but requires more |
|
3052 | %sc is meant to provide much finer control, but requires more | |
3054 | typing. |
|
3053 | typing. | |
3055 |
|
3054 | |||
3056 | 3) Just like %sc -l, this is a list with special attributes: |
|
3055 | 3) Just like %sc -l, this is a list with special attributes: | |
3057 |
|
3056 | |||
3058 | .l (or .list) : value as list. |
|
3057 | .l (or .list) : value as list. | |
3059 | .n (or .nlstr): value as newline-separated string. |
|
3058 | .n (or .nlstr): value as newline-separated string. | |
3060 | .s (or .spstr): value as whitespace-separated string. |
|
3059 | .s (or .spstr): value as whitespace-separated string. | |
3061 |
|
3060 | |||
3062 | This is very useful when trying to use such lists as arguments to |
|
3061 | This is very useful when trying to use such lists as arguments to | |
3063 | system commands.""" |
|
3062 | system commands.""" | |
3064 |
|
3063 | |||
3065 | if parameter_s: |
|
3064 | if parameter_s: | |
3066 | out,err = self.shell.getoutputerror(parameter_s) |
|
3065 | out,err = self.shell.getoutputerror(parameter_s) | |
3067 | if err: |
|
3066 | if err: | |
3068 | print >> Term.cerr,err |
|
3067 | print >> Term.cerr,err | |
3069 | return SList(out.split('\n')) |
|
3068 | return SList(out.split('\n')) | |
3070 |
|
3069 | |||
3071 | def magic_bg(self, parameter_s=''): |
|
3070 | def magic_bg(self, parameter_s=''): | |
3072 | """Run a job in the background, in a separate thread. |
|
3071 | """Run a job in the background, in a separate thread. | |
3073 |
|
3072 | |||
3074 | For example, |
|
3073 | For example, | |
3075 |
|
3074 | |||
3076 | %bg myfunc(x,y,z=1) |
|
3075 | %bg myfunc(x,y,z=1) | |
3077 |
|
3076 | |||
3078 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the |
|
3077 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the | |
3079 | execution starts, a message will be printed indicating the job |
|
3078 | execution starts, a message will be printed indicating the job | |
3080 | number. If your job number is 5, you can use |
|
3079 | number. If your job number is 5, you can use | |
3081 |
|
3080 | |||
3082 | myvar = jobs.result(5) or myvar = jobs[5].result |
|
3081 | myvar = jobs.result(5) or myvar = jobs[5].result | |
3083 |
|
3082 | |||
3084 | to assign this result to variable 'myvar'. |
|
3083 | to assign this result to variable 'myvar'. | |
3085 |
|
3084 | |||
3086 | IPython has a job manager, accessible via the 'jobs' object. You can |
|
3085 | IPython has a job manager, accessible via the 'jobs' object. You can | |
3087 | type jobs? to get more information about it, and use jobs.<TAB> to see |
|
3086 | type jobs? to get more information about it, and use jobs.<TAB> to see | |
3088 | its attributes. All attributes not starting with an underscore are |
|
3087 | its attributes. All attributes not starting with an underscore are | |
3089 | meant for public use. |
|
3088 | meant for public use. | |
3090 |
|
3089 | |||
3091 | In particular, look at the jobs.new() method, which is used to create |
|
3090 | In particular, look at the jobs.new() method, which is used to create | |
3092 | new jobs. This magic %bg function is just a convenience wrapper |
|
3091 | new jobs. This magic %bg function is just a convenience wrapper | |
3093 | around jobs.new(), for expression-based jobs. If you want to create a |
|
3092 | around jobs.new(), for expression-based jobs. If you want to create a | |
3094 | new job with an explicit function object and arguments, you must call |
|
3093 | new job with an explicit function object and arguments, you must call | |
3095 | jobs.new() directly. |
|
3094 | jobs.new() directly. | |
3096 |
|
3095 | |||
3097 | The jobs.new docstring also describes in detail several important |
|
3096 | The jobs.new docstring also describes in detail several important | |
3098 | caveats associated with a thread-based model for background job |
|
3097 | caveats associated with a thread-based model for background job | |
3099 | execution. Type jobs.new? for details. |
|
3098 | execution. Type jobs.new? for details. | |
3100 |
|
3099 | |||
3101 | You can check the status of all jobs with jobs.status(). |
|
3100 | You can check the status of all jobs with jobs.status(). | |
3102 |
|
3101 | |||
3103 | The jobs variable is set by IPython into the Python builtin namespace. |
|
3102 | The jobs variable is set by IPython into the Python builtin namespace. | |
3104 | If you ever declare a variable named 'jobs', you will shadow this |
|
3103 | If you ever declare a variable named 'jobs', you will shadow this | |
3105 | name. You can either delete your global jobs variable to regain |
|
3104 | name. You can either delete your global jobs variable to regain | |
3106 | access to the job manager, or make a new name and assign it manually |
|
3105 | access to the job manager, or make a new name and assign it manually | |
3107 | to the manager (stored in IPython's namespace). For example, to |
|
3106 | to the manager (stored in IPython's namespace). For example, to | |
3108 | assign the job manager to the Jobs name, use: |
|
3107 | assign the job manager to the Jobs name, use: | |
3109 |
|
3108 | |||
3110 | Jobs = __builtins__.jobs""" |
|
3109 | Jobs = __builtins__.jobs""" | |
3111 |
|
3110 | |||
3112 | self.shell.jobs.new(parameter_s,self.shell.user_ns) |
|
3111 | self.shell.jobs.new(parameter_s,self.shell.user_ns) | |
3113 |
|
3112 | |||
3114 | def magic_r(self, parameter_s=''): |
|
3113 | def magic_r(self, parameter_s=''): | |
3115 | """Repeat previous input. |
|
3114 | """Repeat previous input. | |
3116 |
|
3115 | |||
3117 | Note: Consider using the more powerfull %rep instead! |
|
3116 | Note: Consider using the more powerfull %rep instead! | |
3118 |
|
3117 | |||
3119 | If given an argument, repeats the previous command which starts with |
|
3118 | If given an argument, repeats the previous command which starts with | |
3120 | the same string, otherwise it just repeats the previous input. |
|
3119 | the same string, otherwise it just repeats the previous input. | |
3121 |
|
3120 | |||
3122 | Shell escaped commands (with ! as first character) are not recognized |
|
3121 | Shell escaped commands (with ! as first character) are not recognized | |
3123 | by this system, only pure python code and magic commands. |
|
3122 | by this system, only pure python code and magic commands. | |
3124 | """ |
|
3123 | """ | |
3125 |
|
3124 | |||
3126 | start = parameter_s.strip() |
|
3125 | start = parameter_s.strip() | |
3127 | esc_magic = self.shell.ESC_MAGIC |
|
3126 | esc_magic = self.shell.ESC_MAGIC | |
3128 | # Identify magic commands even if automagic is on (which means |
|
3127 | # Identify magic commands even if automagic is on (which means | |
3129 | # the in-memory version is different from that typed by the user). |
|
3128 | # the in-memory version is different from that typed by the user). | |
3130 | if self.shell.rc.automagic: |
|
3129 | if self.shell.rc.automagic: | |
3131 | start_magic = esc_magic+start |
|
3130 | start_magic = esc_magic+start | |
3132 | else: |
|
3131 | else: | |
3133 | start_magic = start |
|
3132 | start_magic = start | |
3134 | # Look through the input history in reverse |
|
3133 | # Look through the input history in reverse | |
3135 | for n in range(len(self.shell.input_hist)-2,0,-1): |
|
3134 | for n in range(len(self.shell.input_hist)-2,0,-1): | |
3136 | input = self.shell.input_hist[n] |
|
3135 | input = self.shell.input_hist[n] | |
3137 | # skip plain 'r' lines so we don't recurse to infinity |
|
3136 | # skip plain 'r' lines so we don't recurse to infinity | |
3138 | if input != '_ip.magic("r")\n' and \ |
|
3137 | if input != '_ip.magic("r")\n' and \ | |
3139 | (input.startswith(start) or input.startswith(start_magic)): |
|
3138 | (input.startswith(start) or input.startswith(start_magic)): | |
3140 | #print 'match',`input` # dbg |
|
3139 | #print 'match',`input` # dbg | |
3141 | print 'Executing:',input, |
|
3140 | print 'Executing:',input, | |
3142 | self.shell.runlines(input) |
|
3141 | self.shell.runlines(input) | |
3143 | return |
|
3142 | return | |
3144 | print 'No previous input matching `%s` found.' % start |
|
3143 | print 'No previous input matching `%s` found.' % start | |
3145 |
|
3144 | |||
3146 |
|
3145 | |||
3147 | def magic_bookmark(self, parameter_s=''): |
|
3146 | def magic_bookmark(self, parameter_s=''): | |
3148 | """Manage IPython's bookmark system. |
|
3147 | """Manage IPython's bookmark system. | |
3149 |
|
3148 | |||
3150 | %bookmark <name> - set bookmark to current dir |
|
3149 | %bookmark <name> - set bookmark to current dir | |
3151 | %bookmark <name> <dir> - set bookmark to <dir> |
|
3150 | %bookmark <name> <dir> - set bookmark to <dir> | |
3152 | %bookmark -l - list all bookmarks |
|
3151 | %bookmark -l - list all bookmarks | |
3153 | %bookmark -d <name> - remove bookmark |
|
3152 | %bookmark -d <name> - remove bookmark | |
3154 | %bookmark -r - remove all bookmarks |
|
3153 | %bookmark -r - remove all bookmarks | |
3155 |
|
3154 | |||
3156 | You can later on access a bookmarked folder with: |
|
3155 | You can later on access a bookmarked folder with: | |
3157 | %cd -b <name> |
|
3156 | %cd -b <name> | |
3158 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3157 | or simply '%cd <name>' if there is no directory called <name> AND | |
3159 | there is such a bookmark defined. |
|
3158 | there is such a bookmark defined. | |
3160 |
|
3159 | |||
3161 | Your bookmarks persist through IPython sessions, but they are |
|
3160 | Your bookmarks persist through IPython sessions, but they are | |
3162 | associated with each profile.""" |
|
3161 | associated with each profile.""" | |
3163 |
|
3162 | |||
3164 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3163 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
3165 | if len(args) > 2: |
|
3164 | if len(args) > 2: | |
3166 | raise UsageError("%bookmark: too many arguments") |
|
3165 | raise UsageError("%bookmark: too many arguments") | |
3167 |
|
3166 | |||
3168 | bkms = self.db.get('bookmarks',{}) |
|
3167 | bkms = self.db.get('bookmarks',{}) | |
3169 |
|
3168 | |||
3170 | if opts.has_key('d'): |
|
3169 | if opts.has_key('d'): | |
3171 | try: |
|
3170 | try: | |
3172 | todel = args[0] |
|
3171 | todel = args[0] | |
3173 | except IndexError: |
|
3172 | except IndexError: | |
3174 | raise UsageError( |
|
3173 | raise UsageError( | |
3175 | "%bookmark -d: must provide a bookmark to delete") |
|
3174 | "%bookmark -d: must provide a bookmark to delete") | |
3176 | else: |
|
3175 | else: | |
3177 | try: |
|
3176 | try: | |
3178 | del bkms[todel] |
|
3177 | del bkms[todel] | |
3179 | except KeyError: |
|
3178 | except KeyError: | |
3180 | raise UsageError( |
|
3179 | raise UsageError( | |
3181 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3180 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) | |
3182 |
|
3181 | |||
3183 | elif opts.has_key('r'): |
|
3182 | elif opts.has_key('r'): | |
3184 | bkms = {} |
|
3183 | bkms = {} | |
3185 | elif opts.has_key('l'): |
|
3184 | elif opts.has_key('l'): | |
3186 | bks = bkms.keys() |
|
3185 | bks = bkms.keys() | |
3187 | bks.sort() |
|
3186 | bks.sort() | |
3188 | if bks: |
|
3187 | if bks: | |
3189 | size = max(map(len,bks)) |
|
3188 | size = max(map(len,bks)) | |
3190 | else: |
|
3189 | else: | |
3191 | size = 0 |
|
3190 | size = 0 | |
3192 | fmt = '%-'+str(size)+'s -> %s' |
|
3191 | fmt = '%-'+str(size)+'s -> %s' | |
3193 | print 'Current bookmarks:' |
|
3192 | print 'Current bookmarks:' | |
3194 | for bk in bks: |
|
3193 | for bk in bks: | |
3195 | print fmt % (bk,bkms[bk]) |
|
3194 | print fmt % (bk,bkms[bk]) | |
3196 | else: |
|
3195 | else: | |
3197 | if not args: |
|
3196 | if not args: | |
3198 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3197 | raise UsageError("%bookmark: You must specify the bookmark name") | |
3199 | elif len(args)==1: |
|
3198 | elif len(args)==1: | |
3200 | bkms[args[0]] = os.getcwd() |
|
3199 | bkms[args[0]] = os.getcwd() | |
3201 | elif len(args)==2: |
|
3200 | elif len(args)==2: | |
3202 | bkms[args[0]] = args[1] |
|
3201 | bkms[args[0]] = args[1] | |
3203 | self.db['bookmarks'] = bkms |
|
3202 | self.db['bookmarks'] = bkms | |
3204 |
|
3203 | |||
3205 | def magic_pycat(self, parameter_s=''): |
|
3204 | def magic_pycat(self, parameter_s=''): | |
3206 | """Show a syntax-highlighted file through a pager. |
|
3205 | """Show a syntax-highlighted file through a pager. | |
3207 |
|
3206 | |||
3208 | This magic is similar to the cat utility, but it will assume the file |
|
3207 | This magic is similar to the cat utility, but it will assume the file | |
3209 | to be Python source and will show it with syntax highlighting. """ |
|
3208 | to be Python source and will show it with syntax highlighting. """ | |
3210 |
|
3209 | |||
3211 | try: |
|
3210 | try: | |
3212 | filename = get_py_filename(parameter_s) |
|
3211 | filename = get_py_filename(parameter_s) | |
3213 | cont = file_read(filename) |
|
3212 | cont = file_read(filename) | |
3214 | except IOError: |
|
3213 | except IOError: | |
3215 | try: |
|
3214 | try: | |
3216 | cont = eval(parameter_s,self.user_ns) |
|
3215 | cont = eval(parameter_s,self.user_ns) | |
3217 | except NameError: |
|
3216 | except NameError: | |
3218 | cont = None |
|
3217 | cont = None | |
3219 | if cont is None: |
|
3218 | if cont is None: | |
3220 | print "Error: no such file or variable" |
|
3219 | print "Error: no such file or variable" | |
3221 | return |
|
3220 | return | |
3222 |
|
3221 | |||
3223 | page(self.shell.pycolorize(cont), |
|
3222 | page(self.shell.pycolorize(cont), | |
3224 | screen_lines=self.shell.rc.screen_length) |
|
3223 | screen_lines=self.shell.rc.screen_length) | |
3225 |
|
3224 | |||
3226 | def magic_cpaste(self, parameter_s=''): |
|
3225 | def magic_cpaste(self, parameter_s=''): | |
3227 | """Allows you to paste & execute a pre-formatted code block from clipboard. |
|
3226 | """Allows you to paste & execute a pre-formatted code block from clipboard. | |
3228 |
|
3227 | |||
3229 | You must terminate the block with '--' (two minus-signs) alone on the |
|
3228 | You must terminate the block with '--' (two minus-signs) alone on the | |
3230 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' |
|
3229 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' | |
3231 | is the new sentinel for this operation) |
|
3230 | is the new sentinel for this operation) | |
3232 |
|
3231 | |||
3233 | The block is dedented prior to execution to enable execution of method |
|
3232 | The block is dedented prior to execution to enable execution of method | |
3234 | definitions. '>' and '+' characters at the beginning of a line are |
|
3233 | definitions. '>' and '+' characters at the beginning of a line are | |
3235 | ignored, to allow pasting directly from e-mails, diff files and |
|
3234 | ignored, to allow pasting directly from e-mails, diff files and | |
3236 | doctests (the '...' continuation prompt is also stripped). The |
|
3235 | doctests (the '...' continuation prompt is also stripped). The | |
3237 | executed block is also assigned to variable named 'pasted_block' for |
|
3236 | executed block is also assigned to variable named 'pasted_block' for | |
3238 | later editing with '%edit pasted_block'. |
|
3237 | later editing with '%edit pasted_block'. | |
3239 |
|
3238 | |||
3240 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. |
|
3239 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. | |
3241 | This assigns the pasted block to variable 'foo' as string, without |
|
3240 | This assigns the pasted block to variable 'foo' as string, without | |
3242 | dedenting or executing it (preceding >>> and + is still stripped) |
|
3241 | dedenting or executing it (preceding >>> and + is still stripped) | |
3243 |
|
3242 | |||
3244 | '%cpaste -r' re-executes the block previously entered by cpaste. |
|
3243 | '%cpaste -r' re-executes the block previously entered by cpaste. | |
3245 |
|
3244 | |||
3246 | Do not be alarmed by garbled output on Windows (it's a readline bug). |
|
3245 | Do not be alarmed by garbled output on Windows (it's a readline bug). | |
3247 | Just press enter and type -- (and press enter again) and the block |
|
3246 | Just press enter and type -- (and press enter again) and the block | |
3248 | will be what was just pasted. |
|
3247 | will be what was just pasted. | |
3249 |
|
3248 | |||
3250 | IPython statements (magics, shell escapes) are not supported (yet). |
|
3249 | IPython statements (magics, shell escapes) are not supported (yet). | |
3251 | """ |
|
3250 | """ | |
3252 | opts,args = self.parse_options(parameter_s,'rs:',mode='string') |
|
3251 | opts,args = self.parse_options(parameter_s,'rs:',mode='string') | |
3253 | par = args.strip() |
|
3252 | par = args.strip() | |
3254 | if opts.has_key('r'): |
|
3253 | if opts.has_key('r'): | |
3255 | b = self.user_ns.get('pasted_block', None) |
|
3254 | b = self.user_ns.get('pasted_block', None) | |
3256 | if b is None: |
|
3255 | if b is None: | |
3257 | raise UsageError('No previous pasted block available') |
|
3256 | raise UsageError('No previous pasted block available') | |
3258 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) |
|
3257 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) | |
3259 | exec b in self.user_ns |
|
3258 | exec b in self.user_ns | |
3260 | return |
|
3259 | return | |
3261 |
|
3260 | |||
3262 | sentinel = opts.get('s','--') |
|
3261 | sentinel = opts.get('s','--') | |
3263 |
|
3262 | |||
3264 | # Regular expressions that declare text we strip from the input: |
|
3263 | # Regular expressions that declare text we strip from the input: | |
3265 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt |
|
3264 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt | |
3266 | r'^\s*(\s?>)+', # Python input prompt |
|
3265 | r'^\s*(\s?>)+', # Python input prompt | |
3267 | r'^\s*\.{3,}', # Continuation prompts |
|
3266 | r'^\s*\.{3,}', # Continuation prompts | |
3268 | r'^\++', |
|
3267 | r'^\++', | |
3269 | ] |
|
3268 | ] | |
3270 |
|
3269 | |||
3271 | strip_from_start = map(re.compile,strip_re) |
|
3270 | strip_from_start = map(re.compile,strip_re) | |
3272 |
|
3271 | |||
3273 | from IPython import iplib |
|
3272 | from IPython import iplib | |
3274 | lines = [] |
|
3273 | lines = [] | |
3275 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
3274 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel | |
3276 | while 1: |
|
3275 | while 1: | |
3277 | l = iplib.raw_input_original(':') |
|
3276 | l = iplib.raw_input_original(':') | |
3278 | if l ==sentinel: |
|
3277 | if l ==sentinel: | |
3279 | break |
|
3278 | break | |
3280 |
|
3279 | |||
3281 | for pat in strip_from_start: |
|
3280 | for pat in strip_from_start: | |
3282 | l = pat.sub('',l) |
|
3281 | l = pat.sub('',l) | |
3283 | lines.append(l) |
|
3282 | lines.append(l) | |
3284 |
|
3283 | |||
3285 | block = "\n".join(lines) + '\n' |
|
3284 | block = "\n".join(lines) + '\n' | |
3286 | #print "block:\n",block |
|
3285 | #print "block:\n",block | |
3287 | if not par: |
|
3286 | if not par: | |
3288 | b = textwrap.dedent(block) |
|
3287 | b = textwrap.dedent(block) | |
3289 | self.user_ns['pasted_block'] = b |
|
3288 | self.user_ns['pasted_block'] = b | |
3290 | exec b in self.user_ns |
|
3289 | exec b in self.user_ns | |
3291 | else: |
|
3290 | else: | |
3292 | self.user_ns[par] = SList(block.splitlines()) |
|
3291 | self.user_ns[par] = SList(block.splitlines()) | |
3293 | print "Block assigned to '%s'" % par |
|
3292 | print "Block assigned to '%s'" % par | |
3294 |
|
3293 | |||
3295 | def magic_quickref(self,arg): |
|
3294 | def magic_quickref(self,arg): | |
3296 | """ Show a quick reference sheet """ |
|
3295 | """ Show a quick reference sheet """ | |
3297 | import IPython.usage |
|
3296 | import IPython.usage | |
3298 | qr = IPython.usage.quick_reference + self.magic_magic('-brief') |
|
3297 | qr = IPython.usage.quick_reference + self.magic_magic('-brief') | |
3299 |
|
3298 | |||
3300 | page(qr) |
|
3299 | page(qr) | |
3301 |
|
3300 | |||
3302 | def magic_upgrade(self,arg): |
|
3301 | def magic_upgrade(self,arg): | |
3303 | """ Upgrade your IPython installation |
|
3302 | """ Upgrade your IPython installation | |
3304 |
|
3303 | |||
3305 | This will copy the config files that don't yet exist in your |
|
3304 | This will copy the config files that don't yet exist in your | |
3306 | ipython dir from the system config dir. Use this after upgrading |
|
3305 | ipython dir from the system config dir. Use this after upgrading | |
3307 | IPython if you don't wish to delete your .ipython dir. |
|
3306 | IPython if you don't wish to delete your .ipython dir. | |
3308 |
|
3307 | |||
3309 | Call with -nolegacy to get rid of ipythonrc* files (recommended for |
|
3308 | Call with -nolegacy to get rid of ipythonrc* files (recommended for | |
3310 | new users) |
|
3309 | new users) | |
3311 |
|
3310 | |||
3312 | """ |
|
3311 | """ | |
3313 | ip = self.getapi() |
|
3312 | ip = self.getapi() | |
3314 | ipinstallation = path(IPython.__file__).dirname() |
|
3313 | ipinstallation = path(IPython.__file__).dirname() | |
3315 | upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py') |
|
3314 | upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py') | |
3316 | src_config = ipinstallation / 'UserConfig' |
|
3315 | src_config = ipinstallation / 'UserConfig' | |
3317 | userdir = path(ip.options.ipythondir) |
|
3316 | userdir = path(ip.options.ipythondir) | |
3318 | cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir) |
|
3317 | cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir) | |
3319 | print ">",cmd |
|
3318 | print ">",cmd | |
3320 | shell(cmd) |
|
3319 | shell(cmd) | |
3321 | if arg == '-nolegacy': |
|
3320 | if arg == '-nolegacy': | |
3322 | legacy = userdir.files('ipythonrc*') |
|
3321 | legacy = userdir.files('ipythonrc*') | |
3323 | print "Nuking legacy files:",legacy |
|
3322 | print "Nuking legacy files:",legacy | |
3324 |
|
3323 | |||
3325 | [p.remove() for p in legacy] |
|
3324 | [p.remove() for p in legacy] | |
3326 | suffix = (sys.platform == 'win32' and '.ini' or '') |
|
3325 | suffix = (sys.platform == 'win32' and '.ini' or '') | |
3327 | (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n') |
|
3326 | (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n') | |
3328 |
|
3327 | |||
3329 |
|
3328 | |||
3330 | def magic_doctest_mode(self,parameter_s=''): |
|
3329 | def magic_doctest_mode(self,parameter_s=''): | |
3331 | """Toggle doctest mode on and off. |
|
3330 | """Toggle doctest mode on and off. | |
3332 |
|
3331 | |||
3333 | This mode allows you to toggle the prompt behavior between normal |
|
3332 | This mode allows you to toggle the prompt behavior between normal | |
3334 | IPython prompts and ones that are as similar to the default IPython |
|
3333 | IPython prompts and ones that are as similar to the default IPython | |
3335 | interpreter as possible. |
|
3334 | interpreter as possible. | |
3336 |
|
3335 | |||
3337 | It also supports the pasting of code snippets that have leading '>>>' |
|
3336 | It also supports the pasting of code snippets that have leading '>>>' | |
3338 | and '...' prompts in them. This means that you can paste doctests from |
|
3337 | and '...' prompts in them. This means that you can paste doctests from | |
3339 | files or docstrings (even if they have leading whitespace), and the |
|
3338 | files or docstrings (even if they have leading whitespace), and the | |
3340 | code will execute correctly. You can then use '%history -tn' to see |
|
3339 | code will execute correctly. You can then use '%history -tn' to see | |
3341 | the translated history without line numbers; this will give you the |
|
3340 | the translated history without line numbers; this will give you the | |
3342 | input after removal of all the leading prompts and whitespace, which |
|
3341 | input after removal of all the leading prompts and whitespace, which | |
3343 | can be pasted back into an editor. |
|
3342 | can be pasted back into an editor. | |
3344 |
|
3343 | |||
3345 | With these features, you can switch into this mode easily whenever you |
|
3344 | With these features, you can switch into this mode easily whenever you | |
3346 | need to do testing and changes to doctests, without having to leave |
|
3345 | need to do testing and changes to doctests, without having to leave | |
3347 | your existing IPython session. |
|
3346 | your existing IPython session. | |
3348 | """ |
|
3347 | """ | |
3349 |
|
3348 | |||
3350 | # XXX - Fix this to have cleaner activate/deactivate calls. |
|
3349 | # XXX - Fix this to have cleaner activate/deactivate calls. | |
3351 | from IPython.Extensions import InterpreterPasteInput as ipaste |
|
3350 | from IPython.Extensions import InterpreterPasteInput as ipaste | |
3352 | from IPython.ipstruct import Struct |
|
3351 | from IPython.ipstruct import Struct | |
3353 |
|
3352 | |||
3354 | # Shorthands |
|
3353 | # Shorthands | |
3355 | shell = self.shell |
|
3354 | shell = self.shell | |
3356 | oc = shell.outputcache |
|
3355 | oc = shell.outputcache | |
3357 | rc = shell.rc |
|
3356 | rc = shell.rc | |
3358 | meta = shell.meta |
|
3357 | meta = shell.meta | |
3359 | # dstore is a data store kept in the instance metadata bag to track any |
|
3358 | # dstore is a data store kept in the instance metadata bag to track any | |
3360 | # changes we make, so we can undo them later. |
|
3359 | # changes we make, so we can undo them later. | |
3361 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3360 | dstore = meta.setdefault('doctest_mode',Struct()) | |
3362 | save_dstore = dstore.setdefault |
|
3361 | save_dstore = dstore.setdefault | |
3363 |
|
3362 | |||
3364 | # save a few values we'll need to recover later |
|
3363 | # save a few values we'll need to recover later | |
3365 | mode = save_dstore('mode',False) |
|
3364 | mode = save_dstore('mode',False) | |
3366 | save_dstore('rc_pprint',rc.pprint) |
|
3365 | save_dstore('rc_pprint',rc.pprint) | |
3367 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3366 | save_dstore('xmode',shell.InteractiveTB.mode) | |
3368 | save_dstore('rc_separate_out',rc.separate_out) |
|
3367 | save_dstore('rc_separate_out',rc.separate_out) | |
3369 | save_dstore('rc_separate_out2',rc.separate_out2) |
|
3368 | save_dstore('rc_separate_out2',rc.separate_out2) | |
3370 | save_dstore('rc_prompts_pad_left',rc.prompts_pad_left) |
|
3369 | save_dstore('rc_prompts_pad_left',rc.prompts_pad_left) | |
3371 | save_dstore('rc_separate_in',rc.separate_in) |
|
3370 | save_dstore('rc_separate_in',rc.separate_in) | |
3372 |
|
3371 | |||
3373 | if mode == False: |
|
3372 | if mode == False: | |
3374 | # turn on |
|
3373 | # turn on | |
3375 | ipaste.activate_prefilter() |
|
3374 | ipaste.activate_prefilter() | |
3376 |
|
3375 | |||
3377 | oc.prompt1.p_template = '>>> ' |
|
3376 | oc.prompt1.p_template = '>>> ' | |
3378 | oc.prompt2.p_template = '... ' |
|
3377 | oc.prompt2.p_template = '... ' | |
3379 | oc.prompt_out.p_template = '' |
|
3378 | oc.prompt_out.p_template = '' | |
3380 |
|
3379 | |||
3381 | # Prompt separators like plain python |
|
3380 | # Prompt separators like plain python | |
3382 | oc.input_sep = oc.prompt1.sep = '' |
|
3381 | oc.input_sep = oc.prompt1.sep = '' | |
3383 | oc.output_sep = '' |
|
3382 | oc.output_sep = '' | |
3384 | oc.output_sep2 = '' |
|
3383 | oc.output_sep2 = '' | |
3385 |
|
3384 | |||
3386 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3385 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3387 | oc.prompt_out.pad_left = False |
|
3386 | oc.prompt_out.pad_left = False | |
3388 |
|
3387 | |||
3389 | rc.pprint = False |
|
3388 | rc.pprint = False | |
3390 |
|
3389 | |||
3391 | shell.magic_xmode('Plain') |
|
3390 | shell.magic_xmode('Plain') | |
3392 |
|
3391 | |||
3393 | else: |
|
3392 | else: | |
3394 | # turn off |
|
3393 | # turn off | |
3395 | ipaste.deactivate_prefilter() |
|
3394 | ipaste.deactivate_prefilter() | |
3396 |
|
3395 | |||
3397 | oc.prompt1.p_template = rc.prompt_in1 |
|
3396 | oc.prompt1.p_template = rc.prompt_in1 | |
3398 | oc.prompt2.p_template = rc.prompt_in2 |
|
3397 | oc.prompt2.p_template = rc.prompt_in2 | |
3399 | oc.prompt_out.p_template = rc.prompt_out |
|
3398 | oc.prompt_out.p_template = rc.prompt_out | |
3400 |
|
3399 | |||
3401 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in |
|
3400 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in | |
3402 |
|
3401 | |||
3403 | oc.output_sep = dstore.rc_separate_out |
|
3402 | oc.output_sep = dstore.rc_separate_out | |
3404 | oc.output_sep2 = dstore.rc_separate_out2 |
|
3403 | oc.output_sep2 = dstore.rc_separate_out2 | |
3405 |
|
3404 | |||
3406 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3405 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3407 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left |
|
3406 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left | |
3408 |
|
3407 | |||
3409 | rc.pprint = dstore.rc_pprint |
|
3408 | rc.pprint = dstore.rc_pprint | |
3410 |
|
3409 | |||
3411 | shell.magic_xmode(dstore.xmode) |
|
3410 | shell.magic_xmode(dstore.xmode) | |
3412 |
|
3411 | |||
3413 | # Store new mode and inform |
|
3412 | # Store new mode and inform | |
3414 | dstore.mode = bool(1-int(mode)) |
|
3413 | dstore.mode = bool(1-int(mode)) | |
3415 | print 'Doctest mode is:', |
|
3414 | print 'Doctest mode is:', | |
3416 | print ['OFF','ON'][dstore.mode] |
|
3415 | print ['OFF','ON'][dstore.mode] | |
3417 |
|
3416 | |||
3418 | # end Magic |
|
3417 | # end Magic |
@@ -1,231 +1,229 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 |
|
2 | |||
3 | r""" mglob - enhanced file list expansion module |
|
3 | r""" mglob - enhanced file list expansion module | |
4 |
|
4 | |||
5 | Use as stand-alone utility (for xargs, `backticks` etc.), |
|
5 | Use as stand-alone utility (for xargs, `backticks` etc.), | |
6 | or a globbing library for own python programs. Globbing the sys.argv is something |
|
6 | or a globbing library for own python programs. Globbing the sys.argv is something | |
7 | that almost every Windows script has to perform manually, and this module is here |
|
7 | that almost every Windows script has to perform manually, and this module is here | |
8 | to help with that task. Also Unix users will benefit from enhanced modes |
|
8 | to help with that task. Also Unix users will benefit from enhanced modes | |
9 | such as recursion, exclusion, directory omission... |
|
9 | such as recursion, exclusion, directory omission... | |
10 |
|
10 | |||
11 | Unlike glob.glob, directories are not included in the glob unless specified |
|
11 | Unlike glob.glob, directories are not included in the glob unless specified | |
12 | with 'dir:' |
|
12 | with 'dir:' | |
13 |
|
13 | |||
14 | 'expand' is the function to use in python programs. Typical use |
|
14 | 'expand' is the function to use in python programs. Typical use | |
15 | to expand argv (esp. in windows):: |
|
15 | to expand argv (esp. in windows):: | |
16 |
|
16 | |||
17 | try: |
|
17 | try: | |
18 | import mglob |
|
18 | import mglob | |
19 | files = mglob.expand(sys.argv[1:]) |
|
19 | files = mglob.expand(sys.argv[1:]) | |
20 | except ImportError: |
|
20 | except ImportError: | |
21 | print "mglob not found; try 'easy_install mglob' for extra features" |
|
21 | print "mglob not found; try 'easy_install mglob' for extra features" | |
22 | files = sys.argv[1:] |
|
22 | files = sys.argv[1:] | |
23 |
|
23 | |||
24 | Note that for unix, shell expands *normal* wildcards (*.cpp, etc.) in argv. |
|
24 | Note that for unix, shell expands *normal* wildcards (*.cpp, etc.) in argv. | |
25 | Therefore, you might want to use quotes with normal wildcards to prevent this |
|
25 | Therefore, you might want to use quotes with normal wildcards to prevent this | |
26 | expansion, in order for mglob to see the wildcards and get the wanted behaviour. |
|
26 | expansion, in order for mglob to see the wildcards and get the wanted behaviour. | |
27 | Not quoting the wildcards is harmless and typically has equivalent results, though. |
|
27 | Not quoting the wildcards is harmless and typically has equivalent results, though. | |
28 |
|
28 | |||
29 | Author: Ville Vainio <vivainio@gmail.com> |
|
29 | Author: Ville Vainio <vivainio@gmail.com> | |
30 | License: MIT Open Source license |
|
30 | License: MIT Open Source license | |
31 |
|
31 | |||
32 | """ |
|
32 | """ | |
33 |
|
33 | |||
34 | #Assigned in variable for "usage" printing convenience" |
|
34 | #Assigned in variable for "usage" printing convenience" | |
35 |
|
35 | |||
36 | globsyntax = """\ |
|
36 | globsyntax = """\ | |
37 | This program allows specifying filenames with "mglob" mechanism. |
|
37 | This program allows specifying filenames with "mglob" mechanism. | |
38 | Supported syntax in globs (wilcard matching patterns):: |
|
38 | Supported syntax in globs (wilcard matching patterns):: | |
39 |
|
39 | |||
40 | *.cpp ?ellowo* |
|
40 | *.cpp ?ellowo* | |
41 | - obvious. Differs from normal glob in that dirs are not included. |
|
41 | - obvious. Differs from normal glob in that dirs are not included. | |
42 | Unix users might want to write this as: "*.cpp" "?ellowo*" |
|
42 | Unix users might want to write this as: "*.cpp" "?ellowo*" | |
43 | rec:/usr/share=*.txt,*.doc |
|
43 | rec:/usr/share=*.txt,*.doc | |
44 | - get all *.txt and *.doc under /usr/share, |
|
44 | - get all *.txt and *.doc under /usr/share, | |
45 | recursively |
|
45 | recursively | |
46 | rec:/usr/share |
|
46 | rec:/usr/share | |
47 | - All files under /usr/share, recursively |
|
47 | - All files under /usr/share, recursively | |
48 | rec:*.py |
|
48 | rec:*.py | |
49 | - All .py files under current working dir, recursively |
|
49 | - All .py files under current working dir, recursively | |
50 | foo |
|
50 | foo | |
51 | - File or dir foo |
|
51 | - File or dir foo | |
52 | !*.bak readme* |
|
52 | !*.bak readme* | |
53 | - readme*, exclude files ending with .bak |
|
53 | - readme*, exclude files ending with .bak | |
54 | !.svn/ !.hg/ !*_Data/ rec:. |
|
54 | !.svn/ !.hg/ !*_Data/ rec:. | |
55 | - Skip .svn, .hg, foo_Data dirs (and their subdirs) in recurse. |
|
55 | - Skip .svn, .hg, foo_Data dirs (and their subdirs) in recurse. | |
56 | Trailing / is the key, \ does not work! Use !.*/ for all hidden. |
|
56 | Trailing / is the key, \ does not work! Use !.*/ for all hidden. | |
57 | dir:foo |
|
57 | dir:foo | |
58 | - the directory foo if it exists (not files in foo) |
|
58 | - the directory foo if it exists (not files in foo) | |
59 | dir:* |
|
59 | dir:* | |
60 | - all directories in current folder |
|
60 | - all directories in current folder | |
61 | foo.py bar.* !h* rec:*.py |
|
61 | foo.py bar.* !h* rec:*.py | |
62 | - Obvious. !h* exclusion only applies for rec:*.py. |
|
62 | - Obvious. !h* exclusion only applies for rec:*.py. | |
63 | foo.py is *not* included twice. |
|
63 | foo.py is *not* included twice. | |
64 | @filelist.txt |
|
64 | @filelist.txt | |
65 | - All files listed in 'filelist.txt' file, on separate lines. |
|
65 | - All files listed in 'filelist.txt' file, on separate lines. | |
66 | "cont:class \wak:" rec:*.py |
|
66 | "cont:class \wak:" rec:*.py | |
67 | - Match files containing regexp. Applies to subsequent files. |
|
67 | - Match files containing regexp. Applies to subsequent files. | |
68 | note quotes because of whitespace. |
|
68 | note quotes because of whitespace. | |
69 | """ |
|
69 | """ | |
70 |
|
70 | |||
71 |
|
71 | |||
72 | __version__ = "0.2" |
|
72 | __version__ = "0.2" | |
73 |
|
73 | |||
74 |
|
74 | |||
75 | import os,glob,fnmatch,sys,re |
|
75 | import os,glob,fnmatch,sys,re | |
76 | from sets import Set as set |
|
|||
77 |
|
||||
78 |
|
76 | |||
79 | def expand(flist,exp_dirs = False): |
|
77 | def expand(flist,exp_dirs = False): | |
80 | """ Expand the glob(s) in flist. |
|
78 | """ Expand the glob(s) in flist. | |
81 |
|
79 | |||
82 | flist may be either a whitespace-separated list of globs/files |
|
80 | flist may be either a whitespace-separated list of globs/files | |
83 | or an array of globs/files. |
|
81 | or an array of globs/files. | |
84 |
|
82 | |||
85 | if exp_dirs is true, directory names in glob are expanded to the files |
|
83 | if exp_dirs is true, directory names in glob are expanded to the files | |
86 | contained in them - otherwise, directory names are returned as is. |
|
84 | contained in them - otherwise, directory names are returned as is. | |
87 |
|
85 | |||
88 | """ |
|
86 | """ | |
89 | if isinstance(flist, basestring): |
|
87 | if isinstance(flist, basestring): | |
90 | import shlex |
|
88 | import shlex | |
91 | flist = shlex.split(flist) |
|
89 | flist = shlex.split(flist) | |
92 | done_set = set() |
|
90 | done_set = set() | |
93 | denied_set = set() |
|
91 | denied_set = set() | |
94 | cont_set = set() |
|
92 | cont_set = set() | |
95 | cur_rejected_dirs = set() |
|
93 | cur_rejected_dirs = set() | |
96 |
|
94 | |||
97 | def recfind(p, pats = ["*"]): |
|
95 | def recfind(p, pats = ["*"]): | |
98 | denied_dirs = [os.path.dirname(d) for d in denied_set if d.endswith("/")] |
|
96 | denied_dirs = [os.path.dirname(d) for d in denied_set if d.endswith("/")] | |
99 | for (dp,dnames,fnames) in os.walk(p): |
|
97 | for (dp,dnames,fnames) in os.walk(p): | |
100 | # see if we should ignore the whole directory |
|
98 | # see if we should ignore the whole directory | |
101 | dp_norm = dp.replace("\\","/") + "/" |
|
99 | dp_norm = dp.replace("\\","/") + "/" | |
102 | deny = False |
|
100 | deny = False | |
103 | # do not traverse under already rejected dirs |
|
101 | # do not traverse under already rejected dirs | |
104 | for d in cur_rejected_dirs: |
|
102 | for d in cur_rejected_dirs: | |
105 | if dp.startswith(d): |
|
103 | if dp.startswith(d): | |
106 | deny = True |
|
104 | deny = True | |
107 | break |
|
105 | break | |
108 | if deny: |
|
106 | if deny: | |
109 | continue |
|
107 | continue | |
110 |
|
108 | |||
111 |
|
109 | |||
112 | #print "dp",dp |
|
110 | #print "dp",dp | |
113 | bname = os.path.basename(dp) |
|
111 | bname = os.path.basename(dp) | |
114 | for deny_pat in denied_dirs: |
|
112 | for deny_pat in denied_dirs: | |
115 | if fnmatch.fnmatch( bname, deny_pat): |
|
113 | if fnmatch.fnmatch( bname, deny_pat): | |
116 | deny = True |
|
114 | deny = True | |
117 | cur_rejected_dirs.add(dp) |
|
115 | cur_rejected_dirs.add(dp) | |
118 | break |
|
116 | break | |
119 | if deny: |
|
117 | if deny: | |
120 | continue |
|
118 | continue | |
121 |
|
119 | |||
122 |
|
120 | |||
123 | for f in fnames: |
|
121 | for f in fnames: | |
124 | matched = False |
|
122 | matched = False | |
125 | for p in pats: |
|
123 | for p in pats: | |
126 | if fnmatch.fnmatch(f,p): |
|
124 | if fnmatch.fnmatch(f,p): | |
127 | matched = True |
|
125 | matched = True | |
128 | break |
|
126 | break | |
129 | if matched: |
|
127 | if matched: | |
130 | yield os.path.join(dp,f) |
|
128 | yield os.path.join(dp,f) | |
131 |
|
129 | |||
132 | def once_filter(seq): |
|
130 | def once_filter(seq): | |
133 | for it in seq: |
|
131 | for it in seq: | |
134 | p = os.path.abspath(it) |
|
132 | p = os.path.abspath(it) | |
135 | if p in done_set: |
|
133 | if p in done_set: | |
136 | continue |
|
134 | continue | |
137 | done_set.add(p) |
|
135 | done_set.add(p) | |
138 | deny = False |
|
136 | deny = False | |
139 | for deny_pat in denied_set: |
|
137 | for deny_pat in denied_set: | |
140 | if fnmatch.fnmatch(os.path.basename(p), deny_pat): |
|
138 | if fnmatch.fnmatch(os.path.basename(p), deny_pat): | |
141 | deny = True |
|
139 | deny = True | |
142 | break |
|
140 | break | |
143 | if cont_set: |
|
141 | if cont_set: | |
144 | try: |
|
142 | try: | |
145 | cont = open(p).read() |
|
143 | cont = open(p).read() | |
146 | except IOError: |
|
144 | except IOError: | |
147 | # deny |
|
145 | # deny | |
148 | continue |
|
146 | continue | |
149 | for pat in cont_set: |
|
147 | for pat in cont_set: | |
150 | if not re.search(pat,cont, re.IGNORECASE): |
|
148 | if not re.search(pat,cont, re.IGNORECASE): | |
151 | deny = True |
|
149 | deny = True | |
152 | break |
|
150 | break | |
153 |
|
151 | |||
154 | if not deny: |
|
152 | if not deny: | |
155 | yield it |
|
153 | yield it | |
156 | return |
|
154 | return | |
157 |
|
155 | |||
158 | res = [] |
|
156 | res = [] | |
159 |
|
157 | |||
160 | for ent in flist: |
|
158 | for ent in flist: | |
161 | ent = os.path.expanduser(os.path.expandvars(ent)) |
|
159 | ent = os.path.expanduser(os.path.expandvars(ent)) | |
162 | if ent.lower().startswith('rec:'): |
|
160 | if ent.lower().startswith('rec:'): | |
163 | fields = ent[4:].split('=') |
|
161 | fields = ent[4:].split('=') | |
164 | if len(fields) == 2: |
|
162 | if len(fields) == 2: | |
165 | pth, patlist = fields |
|
163 | pth, patlist = fields | |
166 | elif len(fields) == 1: |
|
164 | elif len(fields) == 1: | |
167 | if os.path.isdir(fields[0]): |
|
165 | if os.path.isdir(fields[0]): | |
168 | # single arg is dir |
|
166 | # single arg is dir | |
169 | pth, patlist = fields[0], '*' |
|
167 | pth, patlist = fields[0], '*' | |
170 | else: |
|
168 | else: | |
171 | # single arg is pattern |
|
169 | # single arg is pattern | |
172 | pth, patlist = '.', fields[0] |
|
170 | pth, patlist = '.', fields[0] | |
173 |
|
171 | |||
174 | elif len(fields) == 0: |
|
172 | elif len(fields) == 0: | |
175 | pth, pathlist = '.','*' |
|
173 | pth, pathlist = '.','*' | |
176 |
|
174 | |||
177 | pats = patlist.split(',') |
|
175 | pats = patlist.split(',') | |
178 | res.extend(once_filter(recfind(pth, pats))) |
|
176 | res.extend(once_filter(recfind(pth, pats))) | |
179 | # filelist |
|
177 | # filelist | |
180 | elif ent.startswith('@') and os.path.isfile(ent[1:]): |
|
178 | elif ent.startswith('@') and os.path.isfile(ent[1:]): | |
181 | res.extend(once_filter(open(ent[1:]).read().splitlines())) |
|
179 | res.extend(once_filter(open(ent[1:]).read().splitlines())) | |
182 | # exclusion |
|
180 | # exclusion | |
183 | elif ent.startswith('!'): |
|
181 | elif ent.startswith('!'): | |
184 | denied_set.add(ent[1:]) |
|
182 | denied_set.add(ent[1:]) | |
185 | # glob only dirs |
|
183 | # glob only dirs | |
186 | elif ent.lower().startswith('dir:'): |
|
184 | elif ent.lower().startswith('dir:'): | |
187 | res.extend(once_filter(filter(os.path.isdir,glob.glob(ent[4:])))) |
|
185 | res.extend(once_filter(filter(os.path.isdir,glob.glob(ent[4:])))) | |
188 | elif ent.lower().startswith('cont:'): |
|
186 | elif ent.lower().startswith('cont:'): | |
189 | cont_set.add(ent[5:]) |
|
187 | cont_set.add(ent[5:]) | |
190 | # get all files in the specified dir |
|
188 | # get all files in the specified dir | |
191 | elif os.path.isdir(ent) and exp_dirs: |
|
189 | elif os.path.isdir(ent) and exp_dirs: | |
192 | res.extend(once_filter(filter(os.path.isfile,glob.glob(ent + os.sep+"*")))) |
|
190 | res.extend(once_filter(filter(os.path.isfile,glob.glob(ent + os.sep+"*")))) | |
193 |
|
191 | |||
194 | # glob only files |
|
192 | # glob only files | |
195 |
|
193 | |||
196 | elif '*' in ent or '?' in ent: |
|
194 | elif '*' in ent or '?' in ent: | |
197 | res.extend(once_filter(filter(os.path.isfile,glob.glob(ent)))) |
|
195 | res.extend(once_filter(filter(os.path.isfile,glob.glob(ent)))) | |
198 |
|
196 | |||
199 | else: |
|
197 | else: | |
200 | res.extend(once_filter([ent])) |
|
198 | res.extend(once_filter([ent])) | |
201 | return res |
|
199 | return res | |
202 |
|
200 | |||
203 |
|
201 | |||
204 | def test(): |
|
202 | def test(): | |
205 | assert ( |
|
203 | assert ( | |
206 | expand("*.py ~/.ipython/*.py rec:/usr/share/doc-base") == |
|
204 | expand("*.py ~/.ipython/*.py rec:/usr/share/doc-base") == | |
207 | expand( ['*.py', '~/.ipython/*.py', 'rec:/usr/share/doc-base'] ) |
|
205 | expand( ['*.py', '~/.ipython/*.py', 'rec:/usr/share/doc-base'] ) | |
208 | ) |
|
206 | ) | |
209 |
|
207 | |||
210 | def main(): |
|
208 | def main(): | |
211 | if len(sys.argv) < 2: |
|
209 | if len(sys.argv) < 2: | |
212 | print globsyntax |
|
210 | print globsyntax | |
213 | return |
|
211 | return | |
214 |
|
212 | |||
215 | print "\n".join(expand(sys.argv[1:])), |
|
213 | print "\n".join(expand(sys.argv[1:])), | |
216 |
|
214 | |||
217 | def mglob_f(self, arg): |
|
215 | def mglob_f(self, arg): | |
218 | from IPython.genutils import SList |
|
216 | from IPython.genutils import SList | |
219 | if arg.strip(): |
|
217 | if arg.strip(): | |
220 | return SList(expand(arg)) |
|
218 | return SList(expand(arg)) | |
221 | print "Please specify pattern!" |
|
219 | print "Please specify pattern!" | |
222 | print globsyntax |
|
220 | print globsyntax | |
223 |
|
221 | |||
224 | def init_ipython(ip): |
|
222 | def init_ipython(ip): | |
225 | """ register %mglob for IPython """ |
|
223 | """ register %mglob for IPython """ | |
226 | mglob_f.__doc__ = globsyntax |
|
224 | mglob_f.__doc__ = globsyntax | |
227 | ip.expose_magic("mglob",mglob_f) |
|
225 | ip.expose_magic("mglob",mglob_f) | |
228 |
|
226 | |||
229 | # test() |
|
227 | # test() | |
230 | if __name__ == "__main__": |
|
228 | if __name__ == "__main__": | |
231 | main() |
|
229 | main() |
@@ -1,2783 +1,2780 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | IPython -- An enhanced Interactive Python |
|
3 | IPython -- An enhanced Interactive Python | |
4 |
|
4 | |||
5 | Requires Python 2.4 or newer. |
|
5 | Requires Python 2.4 or newer. | |
6 |
|
6 | |||
7 | This file contains all the classes and helper functions specific to IPython. |
|
7 | This file contains all the classes and helper functions specific to IPython. | |
8 | """ |
|
8 | """ | |
9 |
|
9 | |||
10 | #***************************************************************************** |
|
10 | #***************************************************************************** | |
11 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
11 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
12 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
|
12 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> | |
13 | # |
|
13 | # | |
14 | # Distributed under the terms of the BSD License. The full license is in |
|
14 | # Distributed under the terms of the BSD License. The full license is in | |
15 | # the file COPYING, distributed as part of this software. |
|
15 | # the file COPYING, distributed as part of this software. | |
16 | # |
|
16 | # | |
17 | # Note: this code originally subclassed code.InteractiveConsole from the |
|
17 | # Note: this code originally subclassed code.InteractiveConsole from the | |
18 | # Python standard library. Over time, all of that class has been copied |
|
18 | # Python standard library. Over time, all of that class has been copied | |
19 | # verbatim here for modifications which could not be accomplished by |
|
19 | # verbatim here for modifications which could not be accomplished by | |
20 | # subclassing. At this point, there are no dependencies at all on the code |
|
20 | # subclassing. At this point, there are no dependencies at all on the code | |
21 | # module anymore (it is not even imported). The Python License (sec. 2) |
|
21 | # module anymore (it is not even imported). The Python License (sec. 2) | |
22 | # allows for this, but it's always nice to acknowledge credit where credit is |
|
22 | # allows for this, but it's always nice to acknowledge credit where credit is | |
23 | # due. |
|
23 | # due. | |
24 | #***************************************************************************** |
|
24 | #***************************************************************************** | |
25 |
|
25 | |||
26 | #**************************************************************************** |
|
26 | #**************************************************************************** | |
27 | # Modules and globals |
|
27 | # Modules and globals | |
28 |
|
28 | |||
29 | # Python standard modules |
|
29 | # Python standard modules | |
30 | import __main__ |
|
30 | import __main__ | |
31 | import __builtin__ |
|
31 | import __builtin__ | |
32 | import StringIO |
|
32 | import StringIO | |
33 | import bdb |
|
33 | import bdb | |
34 | import cPickle as pickle |
|
34 | import cPickle as pickle | |
35 | import codeop |
|
35 | import codeop | |
36 | import exceptions |
|
36 | import exceptions | |
37 | import glob |
|
37 | import glob | |
38 | import inspect |
|
38 | import inspect | |
39 | import keyword |
|
39 | import keyword | |
40 | import new |
|
40 | import new | |
41 | import os |
|
41 | import os | |
42 | import pydoc |
|
42 | import pydoc | |
43 | import re |
|
43 | import re | |
44 | import shutil |
|
44 | import shutil | |
45 | import string |
|
45 | import string | |
46 | import sys |
|
46 | import sys | |
47 | import tempfile |
|
47 | import tempfile | |
48 | import traceback |
|
48 | import traceback | |
49 | import types |
|
49 | import types | |
50 | import warnings |
|
|||
51 | warnings.filterwarnings('ignore', r'.*sets module*') |
|
|||
52 | from sets import Set |
|
|||
53 | from pprint import pprint, pformat |
|
50 | from pprint import pprint, pformat | |
54 |
|
51 | |||
55 | # IPython's own modules |
|
52 | # IPython's own modules | |
56 | #import IPython |
|
53 | #import IPython | |
57 | from IPython import Debugger,OInspect,PyColorize,ultraTB |
|
54 | from IPython import Debugger,OInspect,PyColorize,ultraTB | |
58 | from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names |
|
55 | from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names | |
59 | from IPython.Extensions import pickleshare |
|
56 | from IPython.Extensions import pickleshare | |
60 | from IPython.FakeModule import FakeModule |
|
57 | from IPython.FakeModule import FakeModule | |
61 | from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns |
|
58 | from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns | |
62 | from IPython.Logger import Logger |
|
59 | from IPython.Logger import Logger | |
63 | from IPython.Magic import Magic |
|
60 | from IPython.Magic import Magic | |
64 | from IPython.Prompts import CachedOutput |
|
61 | from IPython.Prompts import CachedOutput | |
65 | from IPython.ipstruct import Struct |
|
62 | from IPython.ipstruct import Struct | |
66 | from IPython.background_jobs import BackgroundJobManager |
|
63 | from IPython.background_jobs import BackgroundJobManager | |
67 | from IPython.usage import cmd_line_usage,interactive_usage |
|
64 | from IPython.usage import cmd_line_usage,interactive_usage | |
68 | from IPython.genutils import * |
|
65 | from IPython.genutils import * | |
69 | from IPython.strdispatch import StrDispatch |
|
66 | from IPython.strdispatch import StrDispatch | |
70 | import IPython.ipapi |
|
67 | import IPython.ipapi | |
71 | import IPython.history |
|
68 | import IPython.history | |
72 | import IPython.prefilter as prefilter |
|
69 | import IPython.prefilter as prefilter | |
73 | import IPython.shadowns |
|
70 | import IPython.shadowns | |
74 | # Globals |
|
71 | # Globals | |
75 |
|
72 | |||
76 | # store the builtin raw_input globally, and use this always, in case user code |
|
73 | # store the builtin raw_input globally, and use this always, in case user code | |
77 | # overwrites it (like wx.py.PyShell does) |
|
74 | # overwrites it (like wx.py.PyShell does) | |
78 | raw_input_original = raw_input |
|
75 | raw_input_original = raw_input | |
79 |
|
76 | |||
80 | # compiled regexps for autoindent management |
|
77 | # compiled regexps for autoindent management | |
81 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
78 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
82 |
|
79 | |||
83 |
|
80 | |||
84 | #**************************************************************************** |
|
81 | #**************************************************************************** | |
85 | # Some utility function definitions |
|
82 | # Some utility function definitions | |
86 |
|
83 | |||
87 | ini_spaces_re = re.compile(r'^(\s+)') |
|
84 | ini_spaces_re = re.compile(r'^(\s+)') | |
88 |
|
85 | |||
89 | def num_ini_spaces(strng): |
|
86 | def num_ini_spaces(strng): | |
90 | """Return the number of initial spaces in a string""" |
|
87 | """Return the number of initial spaces in a string""" | |
91 |
|
88 | |||
92 | ini_spaces = ini_spaces_re.match(strng) |
|
89 | ini_spaces = ini_spaces_re.match(strng) | |
93 | if ini_spaces: |
|
90 | if ini_spaces: | |
94 | return ini_spaces.end() |
|
91 | return ini_spaces.end() | |
95 | else: |
|
92 | else: | |
96 | return 0 |
|
93 | return 0 | |
97 |
|
94 | |||
98 | def softspace(file, newvalue): |
|
95 | def softspace(file, newvalue): | |
99 | """Copied from code.py, to remove the dependency""" |
|
96 | """Copied from code.py, to remove the dependency""" | |
100 |
|
97 | |||
101 | oldvalue = 0 |
|
98 | oldvalue = 0 | |
102 | try: |
|
99 | try: | |
103 | oldvalue = file.softspace |
|
100 | oldvalue = file.softspace | |
104 | except AttributeError: |
|
101 | except AttributeError: | |
105 | pass |
|
102 | pass | |
106 | try: |
|
103 | try: | |
107 | file.softspace = newvalue |
|
104 | file.softspace = newvalue | |
108 | except (AttributeError, TypeError): |
|
105 | except (AttributeError, TypeError): | |
109 | # "attribute-less object" or "read-only attributes" |
|
106 | # "attribute-less object" or "read-only attributes" | |
110 | pass |
|
107 | pass | |
111 | return oldvalue |
|
108 | return oldvalue | |
112 |
|
109 | |||
113 |
|
110 | |||
114 | #**************************************************************************** |
|
111 | #**************************************************************************** | |
115 | # Local use exceptions |
|
112 | # Local use exceptions | |
116 | class SpaceInInput(exceptions.Exception): pass |
|
113 | class SpaceInInput(exceptions.Exception): pass | |
117 |
|
114 | |||
118 |
|
115 | |||
119 | #**************************************************************************** |
|
116 | #**************************************************************************** | |
120 | # Local use classes |
|
117 | # Local use classes | |
121 | class Bunch: pass |
|
118 | class Bunch: pass | |
122 |
|
119 | |||
123 | class Undefined: pass |
|
120 | class Undefined: pass | |
124 |
|
121 | |||
125 | class Quitter(object): |
|
122 | class Quitter(object): | |
126 | """Simple class to handle exit, similar to Python 2.5's. |
|
123 | """Simple class to handle exit, similar to Python 2.5's. | |
127 |
|
124 | |||
128 | It handles exiting in an ipython-safe manner, which the one in Python 2.5 |
|
125 | It handles exiting in an ipython-safe manner, which the one in Python 2.5 | |
129 | doesn't do (obviously, since it doesn't know about ipython).""" |
|
126 | doesn't do (obviously, since it doesn't know about ipython).""" | |
130 |
|
127 | |||
131 | def __init__(self,shell,name): |
|
128 | def __init__(self,shell,name): | |
132 | self.shell = shell |
|
129 | self.shell = shell | |
133 | self.name = name |
|
130 | self.name = name | |
134 |
|
131 | |||
135 | def __repr__(self): |
|
132 | def __repr__(self): | |
136 | return 'Type %s() to exit.' % self.name |
|
133 | return 'Type %s() to exit.' % self.name | |
137 | __str__ = __repr__ |
|
134 | __str__ = __repr__ | |
138 |
|
135 | |||
139 | def __call__(self): |
|
136 | def __call__(self): | |
140 | self.shell.exit() |
|
137 | self.shell.exit() | |
141 |
|
138 | |||
142 | class InputList(list): |
|
139 | class InputList(list): | |
143 | """Class to store user input. |
|
140 | """Class to store user input. | |
144 |
|
141 | |||
145 | It's basically a list, but slices return a string instead of a list, thus |
|
142 | It's basically a list, but slices return a string instead of a list, thus | |
146 | allowing things like (assuming 'In' is an instance): |
|
143 | allowing things like (assuming 'In' is an instance): | |
147 |
|
144 | |||
148 | exec In[4:7] |
|
145 | exec In[4:7] | |
149 |
|
146 | |||
150 | or |
|
147 | or | |
151 |
|
148 | |||
152 | exec In[5:9] + In[14] + In[21:25]""" |
|
149 | exec In[5:9] + In[14] + In[21:25]""" | |
153 |
|
150 | |||
154 | def __getslice__(self,i,j): |
|
151 | def __getslice__(self,i,j): | |
155 | return ''.join(list.__getslice__(self,i,j)) |
|
152 | return ''.join(list.__getslice__(self,i,j)) | |
156 |
|
153 | |||
157 | class SyntaxTB(ultraTB.ListTB): |
|
154 | class SyntaxTB(ultraTB.ListTB): | |
158 | """Extension which holds some state: the last exception value""" |
|
155 | """Extension which holds some state: the last exception value""" | |
159 |
|
156 | |||
160 | def __init__(self,color_scheme = 'NoColor'): |
|
157 | def __init__(self,color_scheme = 'NoColor'): | |
161 | ultraTB.ListTB.__init__(self,color_scheme) |
|
158 | ultraTB.ListTB.__init__(self,color_scheme) | |
162 | self.last_syntax_error = None |
|
159 | self.last_syntax_error = None | |
163 |
|
160 | |||
164 | def __call__(self, etype, value, elist): |
|
161 | def __call__(self, etype, value, elist): | |
165 | self.last_syntax_error = value |
|
162 | self.last_syntax_error = value | |
166 | ultraTB.ListTB.__call__(self,etype,value,elist) |
|
163 | ultraTB.ListTB.__call__(self,etype,value,elist) | |
167 |
|
164 | |||
168 | def clear_err_state(self): |
|
165 | def clear_err_state(self): | |
169 | """Return the current error state and clear it""" |
|
166 | """Return the current error state and clear it""" | |
170 | e = self.last_syntax_error |
|
167 | e = self.last_syntax_error | |
171 | self.last_syntax_error = None |
|
168 | self.last_syntax_error = None | |
172 | return e |
|
169 | return e | |
173 |
|
170 | |||
174 | #**************************************************************************** |
|
171 | #**************************************************************************** | |
175 | # Main IPython class |
|
172 | # Main IPython class | |
176 |
|
173 | |||
177 | # FIXME: the Magic class is a mixin for now, and will unfortunately remain so |
|
174 | # FIXME: the Magic class is a mixin for now, and will unfortunately remain so | |
178 | # until a full rewrite is made. I've cleaned all cross-class uses of |
|
175 | # until a full rewrite is made. I've cleaned all cross-class uses of | |
179 | # attributes and methods, but too much user code out there relies on the |
|
176 | # attributes and methods, but too much user code out there relies on the | |
180 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. |
|
177 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. | |
181 | # |
|
178 | # | |
182 | # But at least now, all the pieces have been separated and we could, in |
|
179 | # But at least now, all the pieces have been separated and we could, in | |
183 | # principle, stop using the mixin. This will ease the transition to the |
|
180 | # principle, stop using the mixin. This will ease the transition to the | |
184 | # chainsaw branch. |
|
181 | # chainsaw branch. | |
185 |
|
182 | |||
186 | # For reference, the following is the list of 'self.foo' uses in the Magic |
|
183 | # For reference, the following is the list of 'self.foo' uses in the Magic | |
187 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython |
|
184 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython | |
188 | # class, to prevent clashes. |
|
185 | # class, to prevent clashes. | |
189 |
|
186 | |||
190 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', |
|
187 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', | |
191 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', |
|
188 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', | |
192 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', |
|
189 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', | |
193 | # 'self.value'] |
|
190 | # 'self.value'] | |
194 |
|
191 | |||
195 | class InteractiveShell(object,Magic): |
|
192 | class InteractiveShell(object,Magic): | |
196 | """An enhanced console for Python.""" |
|
193 | """An enhanced console for Python.""" | |
197 |
|
194 | |||
198 | # class attribute to indicate whether the class supports threads or not. |
|
195 | # class attribute to indicate whether the class supports threads or not. | |
199 | # Subclasses with thread support should override this as needed. |
|
196 | # Subclasses with thread support should override this as needed. | |
200 | isthreaded = False |
|
197 | isthreaded = False | |
201 |
|
198 | |||
202 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
199 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), | |
203 | user_ns=None,user_global_ns=None,banner2='', |
|
200 | user_ns=None,user_global_ns=None,banner2='', | |
204 | custom_exceptions=((),None),embedded=False): |
|
201 | custom_exceptions=((),None),embedded=False): | |
205 |
|
202 | |||
206 | # log system |
|
203 | # log system | |
207 | self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate') |
|
204 | self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate') | |
208 |
|
205 | |||
209 | # Job manager (for jobs run as background threads) |
|
206 | # Job manager (for jobs run as background threads) | |
210 | self.jobs = BackgroundJobManager() |
|
207 | self.jobs = BackgroundJobManager() | |
211 |
|
208 | |||
212 | # Store the actual shell's name |
|
209 | # Store the actual shell's name | |
213 | self.name = name |
|
210 | self.name = name | |
214 | self.more = False |
|
211 | self.more = False | |
215 |
|
212 | |||
216 | # We need to know whether the instance is meant for embedding, since |
|
213 | # We need to know whether the instance is meant for embedding, since | |
217 | # global/local namespaces need to be handled differently in that case |
|
214 | # global/local namespaces need to be handled differently in that case | |
218 | self.embedded = embedded |
|
215 | self.embedded = embedded | |
219 | if embedded: |
|
216 | if embedded: | |
220 | # Control variable so users can, from within the embedded instance, |
|
217 | # Control variable so users can, from within the embedded instance, | |
221 | # permanently deactivate it. |
|
218 | # permanently deactivate it. | |
222 | self.embedded_active = True |
|
219 | self.embedded_active = True | |
223 |
|
220 | |||
224 | # command compiler |
|
221 | # command compiler | |
225 | self.compile = codeop.CommandCompiler() |
|
222 | self.compile = codeop.CommandCompiler() | |
226 |
|
223 | |||
227 | # User input buffer |
|
224 | # User input buffer | |
228 | self.buffer = [] |
|
225 | self.buffer = [] | |
229 |
|
226 | |||
230 | # Default name given in compilation of code |
|
227 | # Default name given in compilation of code | |
231 | self.filename = '<ipython console>' |
|
228 | self.filename = '<ipython console>' | |
232 |
|
229 | |||
233 | # Install our own quitter instead of the builtins. For python2.3-2.4, |
|
230 | # Install our own quitter instead of the builtins. For python2.3-2.4, | |
234 | # this brings in behavior like 2.5, and for 2.5 it's identical. |
|
231 | # this brings in behavior like 2.5, and for 2.5 it's identical. | |
235 | __builtin__.exit = Quitter(self,'exit') |
|
232 | __builtin__.exit = Quitter(self,'exit') | |
236 | __builtin__.quit = Quitter(self,'quit') |
|
233 | __builtin__.quit = Quitter(self,'quit') | |
237 |
|
234 | |||
238 | # Make an empty namespace, which extension writers can rely on both |
|
235 | # Make an empty namespace, which extension writers can rely on both | |
239 | # existing and NEVER being used by ipython itself. This gives them a |
|
236 | # existing and NEVER being used by ipython itself. This gives them a | |
240 | # convenient location for storing additional information and state |
|
237 | # convenient location for storing additional information and state | |
241 | # their extensions may require, without fear of collisions with other |
|
238 | # their extensions may require, without fear of collisions with other | |
242 | # ipython names that may develop later. |
|
239 | # ipython names that may develop later. | |
243 | self.meta = Struct() |
|
240 | self.meta = Struct() | |
244 |
|
241 | |||
245 | # Create the namespace where the user will operate. user_ns is |
|
242 | # Create the namespace where the user will operate. user_ns is | |
246 | # normally the only one used, and it is passed to the exec calls as |
|
243 | # normally the only one used, and it is passed to the exec calls as | |
247 | # the locals argument. But we do carry a user_global_ns namespace |
|
244 | # the locals argument. But we do carry a user_global_ns namespace | |
248 | # given as the exec 'globals' argument, This is useful in embedding |
|
245 | # given as the exec 'globals' argument, This is useful in embedding | |
249 | # situations where the ipython shell opens in a context where the |
|
246 | # situations where the ipython shell opens in a context where the | |
250 | # distinction between locals and globals is meaningful. For |
|
247 | # distinction between locals and globals is meaningful. For | |
251 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
248 | # non-embedded contexts, it is just the same object as the user_ns dict. | |
252 |
|
249 | |||
253 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
250 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
254 | # level as a dict instead of a module. This is a manual fix, but I |
|
251 | # level as a dict instead of a module. This is a manual fix, but I | |
255 | # should really track down where the problem is coming from. Alex |
|
252 | # should really track down where the problem is coming from. Alex | |
256 | # Schmolck reported this problem first. |
|
253 | # Schmolck reported this problem first. | |
257 |
|
254 | |||
258 | # A useful post by Alex Martelli on this topic: |
|
255 | # A useful post by Alex Martelli on this topic: | |
259 | # Re: inconsistent value from __builtins__ |
|
256 | # Re: inconsistent value from __builtins__ | |
260 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
257 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
261 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
258 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
262 | # Gruppen: comp.lang.python |
|
259 | # Gruppen: comp.lang.python | |
263 |
|
260 | |||
264 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
261 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
265 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
262 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
266 | # > <type 'dict'> |
|
263 | # > <type 'dict'> | |
267 | # > >>> print type(__builtins__) |
|
264 | # > >>> print type(__builtins__) | |
268 | # > <type 'module'> |
|
265 | # > <type 'module'> | |
269 | # > Is this difference in return value intentional? |
|
266 | # > Is this difference in return value intentional? | |
270 |
|
267 | |||
271 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
268 | # Well, it's documented that '__builtins__' can be either a dictionary | |
272 | # or a module, and it's been that way for a long time. Whether it's |
|
269 | # or a module, and it's been that way for a long time. Whether it's | |
273 | # intentional (or sensible), I don't know. In any case, the idea is |
|
270 | # intentional (or sensible), I don't know. In any case, the idea is | |
274 | # that if you need to access the built-in namespace directly, you |
|
271 | # that if you need to access the built-in namespace directly, you | |
275 | # should start with "import __builtin__" (note, no 's') which will |
|
272 | # should start with "import __builtin__" (note, no 's') which will | |
276 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
273 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
277 |
|
274 | |||
278 | # These routines return properly built dicts as needed by the rest of |
|
275 | # These routines return properly built dicts as needed by the rest of | |
279 | # the code, and can also be used by extension writers to generate |
|
276 | # the code, and can also be used by extension writers to generate | |
280 | # properly initialized namespaces. |
|
277 | # properly initialized namespaces. | |
281 | user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns, |
|
278 | user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns, | |
282 | user_global_ns) |
|
279 | user_global_ns) | |
283 |
|
280 | |||
284 | # Assign namespaces |
|
281 | # Assign namespaces | |
285 | # This is the namespace where all normal user variables live |
|
282 | # This is the namespace where all normal user variables live | |
286 | self.user_ns = user_ns |
|
283 | self.user_ns = user_ns | |
287 | self.user_global_ns = user_global_ns |
|
284 | self.user_global_ns = user_global_ns | |
288 |
|
285 | |||
289 | # An auxiliary namespace that checks what parts of the user_ns were |
|
286 | # An auxiliary namespace that checks what parts of the user_ns were | |
290 | # loaded at startup, so we can list later only variables defined in |
|
287 | # loaded at startup, so we can list later only variables defined in | |
291 | # actual interactive use. Since it is always a subset of user_ns, it |
|
288 | # actual interactive use. Since it is always a subset of user_ns, it | |
292 | # doesn't need to be seaparately tracked in the ns_table |
|
289 | # doesn't need to be seaparately tracked in the ns_table | |
293 | self.user_config_ns = {} |
|
290 | self.user_config_ns = {} | |
294 |
|
291 | |||
295 | # A namespace to keep track of internal data structures to prevent |
|
292 | # A namespace to keep track of internal data structures to prevent | |
296 | # them from cluttering user-visible stuff. Will be updated later |
|
293 | # them from cluttering user-visible stuff. Will be updated later | |
297 | self.internal_ns = {} |
|
294 | self.internal_ns = {} | |
298 |
|
295 | |||
299 | # Namespace of system aliases. Each entry in the alias |
|
296 | # Namespace of system aliases. Each entry in the alias | |
300 | # table must be a 2-tuple of the form (N,name), where N is the number |
|
297 | # table must be a 2-tuple of the form (N,name), where N is the number | |
301 | # of positional arguments of the alias. |
|
298 | # of positional arguments of the alias. | |
302 | self.alias_table = {} |
|
299 | self.alias_table = {} | |
303 |
|
300 | |||
304 | # Now that FakeModule produces a real module, we've run into a nasty |
|
301 | # Now that FakeModule produces a real module, we've run into a nasty | |
305 | # problem: after script execution (via %run), the module where the user |
|
302 | # problem: after script execution (via %run), the module where the user | |
306 | # code ran is deleted. Now that this object is a true module (needed |
|
303 | # code ran is deleted. Now that this object is a true module (needed | |
307 | # so docetst and other tools work correctly), the Python module |
|
304 | # so docetst and other tools work correctly), the Python module | |
308 | # teardown mechanism runs over it, and sets to None every variable |
|
305 | # teardown mechanism runs over it, and sets to None every variable | |
309 | # present in that module. Top-level references to objects from the |
|
306 | # present in that module. Top-level references to objects from the | |
310 | # script survive, because the user_ns is updated with them. However, |
|
307 | # script survive, because the user_ns is updated with them. However, | |
311 | # calling functions defined in the script that use other things from |
|
308 | # calling functions defined in the script that use other things from | |
312 | # the script will fail, because the function's closure had references |
|
309 | # the script will fail, because the function's closure had references | |
313 | # to the original objects, which are now all None. So we must protect |
|
310 | # to the original objects, which are now all None. So we must protect | |
314 | # these modules from deletion by keeping a cache. To avoid keeping |
|
311 | # these modules from deletion by keeping a cache. To avoid keeping | |
315 | # stale modules around (we only need the one from the last run), we use |
|
312 | # stale modules around (we only need the one from the last run), we use | |
316 | # a dict keyed with the full path to the script, so only the last |
|
313 | # a dict keyed with the full path to the script, so only the last | |
317 | # version of the module is held in the cache. The %reset command will |
|
314 | # version of the module is held in the cache. The %reset command will | |
318 | # flush this cache. See the cache_main_mod() and clear_main_mod_cache() |
|
315 | # flush this cache. See the cache_main_mod() and clear_main_mod_cache() | |
319 | # methods for details on use. |
|
316 | # methods for details on use. | |
320 | self._user_main_modules = {} |
|
317 | self._user_main_modules = {} | |
321 |
|
318 | |||
322 | # A table holding all the namespaces IPython deals with, so that |
|
319 | # A table holding all the namespaces IPython deals with, so that | |
323 | # introspection facilities can search easily. |
|
320 | # introspection facilities can search easily. | |
324 | self.ns_table = {'user':user_ns, |
|
321 | self.ns_table = {'user':user_ns, | |
325 | 'user_global':user_global_ns, |
|
322 | 'user_global':user_global_ns, | |
326 | 'alias':self.alias_table, |
|
323 | 'alias':self.alias_table, | |
327 | 'internal':self.internal_ns, |
|
324 | 'internal':self.internal_ns, | |
328 | 'builtin':__builtin__.__dict__ |
|
325 | 'builtin':__builtin__.__dict__ | |
329 | } |
|
326 | } | |
330 |
|
327 | |||
331 | # Similarly, track all namespaces where references can be held and that |
|
328 | # Similarly, track all namespaces where references can be held and that | |
332 | # we can safely clear (so it can NOT include builtin). This one can be |
|
329 | # we can safely clear (so it can NOT include builtin). This one can be | |
333 | # a simple list. |
|
330 | # a simple list. | |
334 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns, |
|
331 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns, | |
335 | self.alias_table, self.internal_ns, |
|
332 | self.alias_table, self.internal_ns, | |
336 | self._user_main_modules ] |
|
333 | self._user_main_modules ] | |
337 |
|
334 | |||
338 | # We need to insert into sys.modules something that looks like a |
|
335 | # We need to insert into sys.modules something that looks like a | |
339 | # module but which accesses the IPython namespace, for shelve and |
|
336 | # module but which accesses the IPython namespace, for shelve and | |
340 | # pickle to work interactively. Normally they rely on getting |
|
337 | # pickle to work interactively. Normally they rely on getting | |
341 | # everything out of __main__, but for embedding purposes each IPython |
|
338 | # everything out of __main__, but for embedding purposes each IPython | |
342 | # instance has its own private namespace, so we can't go shoving |
|
339 | # instance has its own private namespace, so we can't go shoving | |
343 | # everything into __main__. |
|
340 | # everything into __main__. | |
344 |
|
341 | |||
345 | # note, however, that we should only do this for non-embedded |
|
342 | # note, however, that we should only do this for non-embedded | |
346 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
343 | # ipythons, which really mimic the __main__.__dict__ with their own | |
347 | # namespace. Embedded instances, on the other hand, should not do |
|
344 | # namespace. Embedded instances, on the other hand, should not do | |
348 | # this because they need to manage the user local/global namespaces |
|
345 | # this because they need to manage the user local/global namespaces | |
349 | # only, but they live within a 'normal' __main__ (meaning, they |
|
346 | # only, but they live within a 'normal' __main__ (meaning, they | |
350 | # shouldn't overtake the execution environment of the script they're |
|
347 | # shouldn't overtake the execution environment of the script they're | |
351 | # embedded in). |
|
348 | # embedded in). | |
352 |
|
349 | |||
353 | if not embedded: |
|
350 | if not embedded: | |
354 | try: |
|
351 | try: | |
355 | main_name = self.user_ns['__name__'] |
|
352 | main_name = self.user_ns['__name__'] | |
356 | except KeyError: |
|
353 | except KeyError: | |
357 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' |
|
354 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' | |
358 | else: |
|
355 | else: | |
359 | #print "pickle hack in place" # dbg |
|
356 | #print "pickle hack in place" # dbg | |
360 | #print 'main_name:',main_name # dbg |
|
357 | #print 'main_name:',main_name # dbg | |
361 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
358 | sys.modules[main_name] = FakeModule(self.user_ns) | |
362 |
|
359 | |||
363 | # List of input with multi-line handling. |
|
360 | # List of input with multi-line handling. | |
364 | self.input_hist = InputList() |
|
361 | self.input_hist = InputList() | |
365 | # This one will hold the 'raw' input history, without any |
|
362 | # This one will hold the 'raw' input history, without any | |
366 | # pre-processing. This will allow users to retrieve the input just as |
|
363 | # pre-processing. This will allow users to retrieve the input just as | |
367 | # it was exactly typed in by the user, with %hist -r. |
|
364 | # it was exactly typed in by the user, with %hist -r. | |
368 | self.input_hist_raw = InputList() |
|
365 | self.input_hist_raw = InputList() | |
369 |
|
366 | |||
370 | # list of visited directories |
|
367 | # list of visited directories | |
371 | try: |
|
368 | try: | |
372 | self.dir_hist = [os.getcwd()] |
|
369 | self.dir_hist = [os.getcwd()] | |
373 | except OSError: |
|
370 | except OSError: | |
374 | self.dir_hist = [] |
|
371 | self.dir_hist = [] | |
375 |
|
372 | |||
376 | # dict of output history |
|
373 | # dict of output history | |
377 | self.output_hist = {} |
|
374 | self.output_hist = {} | |
378 |
|
375 | |||
379 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
376 | # Get system encoding at startup time. Certain terminals (like Emacs | |
380 | # under Win32 have it set to None, and we need to have a known valid |
|
377 | # under Win32 have it set to None, and we need to have a known valid | |
381 | # encoding to use in the raw_input() method |
|
378 | # encoding to use in the raw_input() method | |
382 | try: |
|
379 | try: | |
383 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
380 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
384 | except AttributeError: |
|
381 | except AttributeError: | |
385 | self.stdin_encoding = 'ascii' |
|
382 | self.stdin_encoding = 'ascii' | |
386 |
|
383 | |||
387 | # dict of things NOT to alias (keywords, builtins and some magics) |
|
384 | # dict of things NOT to alias (keywords, builtins and some magics) | |
388 | no_alias = {} |
|
385 | no_alias = {} | |
389 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] |
|
386 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] | |
390 | for key in keyword.kwlist + no_alias_magics: |
|
387 | for key in keyword.kwlist + no_alias_magics: | |
391 | no_alias[key] = 1 |
|
388 | no_alias[key] = 1 | |
392 | no_alias.update(__builtin__.__dict__) |
|
389 | no_alias.update(__builtin__.__dict__) | |
393 | self.no_alias = no_alias |
|
390 | self.no_alias = no_alias | |
394 |
|
391 | |||
395 | # Object variable to store code object waiting execution. This is |
|
392 | # Object variable to store code object waiting execution. This is | |
396 | # used mainly by the multithreaded shells, but it can come in handy in |
|
393 | # used mainly by the multithreaded shells, but it can come in handy in | |
397 | # other situations. No need to use a Queue here, since it's a single |
|
394 | # other situations. No need to use a Queue here, since it's a single | |
398 | # item which gets cleared once run. |
|
395 | # item which gets cleared once run. | |
399 | self.code_to_run = None |
|
396 | self.code_to_run = None | |
400 |
|
397 | |||
401 | # escapes for automatic behavior on the command line |
|
398 | # escapes for automatic behavior on the command line | |
402 | self.ESC_SHELL = '!' |
|
399 | self.ESC_SHELL = '!' | |
403 | self.ESC_SH_CAP = '!!' |
|
400 | self.ESC_SH_CAP = '!!' | |
404 | self.ESC_HELP = '?' |
|
401 | self.ESC_HELP = '?' | |
405 | self.ESC_MAGIC = '%' |
|
402 | self.ESC_MAGIC = '%' | |
406 | self.ESC_QUOTE = ',' |
|
403 | self.ESC_QUOTE = ',' | |
407 | self.ESC_QUOTE2 = ';' |
|
404 | self.ESC_QUOTE2 = ';' | |
408 | self.ESC_PAREN = '/' |
|
405 | self.ESC_PAREN = '/' | |
409 |
|
406 | |||
410 | # And their associated handlers |
|
407 | # And their associated handlers | |
411 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, |
|
408 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, | |
412 | self.ESC_QUOTE : self.handle_auto, |
|
409 | self.ESC_QUOTE : self.handle_auto, | |
413 | self.ESC_QUOTE2 : self.handle_auto, |
|
410 | self.ESC_QUOTE2 : self.handle_auto, | |
414 | self.ESC_MAGIC : self.handle_magic, |
|
411 | self.ESC_MAGIC : self.handle_magic, | |
415 | self.ESC_HELP : self.handle_help, |
|
412 | self.ESC_HELP : self.handle_help, | |
416 | self.ESC_SHELL : self.handle_shell_escape, |
|
413 | self.ESC_SHELL : self.handle_shell_escape, | |
417 | self.ESC_SH_CAP : self.handle_shell_escape, |
|
414 | self.ESC_SH_CAP : self.handle_shell_escape, | |
418 | } |
|
415 | } | |
419 |
|
416 | |||
420 | # class initializations |
|
417 | # class initializations | |
421 | Magic.__init__(self,self) |
|
418 | Magic.__init__(self,self) | |
422 |
|
419 | |||
423 | # Python source parser/formatter for syntax highlighting |
|
420 | # Python source parser/formatter for syntax highlighting | |
424 | pyformat = PyColorize.Parser().format |
|
421 | pyformat = PyColorize.Parser().format | |
425 | self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors']) |
|
422 | self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors']) | |
426 |
|
423 | |||
427 | # hooks holds pointers used for user-side customizations |
|
424 | # hooks holds pointers used for user-side customizations | |
428 | self.hooks = Struct() |
|
425 | self.hooks = Struct() | |
429 |
|
426 | |||
430 | self.strdispatchers = {} |
|
427 | self.strdispatchers = {} | |
431 |
|
428 | |||
432 | # Set all default hooks, defined in the IPython.hooks module. |
|
429 | # Set all default hooks, defined in the IPython.hooks module. | |
433 | hooks = IPython.hooks |
|
430 | hooks = IPython.hooks | |
434 | for hook_name in hooks.__all__: |
|
431 | for hook_name in hooks.__all__: | |
435 | # default hooks have priority 100, i.e. low; user hooks should have |
|
432 | # default hooks have priority 100, i.e. low; user hooks should have | |
436 | # 0-100 priority |
|
433 | # 0-100 priority | |
437 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
434 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |
438 | #print "bound hook",hook_name |
|
435 | #print "bound hook",hook_name | |
439 |
|
436 | |||
440 | # Flag to mark unconditional exit |
|
437 | # Flag to mark unconditional exit | |
441 | self.exit_now = False |
|
438 | self.exit_now = False | |
442 |
|
439 | |||
443 | self.usage_min = """\ |
|
440 | self.usage_min = """\ | |
444 | An enhanced console for Python. |
|
441 | An enhanced console for Python. | |
445 | Some of its features are: |
|
442 | Some of its features are: | |
446 | - Readline support if the readline library is present. |
|
443 | - Readline support if the readline library is present. | |
447 | - Tab completion in the local namespace. |
|
444 | - Tab completion in the local namespace. | |
448 | - Logging of input, see command-line options. |
|
445 | - Logging of input, see command-line options. | |
449 | - System shell escape via ! , eg !ls. |
|
446 | - System shell escape via ! , eg !ls. | |
450 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) |
|
447 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) | |
451 | - Keeps track of locally defined variables via %who, %whos. |
|
448 | - Keeps track of locally defined variables via %who, %whos. | |
452 | - Show object information with a ? eg ?x or x? (use ?? for more info). |
|
449 | - Show object information with a ? eg ?x or x? (use ?? for more info). | |
453 | """ |
|
450 | """ | |
454 | if usage: self.usage = usage |
|
451 | if usage: self.usage = usage | |
455 | else: self.usage = self.usage_min |
|
452 | else: self.usage = self.usage_min | |
456 |
|
453 | |||
457 | # Storage |
|
454 | # Storage | |
458 | self.rc = rc # This will hold all configuration information |
|
455 | self.rc = rc # This will hold all configuration information | |
459 | self.pager = 'less' |
|
456 | self.pager = 'less' | |
460 | # temporary files used for various purposes. Deleted at exit. |
|
457 | # temporary files used for various purposes. Deleted at exit. | |
461 | self.tempfiles = [] |
|
458 | self.tempfiles = [] | |
462 |
|
459 | |||
463 | # Keep track of readline usage (later set by init_readline) |
|
460 | # Keep track of readline usage (later set by init_readline) | |
464 | self.has_readline = False |
|
461 | self.has_readline = False | |
465 |
|
462 | |||
466 | # template for logfile headers. It gets resolved at runtime by the |
|
463 | # template for logfile headers. It gets resolved at runtime by the | |
467 | # logstart method. |
|
464 | # logstart method. | |
468 | self.loghead_tpl = \ |
|
465 | self.loghead_tpl = \ | |
469 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** |
|
466 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** | |
470 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW |
|
467 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW | |
471 | #log# opts = %s |
|
468 | #log# opts = %s | |
472 | #log# args = %s |
|
469 | #log# args = %s | |
473 | #log# It is safe to make manual edits below here. |
|
470 | #log# It is safe to make manual edits below here. | |
474 | #log#----------------------------------------------------------------------- |
|
471 | #log#----------------------------------------------------------------------- | |
475 | """ |
|
472 | """ | |
476 | # for pushd/popd management |
|
473 | # for pushd/popd management | |
477 | try: |
|
474 | try: | |
478 | self.home_dir = get_home_dir() |
|
475 | self.home_dir = get_home_dir() | |
479 | except HomeDirError,msg: |
|
476 | except HomeDirError,msg: | |
480 | fatal(msg) |
|
477 | fatal(msg) | |
481 |
|
478 | |||
482 | self.dir_stack = [] |
|
479 | self.dir_stack = [] | |
483 |
|
480 | |||
484 | # Functions to call the underlying shell. |
|
481 | # Functions to call the underlying shell. | |
485 |
|
482 | |||
486 | # The first is similar to os.system, but it doesn't return a value, |
|
483 | # The first is similar to os.system, but it doesn't return a value, | |
487 | # and it allows interpolation of variables in the user's namespace. |
|
484 | # and it allows interpolation of variables in the user's namespace. | |
488 | self.system = lambda cmd: \ |
|
485 | self.system = lambda cmd: \ | |
489 | self.hooks.shell_hook(self.var_expand(cmd,depth=2)) |
|
486 | self.hooks.shell_hook(self.var_expand(cmd,depth=2)) | |
490 |
|
487 | |||
491 | # These are for getoutput and getoutputerror: |
|
488 | # These are for getoutput and getoutputerror: | |
492 | self.getoutput = lambda cmd: \ |
|
489 | self.getoutput = lambda cmd: \ | |
493 | getoutput(self.var_expand(cmd,depth=2), |
|
490 | getoutput(self.var_expand(cmd,depth=2), | |
494 | header=self.rc.system_header, |
|
491 | header=self.rc.system_header, | |
495 | verbose=self.rc.system_verbose) |
|
492 | verbose=self.rc.system_verbose) | |
496 |
|
493 | |||
497 | self.getoutputerror = lambda cmd: \ |
|
494 | self.getoutputerror = lambda cmd: \ | |
498 | getoutputerror(self.var_expand(cmd,depth=2), |
|
495 | getoutputerror(self.var_expand(cmd,depth=2), | |
499 | header=self.rc.system_header, |
|
496 | header=self.rc.system_header, | |
500 | verbose=self.rc.system_verbose) |
|
497 | verbose=self.rc.system_verbose) | |
501 |
|
498 | |||
502 |
|
499 | |||
503 | # keep track of where we started running (mainly for crash post-mortem) |
|
500 | # keep track of where we started running (mainly for crash post-mortem) | |
504 | self.starting_dir = os.getcwd() |
|
501 | self.starting_dir = os.getcwd() | |
505 |
|
502 | |||
506 | # Various switches which can be set |
|
503 | # Various switches which can be set | |
507 | self.CACHELENGTH = 5000 # this is cheap, it's just text |
|
504 | self.CACHELENGTH = 5000 # this is cheap, it's just text | |
508 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ |
|
505 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ | |
509 | self.banner2 = banner2 |
|
506 | self.banner2 = banner2 | |
510 |
|
507 | |||
511 | # TraceBack handlers: |
|
508 | # TraceBack handlers: | |
512 |
|
509 | |||
513 | # Syntax error handler. |
|
510 | # Syntax error handler. | |
514 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') |
|
511 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') | |
515 |
|
512 | |||
516 | # The interactive one is initialized with an offset, meaning we always |
|
513 | # The interactive one is initialized with an offset, meaning we always | |
517 | # want to remove the topmost item in the traceback, which is our own |
|
514 | # want to remove the topmost item in the traceback, which is our own | |
518 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
515 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
519 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', |
|
516 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', | |
520 | color_scheme='NoColor', |
|
517 | color_scheme='NoColor', | |
521 | tb_offset = 1) |
|
518 | tb_offset = 1) | |
522 |
|
519 | |||
523 | # IPython itself shouldn't crash. This will produce a detailed |
|
520 | # IPython itself shouldn't crash. This will produce a detailed | |
524 | # post-mortem if it does. But we only install the crash handler for |
|
521 | # post-mortem if it does. But we only install the crash handler for | |
525 | # non-threaded shells, the threaded ones use a normal verbose reporter |
|
522 | # non-threaded shells, the threaded ones use a normal verbose reporter | |
526 | # and lose the crash handler. This is because exceptions in the main |
|
523 | # and lose the crash handler. This is because exceptions in the main | |
527 | # thread (such as in GUI code) propagate directly to sys.excepthook, |
|
524 | # thread (such as in GUI code) propagate directly to sys.excepthook, | |
528 | # and there's no point in printing crash dumps for every user exception. |
|
525 | # and there's no point in printing crash dumps for every user exception. | |
529 | if self.isthreaded: |
|
526 | if self.isthreaded: | |
530 | ipCrashHandler = ultraTB.FormattedTB() |
|
527 | ipCrashHandler = ultraTB.FormattedTB() | |
531 | else: |
|
528 | else: | |
532 | from IPython import CrashHandler |
|
529 | from IPython import CrashHandler | |
533 | ipCrashHandler = CrashHandler.IPythonCrashHandler(self) |
|
530 | ipCrashHandler = CrashHandler.IPythonCrashHandler(self) | |
534 | self.set_crash_handler(ipCrashHandler) |
|
531 | self.set_crash_handler(ipCrashHandler) | |
535 |
|
532 | |||
536 | # and add any custom exception handlers the user may have specified |
|
533 | # and add any custom exception handlers the user may have specified | |
537 | self.set_custom_exc(*custom_exceptions) |
|
534 | self.set_custom_exc(*custom_exceptions) | |
538 |
|
535 | |||
539 | # indentation management |
|
536 | # indentation management | |
540 | self.autoindent = False |
|
537 | self.autoindent = False | |
541 | self.indent_current_nsp = 0 |
|
538 | self.indent_current_nsp = 0 | |
542 |
|
539 | |||
543 | # Make some aliases automatically |
|
540 | # Make some aliases automatically | |
544 | # Prepare list of shell aliases to auto-define |
|
541 | # Prepare list of shell aliases to auto-define | |
545 | if os.name == 'posix': |
|
542 | if os.name == 'posix': | |
546 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', |
|
543 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', | |
547 | 'mv mv -i','rm rm -i','cp cp -i', |
|
544 | 'mv mv -i','rm rm -i','cp cp -i', | |
548 | 'cat cat','less less','clear clear', |
|
545 | 'cat cat','less less','clear clear', | |
549 | # a better ls |
|
546 | # a better ls | |
550 | 'ls ls -F', |
|
547 | 'ls ls -F', | |
551 | # long ls |
|
548 | # long ls | |
552 | 'll ls -lF') |
|
549 | 'll ls -lF') | |
553 | # Extra ls aliases with color, which need special treatment on BSD |
|
550 | # Extra ls aliases with color, which need special treatment on BSD | |
554 | # variants |
|
551 | # variants | |
555 | ls_extra = ( # color ls |
|
552 | ls_extra = ( # color ls | |
556 | 'lc ls -F -o --color', |
|
553 | 'lc ls -F -o --color', | |
557 | # ls normal files only |
|
554 | # ls normal files only | |
558 | 'lf ls -F -o --color %l | grep ^-', |
|
555 | 'lf ls -F -o --color %l | grep ^-', | |
559 | # ls symbolic links |
|
556 | # ls symbolic links | |
560 | 'lk ls -F -o --color %l | grep ^l', |
|
557 | 'lk ls -F -o --color %l | grep ^l', | |
561 | # directories or links to directories, |
|
558 | # directories or links to directories, | |
562 | 'ldir ls -F -o --color %l | grep /$', |
|
559 | 'ldir ls -F -o --color %l | grep /$', | |
563 | # things which are executable |
|
560 | # things which are executable | |
564 | 'lx ls -F -o --color %l | grep ^-..x', |
|
561 | 'lx ls -F -o --color %l | grep ^-..x', | |
565 | ) |
|
562 | ) | |
566 | # The BSDs don't ship GNU ls, so they don't understand the |
|
563 | # The BSDs don't ship GNU ls, so they don't understand the | |
567 | # --color switch out of the box |
|
564 | # --color switch out of the box | |
568 | if 'bsd' in sys.platform: |
|
565 | if 'bsd' in sys.platform: | |
569 | ls_extra = ( # ls normal files only |
|
566 | ls_extra = ( # ls normal files only | |
570 | 'lf ls -lF | grep ^-', |
|
567 | 'lf ls -lF | grep ^-', | |
571 | # ls symbolic links |
|
568 | # ls symbolic links | |
572 | 'lk ls -lF | grep ^l', |
|
569 | 'lk ls -lF | grep ^l', | |
573 | # directories or links to directories, |
|
570 | # directories or links to directories, | |
574 | 'ldir ls -lF | grep /$', |
|
571 | 'ldir ls -lF | grep /$', | |
575 | # things which are executable |
|
572 | # things which are executable | |
576 | 'lx ls -lF | grep ^-..x', |
|
573 | 'lx ls -lF | grep ^-..x', | |
577 | ) |
|
574 | ) | |
578 | auto_alias = auto_alias + ls_extra |
|
575 | auto_alias = auto_alias + ls_extra | |
579 | elif os.name in ['nt','dos']: |
|
576 | elif os.name in ['nt','dos']: | |
580 | auto_alias = ('ls dir /on', |
|
577 | auto_alias = ('ls dir /on', | |
581 | 'ddir dir /ad /on', 'ldir dir /ad /on', |
|
578 | 'ddir dir /ad /on', 'ldir dir /ad /on', | |
582 | 'mkdir mkdir','rmdir rmdir','echo echo', |
|
579 | 'mkdir mkdir','rmdir rmdir','echo echo', | |
583 | 'ren ren','cls cls','copy copy') |
|
580 | 'ren ren','cls cls','copy copy') | |
584 | else: |
|
581 | else: | |
585 | auto_alias = () |
|
582 | auto_alias = () | |
586 | self.auto_alias = [s.split(None,1) for s in auto_alias] |
|
583 | self.auto_alias = [s.split(None,1) for s in auto_alias] | |
587 |
|
584 | |||
588 | # Produce a public API instance |
|
585 | # Produce a public API instance | |
589 | self.api = IPython.ipapi.IPApi(self) |
|
586 | self.api = IPython.ipapi.IPApi(self) | |
590 |
|
587 | |||
591 | # Initialize all user-visible namespaces |
|
588 | # Initialize all user-visible namespaces | |
592 | self.init_namespaces() |
|
589 | self.init_namespaces() | |
593 |
|
590 | |||
594 | # Call the actual (public) initializer |
|
591 | # Call the actual (public) initializer | |
595 | self.init_auto_alias() |
|
592 | self.init_auto_alias() | |
596 |
|
593 | |||
597 | # track which builtins we add, so we can clean up later |
|
594 | # track which builtins we add, so we can clean up later | |
598 | self.builtins_added = {} |
|
595 | self.builtins_added = {} | |
599 | # This method will add the necessary builtins for operation, but |
|
596 | # This method will add the necessary builtins for operation, but | |
600 | # tracking what it did via the builtins_added dict. |
|
597 | # tracking what it did via the builtins_added dict. | |
601 |
|
598 | |||
602 | #TODO: remove this, redundant |
|
599 | #TODO: remove this, redundant | |
603 | self.add_builtins() |
|
600 | self.add_builtins() | |
604 | # end __init__ |
|
601 | # end __init__ | |
605 |
|
602 | |||
606 | def var_expand(self,cmd,depth=0): |
|
603 | def var_expand(self,cmd,depth=0): | |
607 | """Expand python variables in a string. |
|
604 | """Expand python variables in a string. | |
608 |
|
605 | |||
609 | The depth argument indicates how many frames above the caller should |
|
606 | The depth argument indicates how many frames above the caller should | |
610 | be walked to look for the local namespace where to expand variables. |
|
607 | be walked to look for the local namespace where to expand variables. | |
611 |
|
608 | |||
612 | The global namespace for expansion is always the user's interactive |
|
609 | The global namespace for expansion is always the user's interactive | |
613 | namespace. |
|
610 | namespace. | |
614 | """ |
|
611 | """ | |
615 |
|
612 | |||
616 | return str(ItplNS(cmd, |
|
613 | return str(ItplNS(cmd, | |
617 | self.user_ns, # globals |
|
614 | self.user_ns, # globals | |
618 | # Skip our own frame in searching for locals: |
|
615 | # Skip our own frame in searching for locals: | |
619 | sys._getframe(depth+1).f_locals # locals |
|
616 | sys._getframe(depth+1).f_locals # locals | |
620 | )) |
|
617 | )) | |
621 |
|
618 | |||
622 | def pre_config_initialization(self): |
|
619 | def pre_config_initialization(self): | |
623 | """Pre-configuration init method |
|
620 | """Pre-configuration init method | |
624 |
|
621 | |||
625 | This is called before the configuration files are processed to |
|
622 | This is called before the configuration files are processed to | |
626 | prepare the services the config files might need. |
|
623 | prepare the services the config files might need. | |
627 |
|
624 | |||
628 | self.rc already has reasonable default values at this point. |
|
625 | self.rc already has reasonable default values at this point. | |
629 | """ |
|
626 | """ | |
630 | rc = self.rc |
|
627 | rc = self.rc | |
631 | try: |
|
628 | try: | |
632 | self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db") |
|
629 | self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db") | |
633 | except exceptions.UnicodeDecodeError: |
|
630 | except exceptions.UnicodeDecodeError: | |
634 | print "Your ipythondir can't be decoded to unicode!" |
|
631 | print "Your ipythondir can't be decoded to unicode!" | |
635 | print "Please set HOME environment variable to something that" |
|
632 | print "Please set HOME environment variable to something that" | |
636 | print r"only has ASCII characters, e.g. c:\home" |
|
633 | print r"only has ASCII characters, e.g. c:\home" | |
637 | print "Now it is",rc.ipythondir |
|
634 | print "Now it is",rc.ipythondir | |
638 | sys.exit() |
|
635 | sys.exit() | |
639 | self.shadowhist = IPython.history.ShadowHist(self.db) |
|
636 | self.shadowhist = IPython.history.ShadowHist(self.db) | |
640 |
|
637 | |||
641 | def post_config_initialization(self): |
|
638 | def post_config_initialization(self): | |
642 | """Post configuration init method |
|
639 | """Post configuration init method | |
643 |
|
640 | |||
644 | This is called after the configuration files have been processed to |
|
641 | This is called after the configuration files have been processed to | |
645 | 'finalize' the initialization.""" |
|
642 | 'finalize' the initialization.""" | |
646 |
|
643 | |||
647 | rc = self.rc |
|
644 | rc = self.rc | |
648 |
|
645 | |||
649 | # Object inspector |
|
646 | # Object inspector | |
650 | self.inspector = OInspect.Inspector(OInspect.InspectColors, |
|
647 | self.inspector = OInspect.Inspector(OInspect.InspectColors, | |
651 | PyColorize.ANSICodeColors, |
|
648 | PyColorize.ANSICodeColors, | |
652 | 'NoColor', |
|
649 | 'NoColor', | |
653 | rc.object_info_string_level) |
|
650 | rc.object_info_string_level) | |
654 |
|
651 | |||
655 | self.rl_next_input = None |
|
652 | self.rl_next_input = None | |
656 | self.rl_do_indent = False |
|
653 | self.rl_do_indent = False | |
657 | # Load readline proper |
|
654 | # Load readline proper | |
658 | if rc.readline: |
|
655 | if rc.readline: | |
659 | self.init_readline() |
|
656 | self.init_readline() | |
660 |
|
657 | |||
661 | # local shortcut, this is used a LOT |
|
658 | # local shortcut, this is used a LOT | |
662 | self.log = self.logger.log |
|
659 | self.log = self.logger.log | |
663 |
|
660 | |||
664 | # Initialize cache, set in/out prompts and printing system |
|
661 | # Initialize cache, set in/out prompts and printing system | |
665 | self.outputcache = CachedOutput(self, |
|
662 | self.outputcache = CachedOutput(self, | |
666 | rc.cache_size, |
|
663 | rc.cache_size, | |
667 | rc.pprint, |
|
664 | rc.pprint, | |
668 | input_sep = rc.separate_in, |
|
665 | input_sep = rc.separate_in, | |
669 | output_sep = rc.separate_out, |
|
666 | output_sep = rc.separate_out, | |
670 | output_sep2 = rc.separate_out2, |
|
667 | output_sep2 = rc.separate_out2, | |
671 | ps1 = rc.prompt_in1, |
|
668 | ps1 = rc.prompt_in1, | |
672 | ps2 = rc.prompt_in2, |
|
669 | ps2 = rc.prompt_in2, | |
673 | ps_out = rc.prompt_out, |
|
670 | ps_out = rc.prompt_out, | |
674 | pad_left = rc.prompts_pad_left) |
|
671 | pad_left = rc.prompts_pad_left) | |
675 |
|
672 | |||
676 | # user may have over-ridden the default print hook: |
|
673 | # user may have over-ridden the default print hook: | |
677 | try: |
|
674 | try: | |
678 | self.outputcache.__class__.display = self.hooks.display |
|
675 | self.outputcache.__class__.display = self.hooks.display | |
679 | except AttributeError: |
|
676 | except AttributeError: | |
680 | pass |
|
677 | pass | |
681 |
|
678 | |||
682 | # I don't like assigning globally to sys, because it means when |
|
679 | # I don't like assigning globally to sys, because it means when | |
683 | # embedding instances, each embedded instance overrides the previous |
|
680 | # embedding instances, each embedded instance overrides the previous | |
684 | # choice. But sys.displayhook seems to be called internally by exec, |
|
681 | # choice. But sys.displayhook seems to be called internally by exec, | |
685 | # so I don't see a way around it. We first save the original and then |
|
682 | # so I don't see a way around it. We first save the original and then | |
686 | # overwrite it. |
|
683 | # overwrite it. | |
687 | self.sys_displayhook = sys.displayhook |
|
684 | self.sys_displayhook = sys.displayhook | |
688 | sys.displayhook = self.outputcache |
|
685 | sys.displayhook = self.outputcache | |
689 |
|
686 | |||
690 | # Do a proper resetting of doctest, including the necessary displayhook |
|
687 | # Do a proper resetting of doctest, including the necessary displayhook | |
691 | # monkeypatching |
|
688 | # monkeypatching | |
692 | try: |
|
689 | try: | |
693 | doctest_reload() |
|
690 | doctest_reload() | |
694 | except ImportError: |
|
691 | except ImportError: | |
695 | warn("doctest module does not exist.") |
|
692 | warn("doctest module does not exist.") | |
696 |
|
693 | |||
697 | # Set user colors (don't do it in the constructor above so that it |
|
694 | # Set user colors (don't do it in the constructor above so that it | |
698 | # doesn't crash if colors option is invalid) |
|
695 | # doesn't crash if colors option is invalid) | |
699 | self.magic_colors(rc.colors) |
|
696 | self.magic_colors(rc.colors) | |
700 |
|
697 | |||
701 | # Set calling of pdb on exceptions |
|
698 | # Set calling of pdb on exceptions | |
702 | self.call_pdb = rc.pdb |
|
699 | self.call_pdb = rc.pdb | |
703 |
|
700 | |||
704 | # Load user aliases |
|
701 | # Load user aliases | |
705 | for alias in rc.alias: |
|
702 | for alias in rc.alias: | |
706 | self.magic_alias(alias) |
|
703 | self.magic_alias(alias) | |
707 |
|
704 | |||
708 | self.hooks.late_startup_hook() |
|
705 | self.hooks.late_startup_hook() | |
709 |
|
706 | |||
710 | for cmd in self.rc.autoexec: |
|
707 | for cmd in self.rc.autoexec: | |
711 | #print "autoexec>",cmd #dbg |
|
708 | #print "autoexec>",cmd #dbg | |
712 | self.api.runlines(cmd) |
|
709 | self.api.runlines(cmd) | |
713 |
|
710 | |||
714 | batchrun = False |
|
711 | batchrun = False | |
715 | for batchfile in [path(arg) for arg in self.rc.args |
|
712 | for batchfile in [path(arg) for arg in self.rc.args | |
716 | if arg.lower().endswith('.ipy')]: |
|
713 | if arg.lower().endswith('.ipy')]: | |
717 | if not batchfile.isfile(): |
|
714 | if not batchfile.isfile(): | |
718 | print "No such batch file:", batchfile |
|
715 | print "No such batch file:", batchfile | |
719 | continue |
|
716 | continue | |
720 | self.api.runlines(batchfile.text()) |
|
717 | self.api.runlines(batchfile.text()) | |
721 | batchrun = True |
|
718 | batchrun = True | |
722 | # without -i option, exit after running the batch file |
|
719 | # without -i option, exit after running the batch file | |
723 | if batchrun and not self.rc.interact: |
|
720 | if batchrun and not self.rc.interact: | |
724 | self.ask_exit() |
|
721 | self.ask_exit() | |
725 |
|
722 | |||
726 | def init_namespaces(self): |
|
723 | def init_namespaces(self): | |
727 | """Initialize all user-visible namespaces to their minimum defaults. |
|
724 | """Initialize all user-visible namespaces to their minimum defaults. | |
728 |
|
725 | |||
729 | Certain history lists are also initialized here, as they effectively |
|
726 | Certain history lists are also initialized here, as they effectively | |
730 | act as user namespaces. |
|
727 | act as user namespaces. | |
731 |
|
728 | |||
732 | Note |
|
729 | Note | |
733 | ---- |
|
730 | ---- | |
734 | All data structures here are only filled in, they are NOT reset by this |
|
731 | All data structures here are only filled in, they are NOT reset by this | |
735 | method. If they were not empty before, data will simply be added to |
|
732 | method. If they were not empty before, data will simply be added to | |
736 | therm. |
|
733 | therm. | |
737 | """ |
|
734 | """ | |
738 | # The user namespace MUST have a pointer to the shell itself. |
|
735 | # The user namespace MUST have a pointer to the shell itself. | |
739 | self.user_ns[self.name] = self |
|
736 | self.user_ns[self.name] = self | |
740 |
|
737 | |||
741 | # Store the public api instance |
|
738 | # Store the public api instance | |
742 | self.user_ns['_ip'] = self.api |
|
739 | self.user_ns['_ip'] = self.api | |
743 |
|
740 | |||
744 | # make global variables for user access to the histories |
|
741 | # make global variables for user access to the histories | |
745 | self.user_ns['_ih'] = self.input_hist |
|
742 | self.user_ns['_ih'] = self.input_hist | |
746 | self.user_ns['_oh'] = self.output_hist |
|
743 | self.user_ns['_oh'] = self.output_hist | |
747 | self.user_ns['_dh'] = self.dir_hist |
|
744 | self.user_ns['_dh'] = self.dir_hist | |
748 |
|
745 | |||
749 | # user aliases to input and output histories |
|
746 | # user aliases to input and output histories | |
750 | self.user_ns['In'] = self.input_hist |
|
747 | self.user_ns['In'] = self.input_hist | |
751 | self.user_ns['Out'] = self.output_hist |
|
748 | self.user_ns['Out'] = self.output_hist | |
752 |
|
749 | |||
753 | self.user_ns['_sh'] = IPython.shadowns |
|
750 | self.user_ns['_sh'] = IPython.shadowns | |
754 |
|
751 | |||
755 | # Fill the history zero entry, user counter starts at 1 |
|
752 | # Fill the history zero entry, user counter starts at 1 | |
756 | self.input_hist.append('\n') |
|
753 | self.input_hist.append('\n') | |
757 | self.input_hist_raw.append('\n') |
|
754 | self.input_hist_raw.append('\n') | |
758 |
|
755 | |||
759 | def add_builtins(self): |
|
756 | def add_builtins(self): | |
760 | """Store ipython references into the builtin namespace. |
|
757 | """Store ipython references into the builtin namespace. | |
761 |
|
758 | |||
762 | Some parts of ipython operate via builtins injected here, which hold a |
|
759 | Some parts of ipython operate via builtins injected here, which hold a | |
763 | reference to IPython itself.""" |
|
760 | reference to IPython itself.""" | |
764 |
|
761 | |||
765 | # TODO: deprecate all of these, they are unsafe |
|
762 | # TODO: deprecate all of these, they are unsafe | |
766 | builtins_new = dict(__IPYTHON__ = self, |
|
763 | builtins_new = dict(__IPYTHON__ = self, | |
767 | ip_set_hook = self.set_hook, |
|
764 | ip_set_hook = self.set_hook, | |
768 | jobs = self.jobs, |
|
765 | jobs = self.jobs, | |
769 | ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'), |
|
766 | ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'), | |
770 | ipalias = wrap_deprecated(self.ipalias), |
|
767 | ipalias = wrap_deprecated(self.ipalias), | |
771 | ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'), |
|
768 | ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'), | |
772 | #_ip = self.api |
|
769 | #_ip = self.api | |
773 | ) |
|
770 | ) | |
774 | for biname,bival in builtins_new.items(): |
|
771 | for biname,bival in builtins_new.items(): | |
775 | try: |
|
772 | try: | |
776 | # store the orignal value so we can restore it |
|
773 | # store the orignal value so we can restore it | |
777 | self.builtins_added[biname] = __builtin__.__dict__[biname] |
|
774 | self.builtins_added[biname] = __builtin__.__dict__[biname] | |
778 | except KeyError: |
|
775 | except KeyError: | |
779 | # or mark that it wasn't defined, and we'll just delete it at |
|
776 | # or mark that it wasn't defined, and we'll just delete it at | |
780 | # cleanup |
|
777 | # cleanup | |
781 | self.builtins_added[biname] = Undefined |
|
778 | self.builtins_added[biname] = Undefined | |
782 | __builtin__.__dict__[biname] = bival |
|
779 | __builtin__.__dict__[biname] = bival | |
783 |
|
780 | |||
784 | # Keep in the builtins a flag for when IPython is active. We set it |
|
781 | # Keep in the builtins a flag for when IPython is active. We set it | |
785 | # with setdefault so that multiple nested IPythons don't clobber one |
|
782 | # with setdefault so that multiple nested IPythons don't clobber one | |
786 | # another. Each will increase its value by one upon being activated, |
|
783 | # another. Each will increase its value by one upon being activated, | |
787 | # which also gives us a way to determine the nesting level. |
|
784 | # which also gives us a way to determine the nesting level. | |
788 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) |
|
785 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) | |
789 |
|
786 | |||
790 | def clean_builtins(self): |
|
787 | def clean_builtins(self): | |
791 | """Remove any builtins which might have been added by add_builtins, or |
|
788 | """Remove any builtins which might have been added by add_builtins, or | |
792 | restore overwritten ones to their previous values.""" |
|
789 | restore overwritten ones to their previous values.""" | |
793 | for biname,bival in self.builtins_added.items(): |
|
790 | for biname,bival in self.builtins_added.items(): | |
794 | if bival is Undefined: |
|
791 | if bival is Undefined: | |
795 | del __builtin__.__dict__[biname] |
|
792 | del __builtin__.__dict__[biname] | |
796 | else: |
|
793 | else: | |
797 | __builtin__.__dict__[biname] = bival |
|
794 | __builtin__.__dict__[biname] = bival | |
798 | self.builtins_added.clear() |
|
795 | self.builtins_added.clear() | |
799 |
|
796 | |||
800 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
797 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): | |
801 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
798 | """set_hook(name,hook) -> sets an internal IPython hook. | |
802 |
|
799 | |||
803 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
800 | IPython exposes some of its internal API as user-modifiable hooks. By | |
804 | adding your function to one of these hooks, you can modify IPython's |
|
801 | adding your function to one of these hooks, you can modify IPython's | |
805 | behavior to call at runtime your own routines.""" |
|
802 | behavior to call at runtime your own routines.""" | |
806 |
|
803 | |||
807 | # At some point in the future, this should validate the hook before it |
|
804 | # At some point in the future, this should validate the hook before it | |
808 | # accepts it. Probably at least check that the hook takes the number |
|
805 | # accepts it. Probably at least check that the hook takes the number | |
809 | # of args it's supposed to. |
|
806 | # of args it's supposed to. | |
810 |
|
807 | |||
811 | f = new.instancemethod(hook,self,self.__class__) |
|
808 | f = new.instancemethod(hook,self,self.__class__) | |
812 |
|
809 | |||
813 | # check if the hook is for strdispatcher first |
|
810 | # check if the hook is for strdispatcher first | |
814 | if str_key is not None: |
|
811 | if str_key is not None: | |
815 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
812 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
816 | sdp.add_s(str_key, f, priority ) |
|
813 | sdp.add_s(str_key, f, priority ) | |
817 | self.strdispatchers[name] = sdp |
|
814 | self.strdispatchers[name] = sdp | |
818 | return |
|
815 | return | |
819 | if re_key is not None: |
|
816 | if re_key is not None: | |
820 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
817 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
821 | sdp.add_re(re.compile(re_key), f, priority ) |
|
818 | sdp.add_re(re.compile(re_key), f, priority ) | |
822 | self.strdispatchers[name] = sdp |
|
819 | self.strdispatchers[name] = sdp | |
823 | return |
|
820 | return | |
824 |
|
821 | |||
825 | dp = getattr(self.hooks, name, None) |
|
822 | dp = getattr(self.hooks, name, None) | |
826 | if name not in IPython.hooks.__all__: |
|
823 | if name not in IPython.hooks.__all__: | |
827 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ ) |
|
824 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ ) | |
828 | if not dp: |
|
825 | if not dp: | |
829 | dp = IPython.hooks.CommandChainDispatcher() |
|
826 | dp = IPython.hooks.CommandChainDispatcher() | |
830 |
|
827 | |||
831 | try: |
|
828 | try: | |
832 | dp.add(f,priority) |
|
829 | dp.add(f,priority) | |
833 | except AttributeError: |
|
830 | except AttributeError: | |
834 | # it was not commandchain, plain old func - replace |
|
831 | # it was not commandchain, plain old func - replace | |
835 | dp = f |
|
832 | dp = f | |
836 |
|
833 | |||
837 | setattr(self.hooks,name, dp) |
|
834 | setattr(self.hooks,name, dp) | |
838 |
|
835 | |||
839 |
|
836 | |||
840 | #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) |
|
837 | #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) | |
841 |
|
838 | |||
842 | def set_crash_handler(self,crashHandler): |
|
839 | def set_crash_handler(self,crashHandler): | |
843 | """Set the IPython crash handler. |
|
840 | """Set the IPython crash handler. | |
844 |
|
841 | |||
845 | This must be a callable with a signature suitable for use as |
|
842 | This must be a callable with a signature suitable for use as | |
846 | sys.excepthook.""" |
|
843 | sys.excepthook.""" | |
847 |
|
844 | |||
848 | # Install the given crash handler as the Python exception hook |
|
845 | # Install the given crash handler as the Python exception hook | |
849 | sys.excepthook = crashHandler |
|
846 | sys.excepthook = crashHandler | |
850 |
|
847 | |||
851 | # The instance will store a pointer to this, so that runtime code |
|
848 | # The instance will store a pointer to this, so that runtime code | |
852 | # (such as magics) can access it. This is because during the |
|
849 | # (such as magics) can access it. This is because during the | |
853 | # read-eval loop, it gets temporarily overwritten (to deal with GUI |
|
850 | # read-eval loop, it gets temporarily overwritten (to deal with GUI | |
854 | # frameworks). |
|
851 | # frameworks). | |
855 | self.sys_excepthook = sys.excepthook |
|
852 | self.sys_excepthook = sys.excepthook | |
856 |
|
853 | |||
857 |
|
854 | |||
858 | def set_custom_exc(self,exc_tuple,handler): |
|
855 | def set_custom_exc(self,exc_tuple,handler): | |
859 | """set_custom_exc(exc_tuple,handler) |
|
856 | """set_custom_exc(exc_tuple,handler) | |
860 |
|
857 | |||
861 | Set a custom exception handler, which will be called if any of the |
|
858 | Set a custom exception handler, which will be called if any of the | |
862 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
859 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
863 | runcode() method. |
|
860 | runcode() method. | |
864 |
|
861 | |||
865 | Inputs: |
|
862 | Inputs: | |
866 |
|
863 | |||
867 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
864 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
868 | handler for. It is very important that you use a tuple, and NOT A |
|
865 | handler for. It is very important that you use a tuple, and NOT A | |
869 | LIST here, because of the way Python's except statement works. If |
|
866 | LIST here, because of the way Python's except statement works. If | |
870 | you only want to trap a single exception, use a singleton tuple: |
|
867 | you only want to trap a single exception, use a singleton tuple: | |
871 |
|
868 | |||
872 | exc_tuple == (MyCustomException,) |
|
869 | exc_tuple == (MyCustomException,) | |
873 |
|
870 | |||
874 | - handler: this must be defined as a function with the following |
|
871 | - handler: this must be defined as a function with the following | |
875 | basic interface: def my_handler(self,etype,value,tb). |
|
872 | basic interface: def my_handler(self,etype,value,tb). | |
876 |
|
873 | |||
877 | This will be made into an instance method (via new.instancemethod) |
|
874 | This will be made into an instance method (via new.instancemethod) | |
878 | of IPython itself, and it will be called if any of the exceptions |
|
875 | of IPython itself, and it will be called if any of the exceptions | |
879 | listed in the exc_tuple are caught. If the handler is None, an |
|
876 | listed in the exc_tuple are caught. If the handler is None, an | |
880 | internal basic one is used, which just prints basic info. |
|
877 | internal basic one is used, which just prints basic info. | |
881 |
|
878 | |||
882 | WARNING: by putting in your own exception handler into IPython's main |
|
879 | WARNING: by putting in your own exception handler into IPython's main | |
883 | execution loop, you run a very good chance of nasty crashes. This |
|
880 | execution loop, you run a very good chance of nasty crashes. This | |
884 | facility should only be used if you really know what you are doing.""" |
|
881 | facility should only be used if you really know what you are doing.""" | |
885 |
|
882 | |||
886 | assert type(exc_tuple)==type(()) , \ |
|
883 | assert type(exc_tuple)==type(()) , \ | |
887 | "The custom exceptions must be given AS A TUPLE." |
|
884 | "The custom exceptions must be given AS A TUPLE." | |
888 |
|
885 | |||
889 | def dummy_handler(self,etype,value,tb): |
|
886 | def dummy_handler(self,etype,value,tb): | |
890 | print '*** Simple custom exception handler ***' |
|
887 | print '*** Simple custom exception handler ***' | |
891 | print 'Exception type :',etype |
|
888 | print 'Exception type :',etype | |
892 | print 'Exception value:',value |
|
889 | print 'Exception value:',value | |
893 | print 'Traceback :',tb |
|
890 | print 'Traceback :',tb | |
894 | print 'Source code :','\n'.join(self.buffer) |
|
891 | print 'Source code :','\n'.join(self.buffer) | |
895 |
|
892 | |||
896 | if handler is None: handler = dummy_handler |
|
893 | if handler is None: handler = dummy_handler | |
897 |
|
894 | |||
898 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
895 | self.CustomTB = new.instancemethod(handler,self,self.__class__) | |
899 | self.custom_exceptions = exc_tuple |
|
896 | self.custom_exceptions = exc_tuple | |
900 |
|
897 | |||
901 | def set_custom_completer(self,completer,pos=0): |
|
898 | def set_custom_completer(self,completer,pos=0): | |
902 | """set_custom_completer(completer,pos=0) |
|
899 | """set_custom_completer(completer,pos=0) | |
903 |
|
900 | |||
904 | Adds a new custom completer function. |
|
901 | Adds a new custom completer function. | |
905 |
|
902 | |||
906 | The position argument (defaults to 0) is the index in the completers |
|
903 | The position argument (defaults to 0) is the index in the completers | |
907 | list where you want the completer to be inserted.""" |
|
904 | list where you want the completer to be inserted.""" | |
908 |
|
905 | |||
909 | newcomp = new.instancemethod(completer,self.Completer, |
|
906 | newcomp = new.instancemethod(completer,self.Completer, | |
910 | self.Completer.__class__) |
|
907 | self.Completer.__class__) | |
911 | self.Completer.matchers.insert(pos,newcomp) |
|
908 | self.Completer.matchers.insert(pos,newcomp) | |
912 |
|
909 | |||
913 | def set_completer(self): |
|
910 | def set_completer(self): | |
914 | """reset readline's completer to be our own.""" |
|
911 | """reset readline's completer to be our own.""" | |
915 | self.readline.set_completer(self.Completer.complete) |
|
912 | self.readline.set_completer(self.Completer.complete) | |
916 |
|
913 | |||
917 | def _get_call_pdb(self): |
|
914 | def _get_call_pdb(self): | |
918 | return self._call_pdb |
|
915 | return self._call_pdb | |
919 |
|
916 | |||
920 | def _set_call_pdb(self,val): |
|
917 | def _set_call_pdb(self,val): | |
921 |
|
918 | |||
922 | if val not in (0,1,False,True): |
|
919 | if val not in (0,1,False,True): | |
923 | raise ValueError,'new call_pdb value must be boolean' |
|
920 | raise ValueError,'new call_pdb value must be boolean' | |
924 |
|
921 | |||
925 | # store value in instance |
|
922 | # store value in instance | |
926 | self._call_pdb = val |
|
923 | self._call_pdb = val | |
927 |
|
924 | |||
928 | # notify the actual exception handlers |
|
925 | # notify the actual exception handlers | |
929 | self.InteractiveTB.call_pdb = val |
|
926 | self.InteractiveTB.call_pdb = val | |
930 | if self.isthreaded: |
|
927 | if self.isthreaded: | |
931 | try: |
|
928 | try: | |
932 | self.sys_excepthook.call_pdb = val |
|
929 | self.sys_excepthook.call_pdb = val | |
933 | except: |
|
930 | except: | |
934 | warn('Failed to activate pdb for threaded exception handler') |
|
931 | warn('Failed to activate pdb for threaded exception handler') | |
935 |
|
932 | |||
936 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
933 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
937 | 'Control auto-activation of pdb at exceptions') |
|
934 | 'Control auto-activation of pdb at exceptions') | |
938 |
|
935 | |||
939 | # These special functions get installed in the builtin namespace, to |
|
936 | # These special functions get installed in the builtin namespace, to | |
940 | # provide programmatic (pure python) access to magics, aliases and system |
|
937 | # provide programmatic (pure python) access to magics, aliases and system | |
941 | # calls. This is important for logging, user scripting, and more. |
|
938 | # calls. This is important for logging, user scripting, and more. | |
942 |
|
939 | |||
943 | # We are basically exposing, via normal python functions, the three |
|
940 | # We are basically exposing, via normal python functions, the three | |
944 | # mechanisms in which ipython offers special call modes (magics for |
|
941 | # mechanisms in which ipython offers special call modes (magics for | |
945 | # internal control, aliases for direct system access via pre-selected |
|
942 | # internal control, aliases for direct system access via pre-selected | |
946 | # names, and !cmd for calling arbitrary system commands). |
|
943 | # names, and !cmd for calling arbitrary system commands). | |
947 |
|
944 | |||
948 | def ipmagic(self,arg_s): |
|
945 | def ipmagic(self,arg_s): | |
949 | """Call a magic function by name. |
|
946 | """Call a magic function by name. | |
950 |
|
947 | |||
951 | Input: a string containing the name of the magic function to call and any |
|
948 | Input: a string containing the name of the magic function to call and any | |
952 | additional arguments to be passed to the magic. |
|
949 | additional arguments to be passed to the magic. | |
953 |
|
950 | |||
954 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython |
|
951 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython | |
955 | prompt: |
|
952 | prompt: | |
956 |
|
953 | |||
957 | In[1]: %name -opt foo bar |
|
954 | In[1]: %name -opt foo bar | |
958 |
|
955 | |||
959 | To call a magic without arguments, simply use ipmagic('name'). |
|
956 | To call a magic without arguments, simply use ipmagic('name'). | |
960 |
|
957 | |||
961 | This provides a proper Python function to call IPython's magics in any |
|
958 | This provides a proper Python function to call IPython's magics in any | |
962 | valid Python code you can type at the interpreter, including loops and |
|
959 | valid Python code you can type at the interpreter, including loops and | |
963 | compound statements. It is added by IPython to the Python builtin |
|
960 | compound statements. It is added by IPython to the Python builtin | |
964 | namespace upon initialization.""" |
|
961 | namespace upon initialization.""" | |
965 |
|
962 | |||
966 | args = arg_s.split(' ',1) |
|
963 | args = arg_s.split(' ',1) | |
967 | magic_name = args[0] |
|
964 | magic_name = args[0] | |
968 | magic_name = magic_name.lstrip(self.ESC_MAGIC) |
|
965 | magic_name = magic_name.lstrip(self.ESC_MAGIC) | |
969 |
|
966 | |||
970 | try: |
|
967 | try: | |
971 | magic_args = args[1] |
|
968 | magic_args = args[1] | |
972 | except IndexError: |
|
969 | except IndexError: | |
973 | magic_args = '' |
|
970 | magic_args = '' | |
974 | fn = getattr(self,'magic_'+magic_name,None) |
|
971 | fn = getattr(self,'magic_'+magic_name,None) | |
975 | if fn is None: |
|
972 | if fn is None: | |
976 | error("Magic function `%s` not found." % magic_name) |
|
973 | error("Magic function `%s` not found." % magic_name) | |
977 | else: |
|
974 | else: | |
978 | magic_args = self.var_expand(magic_args,1) |
|
975 | magic_args = self.var_expand(magic_args,1) | |
979 | return fn(magic_args) |
|
976 | return fn(magic_args) | |
980 |
|
977 | |||
981 | def ipalias(self,arg_s): |
|
978 | def ipalias(self,arg_s): | |
982 | """Call an alias by name. |
|
979 | """Call an alias by name. | |
983 |
|
980 | |||
984 | Input: a string containing the name of the alias to call and any |
|
981 | Input: a string containing the name of the alias to call and any | |
985 | additional arguments to be passed to the magic. |
|
982 | additional arguments to be passed to the magic. | |
986 |
|
983 | |||
987 | ipalias('name -opt foo bar') is equivalent to typing at the ipython |
|
984 | ipalias('name -opt foo bar') is equivalent to typing at the ipython | |
988 | prompt: |
|
985 | prompt: | |
989 |
|
986 | |||
990 | In[1]: name -opt foo bar |
|
987 | In[1]: name -opt foo bar | |
991 |
|
988 | |||
992 | To call an alias without arguments, simply use ipalias('name'). |
|
989 | To call an alias without arguments, simply use ipalias('name'). | |
993 |
|
990 | |||
994 | This provides a proper Python function to call IPython's aliases in any |
|
991 | This provides a proper Python function to call IPython's aliases in any | |
995 | valid Python code you can type at the interpreter, including loops and |
|
992 | valid Python code you can type at the interpreter, including loops and | |
996 | compound statements. It is added by IPython to the Python builtin |
|
993 | compound statements. It is added by IPython to the Python builtin | |
997 | namespace upon initialization.""" |
|
994 | namespace upon initialization.""" | |
998 |
|
995 | |||
999 | args = arg_s.split(' ',1) |
|
996 | args = arg_s.split(' ',1) | |
1000 | alias_name = args[0] |
|
997 | alias_name = args[0] | |
1001 | try: |
|
998 | try: | |
1002 | alias_args = args[1] |
|
999 | alias_args = args[1] | |
1003 | except IndexError: |
|
1000 | except IndexError: | |
1004 | alias_args = '' |
|
1001 | alias_args = '' | |
1005 | if alias_name in self.alias_table: |
|
1002 | if alias_name in self.alias_table: | |
1006 | self.call_alias(alias_name,alias_args) |
|
1003 | self.call_alias(alias_name,alias_args) | |
1007 | else: |
|
1004 | else: | |
1008 | error("Alias `%s` not found." % alias_name) |
|
1005 | error("Alias `%s` not found." % alias_name) | |
1009 |
|
1006 | |||
1010 | def ipsystem(self,arg_s): |
|
1007 | def ipsystem(self,arg_s): | |
1011 | """Make a system call, using IPython.""" |
|
1008 | """Make a system call, using IPython.""" | |
1012 |
|
1009 | |||
1013 | self.system(arg_s) |
|
1010 | self.system(arg_s) | |
1014 |
|
1011 | |||
1015 | def complete(self,text): |
|
1012 | def complete(self,text): | |
1016 | """Return a sorted list of all possible completions on text. |
|
1013 | """Return a sorted list of all possible completions on text. | |
1017 |
|
1014 | |||
1018 | Inputs: |
|
1015 | Inputs: | |
1019 |
|
1016 | |||
1020 | - text: a string of text to be completed on. |
|
1017 | - text: a string of text to be completed on. | |
1021 |
|
1018 | |||
1022 | This is a wrapper around the completion mechanism, similar to what |
|
1019 | This is a wrapper around the completion mechanism, similar to what | |
1023 | readline does at the command line when the TAB key is hit. By |
|
1020 | readline does at the command line when the TAB key is hit. By | |
1024 | exposing it as a method, it can be used by other non-readline |
|
1021 | exposing it as a method, it can be used by other non-readline | |
1025 | environments (such as GUIs) for text completion. |
|
1022 | environments (such as GUIs) for text completion. | |
1026 |
|
1023 | |||
1027 | Simple usage example: |
|
1024 | Simple usage example: | |
1028 |
|
1025 | |||
1029 | In [7]: x = 'hello' |
|
1026 | In [7]: x = 'hello' | |
1030 |
|
1027 | |||
1031 | In [8]: x |
|
1028 | In [8]: x | |
1032 | Out[8]: 'hello' |
|
1029 | Out[8]: 'hello' | |
1033 |
|
1030 | |||
1034 | In [9]: print x |
|
1031 | In [9]: print x | |
1035 | hello |
|
1032 | hello | |
1036 |
|
1033 | |||
1037 | In [10]: _ip.IP.complete('x.l') |
|
1034 | In [10]: _ip.IP.complete('x.l') | |
1038 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] |
|
1035 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] | |
1039 | """ |
|
1036 | """ | |
1040 |
|
1037 | |||
1041 | complete = self.Completer.complete |
|
1038 | complete = self.Completer.complete | |
1042 | state = 0 |
|
1039 | state = 0 | |
1043 | # use a dict so we get unique keys, since ipyhton's multiple |
|
1040 | # use a dict so we get unique keys, since ipyhton's multiple | |
1044 | # completers can return duplicates. When we make 2.4 a requirement, |
|
1041 | # completers can return duplicates. When we make 2.4 a requirement, | |
1045 | # start using sets instead, which are faster. |
|
1042 | # start using sets instead, which are faster. | |
1046 | comps = {} |
|
1043 | comps = {} | |
1047 | while True: |
|
1044 | while True: | |
1048 | newcomp = complete(text,state,line_buffer=text) |
|
1045 | newcomp = complete(text,state,line_buffer=text) | |
1049 | if newcomp is None: |
|
1046 | if newcomp is None: | |
1050 | break |
|
1047 | break | |
1051 | comps[newcomp] = 1 |
|
1048 | comps[newcomp] = 1 | |
1052 | state += 1 |
|
1049 | state += 1 | |
1053 | outcomps = comps.keys() |
|
1050 | outcomps = comps.keys() | |
1054 | outcomps.sort() |
|
1051 | outcomps.sort() | |
1055 | #print "T:",text,"OC:",outcomps # dbg |
|
1052 | #print "T:",text,"OC:",outcomps # dbg | |
1056 | #print "vars:",self.user_ns.keys() |
|
1053 | #print "vars:",self.user_ns.keys() | |
1057 | return outcomps |
|
1054 | return outcomps | |
1058 |
|
1055 | |||
1059 | def set_completer_frame(self, frame=None): |
|
1056 | def set_completer_frame(self, frame=None): | |
1060 | if frame: |
|
1057 | if frame: | |
1061 | self.Completer.namespace = frame.f_locals |
|
1058 | self.Completer.namespace = frame.f_locals | |
1062 | self.Completer.global_namespace = frame.f_globals |
|
1059 | self.Completer.global_namespace = frame.f_globals | |
1063 | else: |
|
1060 | else: | |
1064 | self.Completer.namespace = self.user_ns |
|
1061 | self.Completer.namespace = self.user_ns | |
1065 | self.Completer.global_namespace = self.user_global_ns |
|
1062 | self.Completer.global_namespace = self.user_global_ns | |
1066 |
|
1063 | |||
1067 | def init_auto_alias(self): |
|
1064 | def init_auto_alias(self): | |
1068 | """Define some aliases automatically. |
|
1065 | """Define some aliases automatically. | |
1069 |
|
1066 | |||
1070 | These are ALL parameter-less aliases""" |
|
1067 | These are ALL parameter-less aliases""" | |
1071 |
|
1068 | |||
1072 | for alias,cmd in self.auto_alias: |
|
1069 | for alias,cmd in self.auto_alias: | |
1073 | self.getapi().defalias(alias,cmd) |
|
1070 | self.getapi().defalias(alias,cmd) | |
1074 |
|
1071 | |||
1075 |
|
1072 | |||
1076 | def alias_table_validate(self,verbose=0): |
|
1073 | def alias_table_validate(self,verbose=0): | |
1077 | """Update information about the alias table. |
|
1074 | """Update information about the alias table. | |
1078 |
|
1075 | |||
1079 | In particular, make sure no Python keywords/builtins are in it.""" |
|
1076 | In particular, make sure no Python keywords/builtins are in it.""" | |
1080 |
|
1077 | |||
1081 | no_alias = self.no_alias |
|
1078 | no_alias = self.no_alias | |
1082 | for k in self.alias_table.keys(): |
|
1079 | for k in self.alias_table.keys(): | |
1083 | if k in no_alias: |
|
1080 | if k in no_alias: | |
1084 | del self.alias_table[k] |
|
1081 | del self.alias_table[k] | |
1085 | if verbose: |
|
1082 | if verbose: | |
1086 | print ("Deleting alias <%s>, it's a Python " |
|
1083 | print ("Deleting alias <%s>, it's a Python " | |
1087 | "keyword or builtin." % k) |
|
1084 | "keyword or builtin." % k) | |
1088 |
|
1085 | |||
1089 | def set_autoindent(self,value=None): |
|
1086 | def set_autoindent(self,value=None): | |
1090 | """Set the autoindent flag, checking for readline support. |
|
1087 | """Set the autoindent flag, checking for readline support. | |
1091 |
|
1088 | |||
1092 | If called with no arguments, it acts as a toggle.""" |
|
1089 | If called with no arguments, it acts as a toggle.""" | |
1093 |
|
1090 | |||
1094 | if not self.has_readline: |
|
1091 | if not self.has_readline: | |
1095 | if os.name == 'posix': |
|
1092 | if os.name == 'posix': | |
1096 | warn("The auto-indent feature requires the readline library") |
|
1093 | warn("The auto-indent feature requires the readline library") | |
1097 | self.autoindent = 0 |
|
1094 | self.autoindent = 0 | |
1098 | return |
|
1095 | return | |
1099 | if value is None: |
|
1096 | if value is None: | |
1100 | self.autoindent = not self.autoindent |
|
1097 | self.autoindent = not self.autoindent | |
1101 | else: |
|
1098 | else: | |
1102 | self.autoindent = value |
|
1099 | self.autoindent = value | |
1103 |
|
1100 | |||
1104 | def rc_set_toggle(self,rc_field,value=None): |
|
1101 | def rc_set_toggle(self,rc_field,value=None): | |
1105 | """Set or toggle a field in IPython's rc config. structure. |
|
1102 | """Set or toggle a field in IPython's rc config. structure. | |
1106 |
|
1103 | |||
1107 | If called with no arguments, it acts as a toggle. |
|
1104 | If called with no arguments, it acts as a toggle. | |
1108 |
|
1105 | |||
1109 | If called with a non-existent field, the resulting AttributeError |
|
1106 | If called with a non-existent field, the resulting AttributeError | |
1110 | exception will propagate out.""" |
|
1107 | exception will propagate out.""" | |
1111 |
|
1108 | |||
1112 | rc_val = getattr(self.rc,rc_field) |
|
1109 | rc_val = getattr(self.rc,rc_field) | |
1113 | if value is None: |
|
1110 | if value is None: | |
1114 | value = not rc_val |
|
1111 | value = not rc_val | |
1115 | setattr(self.rc,rc_field,value) |
|
1112 | setattr(self.rc,rc_field,value) | |
1116 |
|
1113 | |||
1117 | def user_setup(self,ipythondir,rc_suffix,mode='install'): |
|
1114 | def user_setup(self,ipythondir,rc_suffix,mode='install'): | |
1118 | """Install the user configuration directory. |
|
1115 | """Install the user configuration directory. | |
1119 |
|
1116 | |||
1120 | Can be called when running for the first time or to upgrade the user's |
|
1117 | Can be called when running for the first time or to upgrade the user's | |
1121 | .ipython/ directory with the mode parameter. Valid modes are 'install' |
|
1118 | .ipython/ directory with the mode parameter. Valid modes are 'install' | |
1122 | and 'upgrade'.""" |
|
1119 | and 'upgrade'.""" | |
1123 |
|
1120 | |||
1124 | def wait(): |
|
1121 | def wait(): | |
1125 | try: |
|
1122 | try: | |
1126 | raw_input("Please press <RETURN> to start IPython.") |
|
1123 | raw_input("Please press <RETURN> to start IPython.") | |
1127 | except EOFError: |
|
1124 | except EOFError: | |
1128 | print >> Term.cout |
|
1125 | print >> Term.cout | |
1129 | print '*'*70 |
|
1126 | print '*'*70 | |
1130 |
|
1127 | |||
1131 | cwd = os.getcwd() # remember where we started |
|
1128 | cwd = os.getcwd() # remember where we started | |
1132 | glb = glob.glob |
|
1129 | glb = glob.glob | |
1133 | print '*'*70 |
|
1130 | print '*'*70 | |
1134 | if mode == 'install': |
|
1131 | if mode == 'install': | |
1135 | print \ |
|
1132 | print \ | |
1136 | """Welcome to IPython. I will try to create a personal configuration directory |
|
1133 | """Welcome to IPython. I will try to create a personal configuration directory | |
1137 | where you can customize many aspects of IPython's functionality in:\n""" |
|
1134 | where you can customize many aspects of IPython's functionality in:\n""" | |
1138 | else: |
|
1135 | else: | |
1139 | print 'I am going to upgrade your configuration in:' |
|
1136 | print 'I am going to upgrade your configuration in:' | |
1140 |
|
1137 | |||
1141 | print ipythondir |
|
1138 | print ipythondir | |
1142 |
|
1139 | |||
1143 | rcdirend = os.path.join('IPython','UserConfig') |
|
1140 | rcdirend = os.path.join('IPython','UserConfig') | |
1144 | cfg = lambda d: os.path.join(d,rcdirend) |
|
1141 | cfg = lambda d: os.path.join(d,rcdirend) | |
1145 | try: |
|
1142 | try: | |
1146 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] |
|
1143 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] | |
1147 | print "Initializing from configuration",rcdir |
|
1144 | print "Initializing from configuration",rcdir | |
1148 | except IndexError: |
|
1145 | except IndexError: | |
1149 | warning = """ |
|
1146 | warning = """ | |
1150 | Installation error. IPython's directory was not found. |
|
1147 | Installation error. IPython's directory was not found. | |
1151 |
|
1148 | |||
1152 | Check the following: |
|
1149 | Check the following: | |
1153 |
|
1150 | |||
1154 | The ipython/IPython directory should be in a directory belonging to your |
|
1151 | The ipython/IPython directory should be in a directory belonging to your | |
1155 | PYTHONPATH environment variable (that is, it should be in a directory |
|
1152 | PYTHONPATH environment variable (that is, it should be in a directory | |
1156 | belonging to sys.path). You can copy it explicitly there or just link to it. |
|
1153 | belonging to sys.path). You can copy it explicitly there or just link to it. | |
1157 |
|
1154 | |||
1158 | IPython will create a minimal default configuration for you. |
|
1155 | IPython will create a minimal default configuration for you. | |
1159 |
|
1156 | |||
1160 | """ |
|
1157 | """ | |
1161 | warn(warning) |
|
1158 | warn(warning) | |
1162 | wait() |
|
1159 | wait() | |
1163 |
|
1160 | |||
1164 | if sys.platform =='win32': |
|
1161 | if sys.platform =='win32': | |
1165 | inif = 'ipythonrc.ini' |
|
1162 | inif = 'ipythonrc.ini' | |
1166 | else: |
|
1163 | else: | |
1167 | inif = 'ipythonrc' |
|
1164 | inif = 'ipythonrc' | |
1168 | minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', |
|
1165 | minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', | |
1169 | inif : '# intentionally left blank' } |
|
1166 | inif : '# intentionally left blank' } | |
1170 | os.makedirs(ipythondir, mode = 0777) |
|
1167 | os.makedirs(ipythondir, mode = 0777) | |
1171 | for f, cont in minimal_setup.items(): |
|
1168 | for f, cont in minimal_setup.items(): | |
1172 | open(ipythondir + '/' + f,'w').write(cont) |
|
1169 | open(ipythondir + '/' + f,'w').write(cont) | |
1173 |
|
1170 | |||
1174 | return |
|
1171 | return | |
1175 |
|
1172 | |||
1176 | if mode == 'install': |
|
1173 | if mode == 'install': | |
1177 | try: |
|
1174 | try: | |
1178 | shutil.copytree(rcdir,ipythondir) |
|
1175 | shutil.copytree(rcdir,ipythondir) | |
1179 | os.chdir(ipythondir) |
|
1176 | os.chdir(ipythondir) | |
1180 | rc_files = glb("ipythonrc*") |
|
1177 | rc_files = glb("ipythonrc*") | |
1181 | for rc_file in rc_files: |
|
1178 | for rc_file in rc_files: | |
1182 | os.rename(rc_file,rc_file+rc_suffix) |
|
1179 | os.rename(rc_file,rc_file+rc_suffix) | |
1183 | except: |
|
1180 | except: | |
1184 | warning = """ |
|
1181 | warning = """ | |
1185 |
|
1182 | |||
1186 | There was a problem with the installation: |
|
1183 | There was a problem with the installation: | |
1187 | %s |
|
1184 | %s | |
1188 | Try to correct it or contact the developers if you think it's a bug. |
|
1185 | Try to correct it or contact the developers if you think it's a bug. | |
1189 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] |
|
1186 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] | |
1190 | warn(warning) |
|
1187 | warn(warning) | |
1191 | wait() |
|
1188 | wait() | |
1192 | return |
|
1189 | return | |
1193 |
|
1190 | |||
1194 | elif mode == 'upgrade': |
|
1191 | elif mode == 'upgrade': | |
1195 | try: |
|
1192 | try: | |
1196 | os.chdir(ipythondir) |
|
1193 | os.chdir(ipythondir) | |
1197 | except: |
|
1194 | except: | |
1198 | print """ |
|
1195 | print """ | |
1199 | Can not upgrade: changing to directory %s failed. Details: |
|
1196 | Can not upgrade: changing to directory %s failed. Details: | |
1200 | %s |
|
1197 | %s | |
1201 | """ % (ipythondir,sys.exc_info()[1]) |
|
1198 | """ % (ipythondir,sys.exc_info()[1]) | |
1202 | wait() |
|
1199 | wait() | |
1203 | return |
|
1200 | return | |
1204 | else: |
|
1201 | else: | |
1205 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) |
|
1202 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) | |
1206 | for new_full_path in sources: |
|
1203 | for new_full_path in sources: | |
1207 | new_filename = os.path.basename(new_full_path) |
|
1204 | new_filename = os.path.basename(new_full_path) | |
1208 | if new_filename.startswith('ipythonrc'): |
|
1205 | if new_filename.startswith('ipythonrc'): | |
1209 | new_filename = new_filename + rc_suffix |
|
1206 | new_filename = new_filename + rc_suffix | |
1210 | # The config directory should only contain files, skip any |
|
1207 | # The config directory should only contain files, skip any | |
1211 | # directories which may be there (like CVS) |
|
1208 | # directories which may be there (like CVS) | |
1212 | if os.path.isdir(new_full_path): |
|
1209 | if os.path.isdir(new_full_path): | |
1213 | continue |
|
1210 | continue | |
1214 | if os.path.exists(new_filename): |
|
1211 | if os.path.exists(new_filename): | |
1215 | old_file = new_filename+'.old' |
|
1212 | old_file = new_filename+'.old' | |
1216 | if os.path.exists(old_file): |
|
1213 | if os.path.exists(old_file): | |
1217 | os.remove(old_file) |
|
1214 | os.remove(old_file) | |
1218 | os.rename(new_filename,old_file) |
|
1215 | os.rename(new_filename,old_file) | |
1219 | shutil.copy(new_full_path,new_filename) |
|
1216 | shutil.copy(new_full_path,new_filename) | |
1220 | else: |
|
1217 | else: | |
1221 | raise ValueError,'unrecognized mode for install:',`mode` |
|
1218 | raise ValueError,'unrecognized mode for install:',`mode` | |
1222 |
|
1219 | |||
1223 | # Fix line-endings to those native to each platform in the config |
|
1220 | # Fix line-endings to those native to each platform in the config | |
1224 | # directory. |
|
1221 | # directory. | |
1225 | try: |
|
1222 | try: | |
1226 | os.chdir(ipythondir) |
|
1223 | os.chdir(ipythondir) | |
1227 | except: |
|
1224 | except: | |
1228 | print """ |
|
1225 | print """ | |
1229 | Problem: changing to directory %s failed. |
|
1226 | Problem: changing to directory %s failed. | |
1230 | Details: |
|
1227 | Details: | |
1231 | %s |
|
1228 | %s | |
1232 |
|
1229 | |||
1233 | Some configuration files may have incorrect line endings. This should not |
|
1230 | Some configuration files may have incorrect line endings. This should not | |
1234 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) |
|
1231 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) | |
1235 | wait() |
|
1232 | wait() | |
1236 | else: |
|
1233 | else: | |
1237 | for fname in glb('ipythonrc*'): |
|
1234 | for fname in glb('ipythonrc*'): | |
1238 | try: |
|
1235 | try: | |
1239 | native_line_ends(fname,backup=0) |
|
1236 | native_line_ends(fname,backup=0) | |
1240 | except IOError: |
|
1237 | except IOError: | |
1241 | pass |
|
1238 | pass | |
1242 |
|
1239 | |||
1243 | if mode == 'install': |
|
1240 | if mode == 'install': | |
1244 | print """ |
|
1241 | print """ | |
1245 | Successful installation! |
|
1242 | Successful installation! | |
1246 |
|
1243 | |||
1247 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the |
|
1244 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the | |
1248 | IPython manual (there are both HTML and PDF versions supplied with the |
|
1245 | IPython manual (there are both HTML and PDF versions supplied with the | |
1249 | distribution) to make sure that your system environment is properly configured |
|
1246 | distribution) to make sure that your system environment is properly configured | |
1250 | to take advantage of IPython's features. |
|
1247 | to take advantage of IPython's features. | |
1251 |
|
1248 | |||
1252 | Important note: the configuration system has changed! The old system is |
|
1249 | Important note: the configuration system has changed! The old system is | |
1253 | still in place, but its setting may be partly overridden by the settings in |
|
1250 | still in place, but its setting may be partly overridden by the settings in | |
1254 | "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file |
|
1251 | "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file | |
1255 | if some of the new settings bother you. |
|
1252 | if some of the new settings bother you. | |
1256 |
|
1253 | |||
1257 | """ |
|
1254 | """ | |
1258 | else: |
|
1255 | else: | |
1259 | print """ |
|
1256 | print """ | |
1260 | Successful upgrade! |
|
1257 | Successful upgrade! | |
1261 |
|
1258 | |||
1262 | All files in your directory: |
|
1259 | All files in your directory: | |
1263 | %(ipythondir)s |
|
1260 | %(ipythondir)s | |
1264 | which would have been overwritten by the upgrade were backed up with a .old |
|
1261 | which would have been overwritten by the upgrade were backed up with a .old | |
1265 | extension. If you had made particular customizations in those files you may |
|
1262 | extension. If you had made particular customizations in those files you may | |
1266 | want to merge them back into the new files.""" % locals() |
|
1263 | want to merge them back into the new files.""" % locals() | |
1267 | wait() |
|
1264 | wait() | |
1268 | os.chdir(cwd) |
|
1265 | os.chdir(cwd) | |
1269 | # end user_setup() |
|
1266 | # end user_setup() | |
1270 |
|
1267 | |||
1271 | def atexit_operations(self): |
|
1268 | def atexit_operations(self): | |
1272 | """This will be executed at the time of exit. |
|
1269 | """This will be executed at the time of exit. | |
1273 |
|
1270 | |||
1274 | Saving of persistent data should be performed here. """ |
|
1271 | Saving of persistent data should be performed here. """ | |
1275 |
|
1272 | |||
1276 | #print '*** IPython exit cleanup ***' # dbg |
|
1273 | #print '*** IPython exit cleanup ***' # dbg | |
1277 | # input history |
|
1274 | # input history | |
1278 | self.savehist() |
|
1275 | self.savehist() | |
1279 |
|
1276 | |||
1280 | # Cleanup all tempfiles left around |
|
1277 | # Cleanup all tempfiles left around | |
1281 | for tfile in self.tempfiles: |
|
1278 | for tfile in self.tempfiles: | |
1282 | try: |
|
1279 | try: | |
1283 | os.unlink(tfile) |
|
1280 | os.unlink(tfile) | |
1284 | except OSError: |
|
1281 | except OSError: | |
1285 | pass |
|
1282 | pass | |
1286 |
|
1283 | |||
1287 | # Clear all user namespaces to release all references cleanly. |
|
1284 | # Clear all user namespaces to release all references cleanly. | |
1288 | self.reset() |
|
1285 | self.reset() | |
1289 |
|
1286 | |||
1290 | # Run user hooks |
|
1287 | # Run user hooks | |
1291 | self.hooks.shutdown_hook() |
|
1288 | self.hooks.shutdown_hook() | |
1292 |
|
1289 | |||
1293 | def reset(self): |
|
1290 | def reset(self): | |
1294 | """Clear all internal namespaces. |
|
1291 | """Clear all internal namespaces. | |
1295 |
|
1292 | |||
1296 | Note that this is much more aggressive than %reset, since it clears |
|
1293 | Note that this is much more aggressive than %reset, since it clears | |
1297 | fully all namespaces, as well as all input/output lists. |
|
1294 | fully all namespaces, as well as all input/output lists. | |
1298 | """ |
|
1295 | """ | |
1299 | for ns in self.ns_refs_table: |
|
1296 | for ns in self.ns_refs_table: | |
1300 | ns.clear() |
|
1297 | ns.clear() | |
1301 |
|
1298 | |||
1302 | # Clear input and output histories |
|
1299 | # Clear input and output histories | |
1303 | self.input_hist[:] = [] |
|
1300 | self.input_hist[:] = [] | |
1304 | self.input_hist_raw[:] = [] |
|
1301 | self.input_hist_raw[:] = [] | |
1305 | self.output_hist.clear() |
|
1302 | self.output_hist.clear() | |
1306 | # Restore the user namespaces to minimal usability |
|
1303 | # Restore the user namespaces to minimal usability | |
1307 | self.init_namespaces() |
|
1304 | self.init_namespaces() | |
1308 |
|
1305 | |||
1309 | def savehist(self): |
|
1306 | def savehist(self): | |
1310 | """Save input history to a file (via readline library).""" |
|
1307 | """Save input history to a file (via readline library).""" | |
1311 |
|
1308 | |||
1312 | if not self.has_readline: |
|
1309 | if not self.has_readline: | |
1313 | return |
|
1310 | return | |
1314 |
|
1311 | |||
1315 | try: |
|
1312 | try: | |
1316 | self.readline.write_history_file(self.histfile) |
|
1313 | self.readline.write_history_file(self.histfile) | |
1317 | except: |
|
1314 | except: | |
1318 | print 'Unable to save IPython command history to file: ' + \ |
|
1315 | print 'Unable to save IPython command history to file: ' + \ | |
1319 | `self.histfile` |
|
1316 | `self.histfile` | |
1320 |
|
1317 | |||
1321 | def reloadhist(self): |
|
1318 | def reloadhist(self): | |
1322 | """Reload the input history from disk file.""" |
|
1319 | """Reload the input history from disk file.""" | |
1323 |
|
1320 | |||
1324 | if self.has_readline: |
|
1321 | if self.has_readline: | |
1325 | try: |
|
1322 | try: | |
1326 | self.readline.clear_history() |
|
1323 | self.readline.clear_history() | |
1327 | self.readline.read_history_file(self.shell.histfile) |
|
1324 | self.readline.read_history_file(self.shell.histfile) | |
1328 | except AttributeError: |
|
1325 | except AttributeError: | |
1329 | pass |
|
1326 | pass | |
1330 |
|
1327 | |||
1331 |
|
1328 | |||
1332 | def history_saving_wrapper(self, func): |
|
1329 | def history_saving_wrapper(self, func): | |
1333 | """ Wrap func for readline history saving |
|
1330 | """ Wrap func for readline history saving | |
1334 |
|
1331 | |||
1335 | Convert func into callable that saves & restores |
|
1332 | Convert func into callable that saves & restores | |
1336 | history around the call """ |
|
1333 | history around the call """ | |
1337 |
|
1334 | |||
1338 | if not self.has_readline: |
|
1335 | if not self.has_readline: | |
1339 | return func |
|
1336 | return func | |
1340 |
|
1337 | |||
1341 | def wrapper(): |
|
1338 | def wrapper(): | |
1342 | self.savehist() |
|
1339 | self.savehist() | |
1343 | try: |
|
1340 | try: | |
1344 | func() |
|
1341 | func() | |
1345 | finally: |
|
1342 | finally: | |
1346 | readline.read_history_file(self.histfile) |
|
1343 | readline.read_history_file(self.histfile) | |
1347 | return wrapper |
|
1344 | return wrapper | |
1348 |
|
1345 | |||
1349 | def pre_readline(self): |
|
1346 | def pre_readline(self): | |
1350 | """readline hook to be used at the start of each line. |
|
1347 | """readline hook to be used at the start of each line. | |
1351 |
|
1348 | |||
1352 | Currently it handles auto-indent only.""" |
|
1349 | Currently it handles auto-indent only.""" | |
1353 |
|
1350 | |||
1354 | #debugx('self.indent_current_nsp','pre_readline:') |
|
1351 | #debugx('self.indent_current_nsp','pre_readline:') | |
1355 |
|
1352 | |||
1356 | if self.rl_do_indent: |
|
1353 | if self.rl_do_indent: | |
1357 | self.readline.insert_text(self.indent_current_str()) |
|
1354 | self.readline.insert_text(self.indent_current_str()) | |
1358 | if self.rl_next_input is not None: |
|
1355 | if self.rl_next_input is not None: | |
1359 | self.readline.insert_text(self.rl_next_input) |
|
1356 | self.readline.insert_text(self.rl_next_input) | |
1360 | self.rl_next_input = None |
|
1357 | self.rl_next_input = None | |
1361 |
|
1358 | |||
1362 | def init_readline(self): |
|
1359 | def init_readline(self): | |
1363 | """Command history completion/saving/reloading.""" |
|
1360 | """Command history completion/saving/reloading.""" | |
1364 |
|
1361 | |||
1365 |
|
1362 | |||
1366 | import IPython.rlineimpl as readline |
|
1363 | import IPython.rlineimpl as readline | |
1367 |
|
1364 | |||
1368 | if not readline.have_readline: |
|
1365 | if not readline.have_readline: | |
1369 | self.has_readline = 0 |
|
1366 | self.has_readline = 0 | |
1370 | self.readline = None |
|
1367 | self.readline = None | |
1371 | # no point in bugging windows users with this every time: |
|
1368 | # no point in bugging windows users with this every time: | |
1372 | warn('Readline services not available on this platform.') |
|
1369 | warn('Readline services not available on this platform.') | |
1373 | else: |
|
1370 | else: | |
1374 | sys.modules['readline'] = readline |
|
1371 | sys.modules['readline'] = readline | |
1375 | import atexit |
|
1372 | import atexit | |
1376 | from IPython.completer import IPCompleter |
|
1373 | from IPython.completer import IPCompleter | |
1377 | self.Completer = IPCompleter(self, |
|
1374 | self.Completer = IPCompleter(self, | |
1378 | self.user_ns, |
|
1375 | self.user_ns, | |
1379 | self.user_global_ns, |
|
1376 | self.user_global_ns, | |
1380 | self.rc.readline_omit__names, |
|
1377 | self.rc.readline_omit__names, | |
1381 | self.alias_table) |
|
1378 | self.alias_table) | |
1382 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1379 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1383 | self.strdispatchers['complete_command'] = sdisp |
|
1380 | self.strdispatchers['complete_command'] = sdisp | |
1384 | self.Completer.custom_completers = sdisp |
|
1381 | self.Completer.custom_completers = sdisp | |
1385 | # Platform-specific configuration |
|
1382 | # Platform-specific configuration | |
1386 | if os.name == 'nt': |
|
1383 | if os.name == 'nt': | |
1387 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1384 | self.readline_startup_hook = readline.set_pre_input_hook | |
1388 | else: |
|
1385 | else: | |
1389 | self.readline_startup_hook = readline.set_startup_hook |
|
1386 | self.readline_startup_hook = readline.set_startup_hook | |
1390 |
|
1387 | |||
1391 | # Load user's initrc file (readline config) |
|
1388 | # Load user's initrc file (readline config) | |
1392 | # Or if libedit is used, load editrc. |
|
1389 | # Or if libedit is used, load editrc. | |
1393 | inputrc_name = os.environ.get('INPUTRC') |
|
1390 | inputrc_name = os.environ.get('INPUTRC') | |
1394 | if inputrc_name is None: |
|
1391 | if inputrc_name is None: | |
1395 | home_dir = get_home_dir() |
|
1392 | home_dir = get_home_dir() | |
1396 | if home_dir is not None: |
|
1393 | if home_dir is not None: | |
1397 | inputrc_name = '.inputrc' |
|
1394 | inputrc_name = '.inputrc' | |
1398 | if readline.uses_libedit: |
|
1395 | if readline.uses_libedit: | |
1399 | inputrc_name = '.editrc' |
|
1396 | inputrc_name = '.editrc' | |
1400 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1397 | inputrc_name = os.path.join(home_dir, inputrc_name) | |
1401 | if os.path.isfile(inputrc_name): |
|
1398 | if os.path.isfile(inputrc_name): | |
1402 | try: |
|
1399 | try: | |
1403 | readline.read_init_file(inputrc_name) |
|
1400 | readline.read_init_file(inputrc_name) | |
1404 | except: |
|
1401 | except: | |
1405 | warn('Problems reading readline initialization file <%s>' |
|
1402 | warn('Problems reading readline initialization file <%s>' | |
1406 | % inputrc_name) |
|
1403 | % inputrc_name) | |
1407 |
|
1404 | |||
1408 | self.has_readline = 1 |
|
1405 | self.has_readline = 1 | |
1409 | self.readline = readline |
|
1406 | self.readline = readline | |
1410 | # save this in sys so embedded copies can restore it properly |
|
1407 | # save this in sys so embedded copies can restore it properly | |
1411 | sys.ipcompleter = self.Completer.complete |
|
1408 | sys.ipcompleter = self.Completer.complete | |
1412 | self.set_completer() |
|
1409 | self.set_completer() | |
1413 |
|
1410 | |||
1414 | # Configure readline according to user's prefs |
|
1411 | # Configure readline according to user's prefs | |
1415 | # This is only done if GNU readline is being used. If libedit |
|
1412 | # This is only done if GNU readline is being used. If libedit | |
1416 | # is being used (as on Leopard) the readline config is |
|
1413 | # is being used (as on Leopard) the readline config is | |
1417 | # not run as the syntax for libedit is different. |
|
1414 | # not run as the syntax for libedit is different. | |
1418 | if not readline.uses_libedit: |
|
1415 | if not readline.uses_libedit: | |
1419 | for rlcommand in self.rc.readline_parse_and_bind: |
|
1416 | for rlcommand in self.rc.readline_parse_and_bind: | |
1420 | readline.parse_and_bind(rlcommand) |
|
1417 | readline.parse_and_bind(rlcommand) | |
1421 |
|
1418 | |||
1422 | # remove some chars from the delimiters list |
|
1419 | # remove some chars from the delimiters list | |
1423 | delims = readline.get_completer_delims() |
|
1420 | delims = readline.get_completer_delims() | |
1424 | delims = delims.translate(string._idmap, |
|
1421 | delims = delims.translate(string._idmap, | |
1425 | self.rc.readline_remove_delims) |
|
1422 | self.rc.readline_remove_delims) | |
1426 | readline.set_completer_delims(delims) |
|
1423 | readline.set_completer_delims(delims) | |
1427 | # otherwise we end up with a monster history after a while: |
|
1424 | # otherwise we end up with a monster history after a while: | |
1428 | readline.set_history_length(1000) |
|
1425 | readline.set_history_length(1000) | |
1429 | try: |
|
1426 | try: | |
1430 | #print '*** Reading readline history' # dbg |
|
1427 | #print '*** Reading readline history' # dbg | |
1431 | readline.read_history_file(self.histfile) |
|
1428 | readline.read_history_file(self.histfile) | |
1432 | except IOError: |
|
1429 | except IOError: | |
1433 | pass # It doesn't exist yet. |
|
1430 | pass # It doesn't exist yet. | |
1434 |
|
1431 | |||
1435 | atexit.register(self.atexit_operations) |
|
1432 | atexit.register(self.atexit_operations) | |
1436 | del atexit |
|
1433 | del atexit | |
1437 |
|
1434 | |||
1438 | # Configure auto-indent for all platforms |
|
1435 | # Configure auto-indent for all platforms | |
1439 | self.set_autoindent(self.rc.autoindent) |
|
1436 | self.set_autoindent(self.rc.autoindent) | |
1440 |
|
1437 | |||
1441 | def ask_yes_no(self,prompt,default=True): |
|
1438 | def ask_yes_no(self,prompt,default=True): | |
1442 | if self.rc.quiet: |
|
1439 | if self.rc.quiet: | |
1443 | return True |
|
1440 | return True | |
1444 | return ask_yes_no(prompt,default) |
|
1441 | return ask_yes_no(prompt,default) | |
1445 |
|
1442 | |||
1446 | def cache_main_mod(self,mod): |
|
1443 | def cache_main_mod(self,mod): | |
1447 | """Cache a main module. |
|
1444 | """Cache a main module. | |
1448 |
|
1445 | |||
1449 | When scripts are executed via %run, we must keep a reference to their |
|
1446 | When scripts are executed via %run, we must keep a reference to their | |
1450 | __main__ module (a FakeModule instance) around so that Python doesn't |
|
1447 | __main__ module (a FakeModule instance) around so that Python doesn't | |
1451 | clear it, rendering objects defined therein useless. |
|
1448 | clear it, rendering objects defined therein useless. | |
1452 |
|
1449 | |||
1453 | This method keeps said reference in a private dict, keyed by the |
|
1450 | This method keeps said reference in a private dict, keyed by the | |
1454 | absolute path of the module object (which corresponds to the script |
|
1451 | absolute path of the module object (which corresponds to the script | |
1455 | path). This way, for multiple executions of the same script we only |
|
1452 | path). This way, for multiple executions of the same script we only | |
1456 | keep one copy of __main__ (the last one), thus preventing memory leaks |
|
1453 | keep one copy of __main__ (the last one), thus preventing memory leaks | |
1457 | from old references while allowing the objects from the last execution |
|
1454 | from old references while allowing the objects from the last execution | |
1458 | to be accessible. |
|
1455 | to be accessible. | |
1459 |
|
1456 | |||
1460 | Parameters |
|
1457 | Parameters | |
1461 | ---------- |
|
1458 | ---------- | |
1462 | mod : a module object |
|
1459 | mod : a module object | |
1463 |
|
1460 | |||
1464 | Examples |
|
1461 | Examples | |
1465 | -------- |
|
1462 | -------- | |
1466 |
|
1463 | |||
1467 | In [10]: import IPython |
|
1464 | In [10]: import IPython | |
1468 |
|
1465 | |||
1469 | In [11]: _ip.IP.cache_main_mod(IPython) |
|
1466 | In [11]: _ip.IP.cache_main_mod(IPython) | |
1470 |
|
1467 | |||
1471 | In [12]: IPython.__file__ in _ip.IP._user_main_modules |
|
1468 | In [12]: IPython.__file__ in _ip.IP._user_main_modules | |
1472 | Out[12]: True |
|
1469 | Out[12]: True | |
1473 | """ |
|
1470 | """ | |
1474 | self._user_main_modules[os.path.abspath(mod.__file__) ] = mod |
|
1471 | self._user_main_modules[os.path.abspath(mod.__file__) ] = mod | |
1475 |
|
1472 | |||
1476 | def clear_main_mod_cache(self): |
|
1473 | def clear_main_mod_cache(self): | |
1477 | """Clear the cache of main modules. |
|
1474 | """Clear the cache of main modules. | |
1478 |
|
1475 | |||
1479 | Mainly for use by utilities like %reset. |
|
1476 | Mainly for use by utilities like %reset. | |
1480 |
|
1477 | |||
1481 | Examples |
|
1478 | Examples | |
1482 | -------- |
|
1479 | -------- | |
1483 |
|
1480 | |||
1484 | In [15]: import IPython |
|
1481 | In [15]: import IPython | |
1485 |
|
1482 | |||
1486 | In [16]: _ip.IP.cache_main_mod(IPython) |
|
1483 | In [16]: _ip.IP.cache_main_mod(IPython) | |
1487 |
|
1484 | |||
1488 | In [17]: len(_ip.IP._user_main_modules) > 0 |
|
1485 | In [17]: len(_ip.IP._user_main_modules) > 0 | |
1489 | Out[17]: True |
|
1486 | Out[17]: True | |
1490 |
|
1487 | |||
1491 | In [18]: _ip.IP.clear_main_mod_cache() |
|
1488 | In [18]: _ip.IP.clear_main_mod_cache() | |
1492 |
|
1489 | |||
1493 | In [19]: len(_ip.IP._user_main_modules) == 0 |
|
1490 | In [19]: len(_ip.IP._user_main_modules) == 0 | |
1494 | Out[19]: True |
|
1491 | Out[19]: True | |
1495 | """ |
|
1492 | """ | |
1496 | self._user_main_modules.clear() |
|
1493 | self._user_main_modules.clear() | |
1497 |
|
1494 | |||
1498 | def _should_recompile(self,e): |
|
1495 | def _should_recompile(self,e): | |
1499 | """Utility routine for edit_syntax_error""" |
|
1496 | """Utility routine for edit_syntax_error""" | |
1500 |
|
1497 | |||
1501 | if e.filename in ('<ipython console>','<input>','<string>', |
|
1498 | if e.filename in ('<ipython console>','<input>','<string>', | |
1502 | '<console>','<BackgroundJob compilation>', |
|
1499 | '<console>','<BackgroundJob compilation>', | |
1503 | None): |
|
1500 | None): | |
1504 |
|
1501 | |||
1505 | return False |
|
1502 | return False | |
1506 | try: |
|
1503 | try: | |
1507 | if (self.rc.autoedit_syntax and |
|
1504 | if (self.rc.autoedit_syntax and | |
1508 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
1505 | not self.ask_yes_no('Return to editor to correct syntax error? ' | |
1509 | '[Y/n] ','y')): |
|
1506 | '[Y/n] ','y')): | |
1510 | return False |
|
1507 | return False | |
1511 | except EOFError: |
|
1508 | except EOFError: | |
1512 | return False |
|
1509 | return False | |
1513 |
|
1510 | |||
1514 | def int0(x): |
|
1511 | def int0(x): | |
1515 | try: |
|
1512 | try: | |
1516 | return int(x) |
|
1513 | return int(x) | |
1517 | except TypeError: |
|
1514 | except TypeError: | |
1518 | return 0 |
|
1515 | return 0 | |
1519 | # always pass integer line and offset values to editor hook |
|
1516 | # always pass integer line and offset values to editor hook | |
1520 | self.hooks.fix_error_editor(e.filename, |
|
1517 | self.hooks.fix_error_editor(e.filename, | |
1521 | int0(e.lineno),int0(e.offset),e.msg) |
|
1518 | int0(e.lineno),int0(e.offset),e.msg) | |
1522 | return True |
|
1519 | return True | |
1523 |
|
1520 | |||
1524 | def edit_syntax_error(self): |
|
1521 | def edit_syntax_error(self): | |
1525 | """The bottom half of the syntax error handler called in the main loop. |
|
1522 | """The bottom half of the syntax error handler called in the main loop. | |
1526 |
|
1523 | |||
1527 | Loop until syntax error is fixed or user cancels. |
|
1524 | Loop until syntax error is fixed or user cancels. | |
1528 | """ |
|
1525 | """ | |
1529 |
|
1526 | |||
1530 | while self.SyntaxTB.last_syntax_error: |
|
1527 | while self.SyntaxTB.last_syntax_error: | |
1531 | # copy and clear last_syntax_error |
|
1528 | # copy and clear last_syntax_error | |
1532 | err = self.SyntaxTB.clear_err_state() |
|
1529 | err = self.SyntaxTB.clear_err_state() | |
1533 | if not self._should_recompile(err): |
|
1530 | if not self._should_recompile(err): | |
1534 | return |
|
1531 | return | |
1535 | try: |
|
1532 | try: | |
1536 | # may set last_syntax_error again if a SyntaxError is raised |
|
1533 | # may set last_syntax_error again if a SyntaxError is raised | |
1537 | self.safe_execfile(err.filename,self.user_ns) |
|
1534 | self.safe_execfile(err.filename,self.user_ns) | |
1538 | except: |
|
1535 | except: | |
1539 | self.showtraceback() |
|
1536 | self.showtraceback() | |
1540 | else: |
|
1537 | else: | |
1541 | try: |
|
1538 | try: | |
1542 | f = file(err.filename) |
|
1539 | f = file(err.filename) | |
1543 | try: |
|
1540 | try: | |
1544 | sys.displayhook(f.read()) |
|
1541 | sys.displayhook(f.read()) | |
1545 | finally: |
|
1542 | finally: | |
1546 | f.close() |
|
1543 | f.close() | |
1547 | except: |
|
1544 | except: | |
1548 | self.showtraceback() |
|
1545 | self.showtraceback() | |
1549 |
|
1546 | |||
1550 | def showsyntaxerror(self, filename=None): |
|
1547 | def showsyntaxerror(self, filename=None): | |
1551 | """Display the syntax error that just occurred. |
|
1548 | """Display the syntax error that just occurred. | |
1552 |
|
1549 | |||
1553 | This doesn't display a stack trace because there isn't one. |
|
1550 | This doesn't display a stack trace because there isn't one. | |
1554 |
|
1551 | |||
1555 | If a filename is given, it is stuffed in the exception instead |
|
1552 | If a filename is given, it is stuffed in the exception instead | |
1556 | of what was there before (because Python's parser always uses |
|
1553 | of what was there before (because Python's parser always uses | |
1557 | "<string>" when reading from a string). |
|
1554 | "<string>" when reading from a string). | |
1558 | """ |
|
1555 | """ | |
1559 | etype, value, last_traceback = sys.exc_info() |
|
1556 | etype, value, last_traceback = sys.exc_info() | |
1560 |
|
1557 | |||
1561 | # See note about these variables in showtraceback() below |
|
1558 | # See note about these variables in showtraceback() below | |
1562 | sys.last_type = etype |
|
1559 | sys.last_type = etype | |
1563 | sys.last_value = value |
|
1560 | sys.last_value = value | |
1564 | sys.last_traceback = last_traceback |
|
1561 | sys.last_traceback = last_traceback | |
1565 |
|
1562 | |||
1566 | if filename and etype is SyntaxError: |
|
1563 | if filename and etype is SyntaxError: | |
1567 | # Work hard to stuff the correct filename in the exception |
|
1564 | # Work hard to stuff the correct filename in the exception | |
1568 | try: |
|
1565 | try: | |
1569 | msg, (dummy_filename, lineno, offset, line) = value |
|
1566 | msg, (dummy_filename, lineno, offset, line) = value | |
1570 | except: |
|
1567 | except: | |
1571 | # Not the format we expect; leave it alone |
|
1568 | # Not the format we expect; leave it alone | |
1572 | pass |
|
1569 | pass | |
1573 | else: |
|
1570 | else: | |
1574 | # Stuff in the right filename |
|
1571 | # Stuff in the right filename | |
1575 | try: |
|
1572 | try: | |
1576 | # Assume SyntaxError is a class exception |
|
1573 | # Assume SyntaxError is a class exception | |
1577 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1574 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1578 | except: |
|
1575 | except: | |
1579 | # If that failed, assume SyntaxError is a string |
|
1576 | # If that failed, assume SyntaxError is a string | |
1580 | value = msg, (filename, lineno, offset, line) |
|
1577 | value = msg, (filename, lineno, offset, line) | |
1581 | self.SyntaxTB(etype,value,[]) |
|
1578 | self.SyntaxTB(etype,value,[]) | |
1582 |
|
1579 | |||
1583 | def debugger(self,force=False): |
|
1580 | def debugger(self,force=False): | |
1584 | """Call the pydb/pdb debugger. |
|
1581 | """Call the pydb/pdb debugger. | |
1585 |
|
1582 | |||
1586 | Keywords: |
|
1583 | Keywords: | |
1587 |
|
1584 | |||
1588 | - force(False): by default, this routine checks the instance call_pdb |
|
1585 | - force(False): by default, this routine checks the instance call_pdb | |
1589 | flag and does not actually invoke the debugger if the flag is false. |
|
1586 | flag and does not actually invoke the debugger if the flag is false. | |
1590 | The 'force' option forces the debugger to activate even if the flag |
|
1587 | The 'force' option forces the debugger to activate even if the flag | |
1591 | is false. |
|
1588 | is false. | |
1592 | """ |
|
1589 | """ | |
1593 |
|
1590 | |||
1594 | if not (force or self.call_pdb): |
|
1591 | if not (force or self.call_pdb): | |
1595 | return |
|
1592 | return | |
1596 |
|
1593 | |||
1597 | if not hasattr(sys,'last_traceback'): |
|
1594 | if not hasattr(sys,'last_traceback'): | |
1598 | error('No traceback has been produced, nothing to debug.') |
|
1595 | error('No traceback has been produced, nothing to debug.') | |
1599 | return |
|
1596 | return | |
1600 |
|
1597 | |||
1601 | # use pydb if available |
|
1598 | # use pydb if available | |
1602 | if Debugger.has_pydb: |
|
1599 | if Debugger.has_pydb: | |
1603 | from pydb import pm |
|
1600 | from pydb import pm | |
1604 | else: |
|
1601 | else: | |
1605 | # fallback to our internal debugger |
|
1602 | # fallback to our internal debugger | |
1606 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
1603 | pm = lambda : self.InteractiveTB.debugger(force=True) | |
1607 | self.history_saving_wrapper(pm)() |
|
1604 | self.history_saving_wrapper(pm)() | |
1608 |
|
1605 | |||
1609 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): |
|
1606 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): | |
1610 | """Display the exception that just occurred. |
|
1607 | """Display the exception that just occurred. | |
1611 |
|
1608 | |||
1612 | If nothing is known about the exception, this is the method which |
|
1609 | If nothing is known about the exception, this is the method which | |
1613 | should be used throughout the code for presenting user tracebacks, |
|
1610 | should be used throughout the code for presenting user tracebacks, | |
1614 | rather than directly invoking the InteractiveTB object. |
|
1611 | rather than directly invoking the InteractiveTB object. | |
1615 |
|
1612 | |||
1616 | A specific showsyntaxerror() also exists, but this method can take |
|
1613 | A specific showsyntaxerror() also exists, but this method can take | |
1617 | care of calling it if needed, so unless you are explicitly catching a |
|
1614 | care of calling it if needed, so unless you are explicitly catching a | |
1618 | SyntaxError exception, don't try to analyze the stack manually and |
|
1615 | SyntaxError exception, don't try to analyze the stack manually and | |
1619 | simply call this method.""" |
|
1616 | simply call this method.""" | |
1620 |
|
1617 | |||
1621 |
|
1618 | |||
1622 | # Though this won't be called by syntax errors in the input line, |
|
1619 | # Though this won't be called by syntax errors in the input line, | |
1623 | # there may be SyntaxError cases whith imported code. |
|
1620 | # there may be SyntaxError cases whith imported code. | |
1624 |
|
1621 | |||
1625 | try: |
|
1622 | try: | |
1626 | if exc_tuple is None: |
|
1623 | if exc_tuple is None: | |
1627 | etype, value, tb = sys.exc_info() |
|
1624 | etype, value, tb = sys.exc_info() | |
1628 | else: |
|
1625 | else: | |
1629 | etype, value, tb = exc_tuple |
|
1626 | etype, value, tb = exc_tuple | |
1630 |
|
1627 | |||
1631 | if etype is SyntaxError: |
|
1628 | if etype is SyntaxError: | |
1632 | self.showsyntaxerror(filename) |
|
1629 | self.showsyntaxerror(filename) | |
1633 | elif etype is IPython.ipapi.UsageError: |
|
1630 | elif etype is IPython.ipapi.UsageError: | |
1634 | print "UsageError:", value |
|
1631 | print "UsageError:", value | |
1635 | else: |
|
1632 | else: | |
1636 | # WARNING: these variables are somewhat deprecated and not |
|
1633 | # WARNING: these variables are somewhat deprecated and not | |
1637 | # necessarily safe to use in a threaded environment, but tools |
|
1634 | # necessarily safe to use in a threaded environment, but tools | |
1638 | # like pdb depend on their existence, so let's set them. If we |
|
1635 | # like pdb depend on their existence, so let's set them. If we | |
1639 | # find problems in the field, we'll need to revisit their use. |
|
1636 | # find problems in the field, we'll need to revisit their use. | |
1640 | sys.last_type = etype |
|
1637 | sys.last_type = etype | |
1641 | sys.last_value = value |
|
1638 | sys.last_value = value | |
1642 | sys.last_traceback = tb |
|
1639 | sys.last_traceback = tb | |
1643 |
|
1640 | |||
1644 | if etype in self.custom_exceptions: |
|
1641 | if etype in self.custom_exceptions: | |
1645 | self.CustomTB(etype,value,tb) |
|
1642 | self.CustomTB(etype,value,tb) | |
1646 | else: |
|
1643 | else: | |
1647 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) |
|
1644 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) | |
1648 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1645 | if self.InteractiveTB.call_pdb and self.has_readline: | |
1649 | # pdb mucks up readline, fix it back |
|
1646 | # pdb mucks up readline, fix it back | |
1650 | self.set_completer() |
|
1647 | self.set_completer() | |
1651 | except KeyboardInterrupt: |
|
1648 | except KeyboardInterrupt: | |
1652 | self.write("\nKeyboardInterrupt\n") |
|
1649 | self.write("\nKeyboardInterrupt\n") | |
1653 |
|
1650 | |||
1654 | def mainloop(self,banner=None): |
|
1651 | def mainloop(self,banner=None): | |
1655 | """Creates the local namespace and starts the mainloop. |
|
1652 | """Creates the local namespace and starts the mainloop. | |
1656 |
|
1653 | |||
1657 | If an optional banner argument is given, it will override the |
|
1654 | If an optional banner argument is given, it will override the | |
1658 | internally created default banner.""" |
|
1655 | internally created default banner.""" | |
1659 |
|
1656 | |||
1660 | if self.rc.c: # Emulate Python's -c option |
|
1657 | if self.rc.c: # Emulate Python's -c option | |
1661 | self.exec_init_cmd() |
|
1658 | self.exec_init_cmd() | |
1662 | if banner is None: |
|
1659 | if banner is None: | |
1663 | if not self.rc.banner: |
|
1660 | if not self.rc.banner: | |
1664 | banner = '' |
|
1661 | banner = '' | |
1665 | # banner is string? Use it directly! |
|
1662 | # banner is string? Use it directly! | |
1666 | elif isinstance(self.rc.banner,basestring): |
|
1663 | elif isinstance(self.rc.banner,basestring): | |
1667 | banner = self.rc.banner |
|
1664 | banner = self.rc.banner | |
1668 | else: |
|
1665 | else: | |
1669 | banner = self.BANNER+self.banner2 |
|
1666 | banner = self.BANNER+self.banner2 | |
1670 |
|
1667 | |||
1671 | while 1: |
|
1668 | while 1: | |
1672 | try: |
|
1669 | try: | |
1673 | self.interact(banner) |
|
1670 | self.interact(banner) | |
1674 | #self.interact_with_readline() |
|
1671 | #self.interact_with_readline() | |
1675 |
|
1672 | |||
1676 | # XXX for testing of a readline-decoupled repl loop, call |
|
1673 | # XXX for testing of a readline-decoupled repl loop, call | |
1677 | # interact_with_readline above |
|
1674 | # interact_with_readline above | |
1678 |
|
1675 | |||
1679 | break |
|
1676 | break | |
1680 | except KeyboardInterrupt: |
|
1677 | except KeyboardInterrupt: | |
1681 | # this should not be necessary, but KeyboardInterrupt |
|
1678 | # this should not be necessary, but KeyboardInterrupt | |
1682 | # handling seems rather unpredictable... |
|
1679 | # handling seems rather unpredictable... | |
1683 | self.write("\nKeyboardInterrupt in interact()\n") |
|
1680 | self.write("\nKeyboardInterrupt in interact()\n") | |
1684 |
|
1681 | |||
1685 | def exec_init_cmd(self): |
|
1682 | def exec_init_cmd(self): | |
1686 | """Execute a command given at the command line. |
|
1683 | """Execute a command given at the command line. | |
1687 |
|
1684 | |||
1688 | This emulates Python's -c option.""" |
|
1685 | This emulates Python's -c option.""" | |
1689 |
|
1686 | |||
1690 | #sys.argv = ['-c'] |
|
1687 | #sys.argv = ['-c'] | |
1691 | self.push(self.prefilter(self.rc.c, False)) |
|
1688 | self.push(self.prefilter(self.rc.c, False)) | |
1692 | if not self.rc.interact: |
|
1689 | if not self.rc.interact: | |
1693 | self.ask_exit() |
|
1690 | self.ask_exit() | |
1694 |
|
1691 | |||
1695 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): |
|
1692 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): | |
1696 | """Embeds IPython into a running python program. |
|
1693 | """Embeds IPython into a running python program. | |
1697 |
|
1694 | |||
1698 | Input: |
|
1695 | Input: | |
1699 |
|
1696 | |||
1700 | - header: An optional header message can be specified. |
|
1697 | - header: An optional header message can be specified. | |
1701 |
|
1698 | |||
1702 | - local_ns, global_ns: working namespaces. If given as None, the |
|
1699 | - local_ns, global_ns: working namespaces. If given as None, the | |
1703 | IPython-initialized one is updated with __main__.__dict__, so that |
|
1700 | IPython-initialized one is updated with __main__.__dict__, so that | |
1704 | program variables become visible but user-specific configuration |
|
1701 | program variables become visible but user-specific configuration | |
1705 | remains possible. |
|
1702 | remains possible. | |
1706 |
|
1703 | |||
1707 | - stack_depth: specifies how many levels in the stack to go to |
|
1704 | - stack_depth: specifies how many levels in the stack to go to | |
1708 | looking for namespaces (when local_ns and global_ns are None). This |
|
1705 | looking for namespaces (when local_ns and global_ns are None). This | |
1709 | allows an intermediate caller to make sure that this function gets |
|
1706 | allows an intermediate caller to make sure that this function gets | |
1710 | the namespace from the intended level in the stack. By default (0) |
|
1707 | the namespace from the intended level in the stack. By default (0) | |
1711 | it will get its locals and globals from the immediate caller. |
|
1708 | it will get its locals and globals from the immediate caller. | |
1712 |
|
1709 | |||
1713 | Warning: it's possible to use this in a program which is being run by |
|
1710 | Warning: it's possible to use this in a program which is being run by | |
1714 | IPython itself (via %run), but some funny things will happen (a few |
|
1711 | IPython itself (via %run), but some funny things will happen (a few | |
1715 | globals get overwritten). In the future this will be cleaned up, as |
|
1712 | globals get overwritten). In the future this will be cleaned up, as | |
1716 | there is no fundamental reason why it can't work perfectly.""" |
|
1713 | there is no fundamental reason why it can't work perfectly.""" | |
1717 |
|
1714 | |||
1718 | # Get locals and globals from caller |
|
1715 | # Get locals and globals from caller | |
1719 | if local_ns is None or global_ns is None: |
|
1716 | if local_ns is None or global_ns is None: | |
1720 | call_frame = sys._getframe(stack_depth).f_back |
|
1717 | call_frame = sys._getframe(stack_depth).f_back | |
1721 |
|
1718 | |||
1722 | if local_ns is None: |
|
1719 | if local_ns is None: | |
1723 | local_ns = call_frame.f_locals |
|
1720 | local_ns = call_frame.f_locals | |
1724 | if global_ns is None: |
|
1721 | if global_ns is None: | |
1725 | global_ns = call_frame.f_globals |
|
1722 | global_ns = call_frame.f_globals | |
1726 |
|
1723 | |||
1727 | # Update namespaces and fire up interpreter |
|
1724 | # Update namespaces and fire up interpreter | |
1728 |
|
1725 | |||
1729 | # The global one is easy, we can just throw it in |
|
1726 | # The global one is easy, we can just throw it in | |
1730 | self.user_global_ns = global_ns |
|
1727 | self.user_global_ns = global_ns | |
1731 |
|
1728 | |||
1732 | # but the user/local one is tricky: ipython needs it to store internal |
|
1729 | # but the user/local one is tricky: ipython needs it to store internal | |
1733 | # data, but we also need the locals. We'll copy locals in the user |
|
1730 | # data, but we also need the locals. We'll copy locals in the user | |
1734 | # one, but will track what got copied so we can delete them at exit. |
|
1731 | # one, but will track what got copied so we can delete them at exit. | |
1735 | # This is so that a later embedded call doesn't see locals from a |
|
1732 | # This is so that a later embedded call doesn't see locals from a | |
1736 | # previous call (which most likely existed in a separate scope). |
|
1733 | # previous call (which most likely existed in a separate scope). | |
1737 | local_varnames = local_ns.keys() |
|
1734 | local_varnames = local_ns.keys() | |
1738 | self.user_ns.update(local_ns) |
|
1735 | self.user_ns.update(local_ns) | |
1739 | #self.user_ns['local_ns'] = local_ns # dbg |
|
1736 | #self.user_ns['local_ns'] = local_ns # dbg | |
1740 |
|
1737 | |||
1741 | # Patch for global embedding to make sure that things don't overwrite |
|
1738 | # Patch for global embedding to make sure that things don't overwrite | |
1742 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> |
|
1739 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> | |
1743 | # FIXME. Test this a bit more carefully (the if.. is new) |
|
1740 | # FIXME. Test this a bit more carefully (the if.. is new) | |
1744 | if local_ns is None and global_ns is None: |
|
1741 | if local_ns is None and global_ns is None: | |
1745 | self.user_global_ns.update(__main__.__dict__) |
|
1742 | self.user_global_ns.update(__main__.__dict__) | |
1746 |
|
1743 | |||
1747 | # make sure the tab-completer has the correct frame information, so it |
|
1744 | # make sure the tab-completer has the correct frame information, so it | |
1748 | # actually completes using the frame's locals/globals |
|
1745 | # actually completes using the frame's locals/globals | |
1749 | self.set_completer_frame() |
|
1746 | self.set_completer_frame() | |
1750 |
|
1747 | |||
1751 | # before activating the interactive mode, we need to make sure that |
|
1748 | # before activating the interactive mode, we need to make sure that | |
1752 | # all names in the builtin namespace needed by ipython point to |
|
1749 | # all names in the builtin namespace needed by ipython point to | |
1753 | # ourselves, and not to other instances. |
|
1750 | # ourselves, and not to other instances. | |
1754 | self.add_builtins() |
|
1751 | self.add_builtins() | |
1755 |
|
1752 | |||
1756 | self.interact(header) |
|
1753 | self.interact(header) | |
1757 |
|
1754 | |||
1758 | # now, purge out the user namespace from anything we might have added |
|
1755 | # now, purge out the user namespace from anything we might have added | |
1759 | # from the caller's local namespace |
|
1756 | # from the caller's local namespace | |
1760 | delvar = self.user_ns.pop |
|
1757 | delvar = self.user_ns.pop | |
1761 | for var in local_varnames: |
|
1758 | for var in local_varnames: | |
1762 | delvar(var,None) |
|
1759 | delvar(var,None) | |
1763 | # and clean builtins we may have overridden |
|
1760 | # and clean builtins we may have overridden | |
1764 | self.clean_builtins() |
|
1761 | self.clean_builtins() | |
1765 |
|
1762 | |||
1766 | def interact_prompt(self): |
|
1763 | def interact_prompt(self): | |
1767 | """ Print the prompt (in read-eval-print loop) |
|
1764 | """ Print the prompt (in read-eval-print loop) | |
1768 |
|
1765 | |||
1769 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1766 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not | |
1770 | used in standard IPython flow. |
|
1767 | used in standard IPython flow. | |
1771 | """ |
|
1768 | """ | |
1772 | if self.more: |
|
1769 | if self.more: | |
1773 | try: |
|
1770 | try: | |
1774 | prompt = self.hooks.generate_prompt(True) |
|
1771 | prompt = self.hooks.generate_prompt(True) | |
1775 | except: |
|
1772 | except: | |
1776 | self.showtraceback() |
|
1773 | self.showtraceback() | |
1777 | if self.autoindent: |
|
1774 | if self.autoindent: | |
1778 | self.rl_do_indent = True |
|
1775 | self.rl_do_indent = True | |
1779 |
|
1776 | |||
1780 | else: |
|
1777 | else: | |
1781 | try: |
|
1778 | try: | |
1782 | prompt = self.hooks.generate_prompt(False) |
|
1779 | prompt = self.hooks.generate_prompt(False) | |
1783 | except: |
|
1780 | except: | |
1784 | self.showtraceback() |
|
1781 | self.showtraceback() | |
1785 | self.write(prompt) |
|
1782 | self.write(prompt) | |
1786 |
|
1783 | |||
1787 | def interact_handle_input(self,line): |
|
1784 | def interact_handle_input(self,line): | |
1788 | """ Handle the input line (in read-eval-print loop) |
|
1785 | """ Handle the input line (in read-eval-print loop) | |
1789 |
|
1786 | |||
1790 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1787 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not | |
1791 | used in standard IPython flow. |
|
1788 | used in standard IPython flow. | |
1792 | """ |
|
1789 | """ | |
1793 | if line.lstrip() == line: |
|
1790 | if line.lstrip() == line: | |
1794 | self.shadowhist.add(line.strip()) |
|
1791 | self.shadowhist.add(line.strip()) | |
1795 | lineout = self.prefilter(line,self.more) |
|
1792 | lineout = self.prefilter(line,self.more) | |
1796 |
|
1793 | |||
1797 | if line.strip(): |
|
1794 | if line.strip(): | |
1798 | if self.more: |
|
1795 | if self.more: | |
1799 | self.input_hist_raw[-1] += '%s\n' % line |
|
1796 | self.input_hist_raw[-1] += '%s\n' % line | |
1800 | else: |
|
1797 | else: | |
1801 | self.input_hist_raw.append('%s\n' % line) |
|
1798 | self.input_hist_raw.append('%s\n' % line) | |
1802 |
|
1799 | |||
1803 |
|
1800 | |||
1804 | self.more = self.push(lineout) |
|
1801 | self.more = self.push(lineout) | |
1805 | if (self.SyntaxTB.last_syntax_error and |
|
1802 | if (self.SyntaxTB.last_syntax_error and | |
1806 | self.rc.autoedit_syntax): |
|
1803 | self.rc.autoedit_syntax): | |
1807 | self.edit_syntax_error() |
|
1804 | self.edit_syntax_error() | |
1808 |
|
1805 | |||
1809 | def interact_with_readline(self): |
|
1806 | def interact_with_readline(self): | |
1810 | """ Demo of using interact_handle_input, interact_prompt |
|
1807 | """ Demo of using interact_handle_input, interact_prompt | |
1811 |
|
1808 | |||
1812 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), |
|
1809 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), | |
1813 | it should work like this. |
|
1810 | it should work like this. | |
1814 | """ |
|
1811 | """ | |
1815 | self.readline_startup_hook(self.pre_readline) |
|
1812 | self.readline_startup_hook(self.pre_readline) | |
1816 | while not self.exit_now: |
|
1813 | while not self.exit_now: | |
1817 | self.interact_prompt() |
|
1814 | self.interact_prompt() | |
1818 | if self.more: |
|
1815 | if self.more: | |
1819 | self.rl_do_indent = True |
|
1816 | self.rl_do_indent = True | |
1820 | else: |
|
1817 | else: | |
1821 | self.rl_do_indent = False |
|
1818 | self.rl_do_indent = False | |
1822 | line = raw_input_original().decode(self.stdin_encoding) |
|
1819 | line = raw_input_original().decode(self.stdin_encoding) | |
1823 | self.interact_handle_input(line) |
|
1820 | self.interact_handle_input(line) | |
1824 |
|
1821 | |||
1825 |
|
1822 | |||
1826 | def interact(self, banner=None): |
|
1823 | def interact(self, banner=None): | |
1827 | """Closely emulate the interactive Python console. |
|
1824 | """Closely emulate the interactive Python console. | |
1828 |
|
1825 | |||
1829 | The optional banner argument specify the banner to print |
|
1826 | The optional banner argument specify the banner to print | |
1830 | before the first interaction; by default it prints a banner |
|
1827 | before the first interaction; by default it prints a banner | |
1831 | similar to the one printed by the real Python interpreter, |
|
1828 | similar to the one printed by the real Python interpreter, | |
1832 | followed by the current class name in parentheses (so as not |
|
1829 | followed by the current class name in parentheses (so as not | |
1833 | to confuse this with the real interpreter -- since it's so |
|
1830 | to confuse this with the real interpreter -- since it's so | |
1834 | close!). |
|
1831 | close!). | |
1835 |
|
1832 | |||
1836 | """ |
|
1833 | """ | |
1837 |
|
1834 | |||
1838 | if self.exit_now: |
|
1835 | if self.exit_now: | |
1839 | # batch run -> do not interact |
|
1836 | # batch run -> do not interact | |
1840 | return |
|
1837 | return | |
1841 | cprt = 'Type "copyright", "credits" or "license" for more information.' |
|
1838 | cprt = 'Type "copyright", "credits" or "license" for more information.' | |
1842 | if banner is None: |
|
1839 | if banner is None: | |
1843 | self.write("Python %s on %s\n%s\n(%s)\n" % |
|
1840 | self.write("Python %s on %s\n%s\n(%s)\n" % | |
1844 | (sys.version, sys.platform, cprt, |
|
1841 | (sys.version, sys.platform, cprt, | |
1845 | self.__class__.__name__)) |
|
1842 | self.__class__.__name__)) | |
1846 | else: |
|
1843 | else: | |
1847 | self.write(banner) |
|
1844 | self.write(banner) | |
1848 |
|
1845 | |||
1849 | more = 0 |
|
1846 | more = 0 | |
1850 |
|
1847 | |||
1851 | # Mark activity in the builtins |
|
1848 | # Mark activity in the builtins | |
1852 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
1849 | __builtin__.__dict__['__IPYTHON__active'] += 1 | |
1853 |
|
1850 | |||
1854 | if self.has_readline: |
|
1851 | if self.has_readline: | |
1855 | self.readline_startup_hook(self.pre_readline) |
|
1852 | self.readline_startup_hook(self.pre_readline) | |
1856 | # exit_now is set by a call to %Exit or %Quit, through the |
|
1853 | # exit_now is set by a call to %Exit or %Quit, through the | |
1857 | # ask_exit callback. |
|
1854 | # ask_exit callback. | |
1858 |
|
1855 | |||
1859 | while not self.exit_now: |
|
1856 | while not self.exit_now: | |
1860 | self.hooks.pre_prompt_hook() |
|
1857 | self.hooks.pre_prompt_hook() | |
1861 | if more: |
|
1858 | if more: | |
1862 | try: |
|
1859 | try: | |
1863 | prompt = self.hooks.generate_prompt(True) |
|
1860 | prompt = self.hooks.generate_prompt(True) | |
1864 | except: |
|
1861 | except: | |
1865 | self.showtraceback() |
|
1862 | self.showtraceback() | |
1866 | if self.autoindent: |
|
1863 | if self.autoindent: | |
1867 | self.rl_do_indent = True |
|
1864 | self.rl_do_indent = True | |
1868 |
|
1865 | |||
1869 | else: |
|
1866 | else: | |
1870 | try: |
|
1867 | try: | |
1871 | prompt = self.hooks.generate_prompt(False) |
|
1868 | prompt = self.hooks.generate_prompt(False) | |
1872 | except: |
|
1869 | except: | |
1873 | self.showtraceback() |
|
1870 | self.showtraceback() | |
1874 | try: |
|
1871 | try: | |
1875 | line = self.raw_input(prompt,more) |
|
1872 | line = self.raw_input(prompt,more) | |
1876 | if self.exit_now: |
|
1873 | if self.exit_now: | |
1877 | # quick exit on sys.std[in|out] close |
|
1874 | # quick exit on sys.std[in|out] close | |
1878 | break |
|
1875 | break | |
1879 | if self.autoindent: |
|
1876 | if self.autoindent: | |
1880 | self.rl_do_indent = False |
|
1877 | self.rl_do_indent = False | |
1881 |
|
1878 | |||
1882 | except KeyboardInterrupt: |
|
1879 | except KeyboardInterrupt: | |
1883 | #double-guard against keyboardinterrupts during kbdint handling |
|
1880 | #double-guard against keyboardinterrupts during kbdint handling | |
1884 | try: |
|
1881 | try: | |
1885 | self.write('\nKeyboardInterrupt\n') |
|
1882 | self.write('\nKeyboardInterrupt\n') | |
1886 | self.resetbuffer() |
|
1883 | self.resetbuffer() | |
1887 | # keep cache in sync with the prompt counter: |
|
1884 | # keep cache in sync with the prompt counter: | |
1888 | self.outputcache.prompt_count -= 1 |
|
1885 | self.outputcache.prompt_count -= 1 | |
1889 |
|
1886 | |||
1890 | if self.autoindent: |
|
1887 | if self.autoindent: | |
1891 | self.indent_current_nsp = 0 |
|
1888 | self.indent_current_nsp = 0 | |
1892 | more = 0 |
|
1889 | more = 0 | |
1893 | except KeyboardInterrupt: |
|
1890 | except KeyboardInterrupt: | |
1894 | pass |
|
1891 | pass | |
1895 | except EOFError: |
|
1892 | except EOFError: | |
1896 | if self.autoindent: |
|
1893 | if self.autoindent: | |
1897 | self.rl_do_indent = False |
|
1894 | self.rl_do_indent = False | |
1898 | self.readline_startup_hook(None) |
|
1895 | self.readline_startup_hook(None) | |
1899 | self.write('\n') |
|
1896 | self.write('\n') | |
1900 | self.exit() |
|
1897 | self.exit() | |
1901 | except bdb.BdbQuit: |
|
1898 | except bdb.BdbQuit: | |
1902 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
1899 | warn('The Python debugger has exited with a BdbQuit exception.\n' | |
1903 | 'Because of how pdb handles the stack, it is impossible\n' |
|
1900 | 'Because of how pdb handles the stack, it is impossible\n' | |
1904 | 'for IPython to properly format this particular exception.\n' |
|
1901 | 'for IPython to properly format this particular exception.\n' | |
1905 | 'IPython will resume normal operation.') |
|
1902 | 'IPython will resume normal operation.') | |
1906 | except: |
|
1903 | except: | |
1907 | # exceptions here are VERY RARE, but they can be triggered |
|
1904 | # exceptions here are VERY RARE, but they can be triggered | |
1908 | # asynchronously by signal handlers, for example. |
|
1905 | # asynchronously by signal handlers, for example. | |
1909 | self.showtraceback() |
|
1906 | self.showtraceback() | |
1910 | else: |
|
1907 | else: | |
1911 | more = self.push(line) |
|
1908 | more = self.push(line) | |
1912 | if (self.SyntaxTB.last_syntax_error and |
|
1909 | if (self.SyntaxTB.last_syntax_error and | |
1913 | self.rc.autoedit_syntax): |
|
1910 | self.rc.autoedit_syntax): | |
1914 | self.edit_syntax_error() |
|
1911 | self.edit_syntax_error() | |
1915 |
|
1912 | |||
1916 | # We are off again... |
|
1913 | # We are off again... | |
1917 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
1914 | __builtin__.__dict__['__IPYTHON__active'] -= 1 | |
1918 |
|
1915 | |||
1919 | def excepthook(self, etype, value, tb): |
|
1916 | def excepthook(self, etype, value, tb): | |
1920 | """One more defense for GUI apps that call sys.excepthook. |
|
1917 | """One more defense for GUI apps that call sys.excepthook. | |
1921 |
|
1918 | |||
1922 | GUI frameworks like wxPython trap exceptions and call |
|
1919 | GUI frameworks like wxPython trap exceptions and call | |
1923 | sys.excepthook themselves. I guess this is a feature that |
|
1920 | sys.excepthook themselves. I guess this is a feature that | |
1924 | enables them to keep running after exceptions that would |
|
1921 | enables them to keep running after exceptions that would | |
1925 | otherwise kill their mainloop. This is a bother for IPython |
|
1922 | otherwise kill their mainloop. This is a bother for IPython | |
1926 | which excepts to catch all of the program exceptions with a try: |
|
1923 | which excepts to catch all of the program exceptions with a try: | |
1927 | except: statement. |
|
1924 | except: statement. | |
1928 |
|
1925 | |||
1929 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1926 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1930 | any app directly invokes sys.excepthook, it will look to the user like |
|
1927 | any app directly invokes sys.excepthook, it will look to the user like | |
1931 | IPython crashed. In order to work around this, we can disable the |
|
1928 | IPython crashed. In order to work around this, we can disable the | |
1932 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1929 | CrashHandler and replace it with this excepthook instead, which prints a | |
1933 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1930 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1934 | call sys.excepthook will generate a regular-looking exception from |
|
1931 | call sys.excepthook will generate a regular-looking exception from | |
1935 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1932 | IPython, and the CrashHandler will only be triggered by real IPython | |
1936 | crashes. |
|
1933 | crashes. | |
1937 |
|
1934 | |||
1938 | This hook should be used sparingly, only in places which are not likely |
|
1935 | This hook should be used sparingly, only in places which are not likely | |
1939 | to be true IPython errors. |
|
1936 | to be true IPython errors. | |
1940 | """ |
|
1937 | """ | |
1941 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1938 | self.showtraceback((etype,value,tb),tb_offset=0) | |
1942 |
|
1939 | |||
1943 | def expand_aliases(self,fn,rest): |
|
1940 | def expand_aliases(self,fn,rest): | |
1944 | """ Expand multiple levels of aliases: |
|
1941 | """ Expand multiple levels of aliases: | |
1945 |
|
1942 | |||
1946 | if: |
|
1943 | if: | |
1947 |
|
1944 | |||
1948 | alias foo bar /tmp |
|
1945 | alias foo bar /tmp | |
1949 | alias baz foo |
|
1946 | alias baz foo | |
1950 |
|
1947 | |||
1951 | then: |
|
1948 | then: | |
1952 |
|
1949 | |||
1953 | baz huhhahhei -> bar /tmp huhhahhei |
|
1950 | baz huhhahhei -> bar /tmp huhhahhei | |
1954 |
|
1951 | |||
1955 | """ |
|
1952 | """ | |
1956 | line = fn + " " + rest |
|
1953 | line = fn + " " + rest | |
1957 |
|
1954 | |||
1958 |
done = |
|
1955 | done = set() | |
1959 | while 1: |
|
1956 | while 1: | |
1960 | pre,fn,rest = prefilter.splitUserInput(line, |
|
1957 | pre,fn,rest = prefilter.splitUserInput(line, | |
1961 | prefilter.shell_line_split) |
|
1958 | prefilter.shell_line_split) | |
1962 | if fn in self.alias_table: |
|
1959 | if fn in self.alias_table: | |
1963 | if fn in done: |
|
1960 | if fn in done: | |
1964 | warn("Cyclic alias definition, repeated '%s'" % fn) |
|
1961 | warn("Cyclic alias definition, repeated '%s'" % fn) | |
1965 | return "" |
|
1962 | return "" | |
1966 | done.add(fn) |
|
1963 | done.add(fn) | |
1967 |
|
1964 | |||
1968 | l2 = self.transform_alias(fn,rest) |
|
1965 | l2 = self.transform_alias(fn,rest) | |
1969 | # dir -> dir |
|
1966 | # dir -> dir | |
1970 | # print "alias",line, "->",l2 #dbg |
|
1967 | # print "alias",line, "->",l2 #dbg | |
1971 | if l2 == line: |
|
1968 | if l2 == line: | |
1972 | break |
|
1969 | break | |
1973 | # ls -> ls -F should not recurse forever |
|
1970 | # ls -> ls -F should not recurse forever | |
1974 | if l2.split(None,1)[0] == line.split(None,1)[0]: |
|
1971 | if l2.split(None,1)[0] == line.split(None,1)[0]: | |
1975 | line = l2 |
|
1972 | line = l2 | |
1976 | break |
|
1973 | break | |
1977 |
|
1974 | |||
1978 | line=l2 |
|
1975 | line=l2 | |
1979 |
|
1976 | |||
1980 |
|
1977 | |||
1981 | # print "al expand to",line #dbg |
|
1978 | # print "al expand to",line #dbg | |
1982 | else: |
|
1979 | else: | |
1983 | break |
|
1980 | break | |
1984 |
|
1981 | |||
1985 | return line |
|
1982 | return line | |
1986 |
|
1983 | |||
1987 | def transform_alias(self, alias,rest=''): |
|
1984 | def transform_alias(self, alias,rest=''): | |
1988 | """ Transform alias to system command string. |
|
1985 | """ Transform alias to system command string. | |
1989 | """ |
|
1986 | """ | |
1990 | trg = self.alias_table[alias] |
|
1987 | trg = self.alias_table[alias] | |
1991 |
|
1988 | |||
1992 | nargs,cmd = trg |
|
1989 | nargs,cmd = trg | |
1993 | # print trg #dbg |
|
1990 | # print trg #dbg | |
1994 | if ' ' in cmd and os.path.isfile(cmd): |
|
1991 | if ' ' in cmd and os.path.isfile(cmd): | |
1995 | cmd = '"%s"' % cmd |
|
1992 | cmd = '"%s"' % cmd | |
1996 |
|
1993 | |||
1997 | # Expand the %l special to be the user's input line |
|
1994 | # Expand the %l special to be the user's input line | |
1998 | if cmd.find('%l') >= 0: |
|
1995 | if cmd.find('%l') >= 0: | |
1999 | cmd = cmd.replace('%l',rest) |
|
1996 | cmd = cmd.replace('%l',rest) | |
2000 | rest = '' |
|
1997 | rest = '' | |
2001 | if nargs==0: |
|
1998 | if nargs==0: | |
2002 | # Simple, argument-less aliases |
|
1999 | # Simple, argument-less aliases | |
2003 | cmd = '%s %s' % (cmd,rest) |
|
2000 | cmd = '%s %s' % (cmd,rest) | |
2004 | else: |
|
2001 | else: | |
2005 | # Handle aliases with positional arguments |
|
2002 | # Handle aliases with positional arguments | |
2006 | args = rest.split(None,nargs) |
|
2003 | args = rest.split(None,nargs) | |
2007 | if len(args)< nargs: |
|
2004 | if len(args)< nargs: | |
2008 | error('Alias <%s> requires %s arguments, %s given.' % |
|
2005 | error('Alias <%s> requires %s arguments, %s given.' % | |
2009 | (alias,nargs,len(args))) |
|
2006 | (alias,nargs,len(args))) | |
2010 | return None |
|
2007 | return None | |
2011 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) |
|
2008 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) | |
2012 | # Now call the macro, evaluating in the user's namespace |
|
2009 | # Now call the macro, evaluating in the user's namespace | |
2013 | #print 'new command: <%r>' % cmd # dbg |
|
2010 | #print 'new command: <%r>' % cmd # dbg | |
2014 | return cmd |
|
2011 | return cmd | |
2015 |
|
2012 | |||
2016 | def call_alias(self,alias,rest=''): |
|
2013 | def call_alias(self,alias,rest=''): | |
2017 | """Call an alias given its name and the rest of the line. |
|
2014 | """Call an alias given its name and the rest of the line. | |
2018 |
|
2015 | |||
2019 | This is only used to provide backwards compatibility for users of |
|
2016 | This is only used to provide backwards compatibility for users of | |
2020 | ipalias(), use of which is not recommended for anymore.""" |
|
2017 | ipalias(), use of which is not recommended for anymore.""" | |
2021 |
|
2018 | |||
2022 | # Now call the macro, evaluating in the user's namespace |
|
2019 | # Now call the macro, evaluating in the user's namespace | |
2023 | cmd = self.transform_alias(alias, rest) |
|
2020 | cmd = self.transform_alias(alias, rest) | |
2024 | try: |
|
2021 | try: | |
2025 | self.system(cmd) |
|
2022 | self.system(cmd) | |
2026 | except: |
|
2023 | except: | |
2027 | self.showtraceback() |
|
2024 | self.showtraceback() | |
2028 |
|
2025 | |||
2029 | def indent_current_str(self): |
|
2026 | def indent_current_str(self): | |
2030 | """return the current level of indentation as a string""" |
|
2027 | """return the current level of indentation as a string""" | |
2031 | return self.indent_current_nsp * ' ' |
|
2028 | return self.indent_current_nsp * ' ' | |
2032 |
|
2029 | |||
2033 | def autoindent_update(self,line): |
|
2030 | def autoindent_update(self,line): | |
2034 | """Keep track of the indent level.""" |
|
2031 | """Keep track of the indent level.""" | |
2035 |
|
2032 | |||
2036 | #debugx('line') |
|
2033 | #debugx('line') | |
2037 | #debugx('self.indent_current_nsp') |
|
2034 | #debugx('self.indent_current_nsp') | |
2038 | if self.autoindent: |
|
2035 | if self.autoindent: | |
2039 | if line: |
|
2036 | if line: | |
2040 | inisp = num_ini_spaces(line) |
|
2037 | inisp = num_ini_spaces(line) | |
2041 | if inisp < self.indent_current_nsp: |
|
2038 | if inisp < self.indent_current_nsp: | |
2042 | self.indent_current_nsp = inisp |
|
2039 | self.indent_current_nsp = inisp | |
2043 |
|
2040 | |||
2044 | if line[-1] == ':': |
|
2041 | if line[-1] == ':': | |
2045 | self.indent_current_nsp += 4 |
|
2042 | self.indent_current_nsp += 4 | |
2046 | elif dedent_re.match(line): |
|
2043 | elif dedent_re.match(line): | |
2047 | self.indent_current_nsp -= 4 |
|
2044 | self.indent_current_nsp -= 4 | |
2048 | else: |
|
2045 | else: | |
2049 | self.indent_current_nsp = 0 |
|
2046 | self.indent_current_nsp = 0 | |
2050 |
|
2047 | |||
2051 | def runlines(self,lines): |
|
2048 | def runlines(self,lines): | |
2052 | """Run a string of one or more lines of source. |
|
2049 | """Run a string of one or more lines of source. | |
2053 |
|
2050 | |||
2054 | This method is capable of running a string containing multiple source |
|
2051 | This method is capable of running a string containing multiple source | |
2055 | lines, as if they had been entered at the IPython prompt. Since it |
|
2052 | lines, as if they had been entered at the IPython prompt. Since it | |
2056 | exposes IPython's processing machinery, the given strings can contain |
|
2053 | exposes IPython's processing machinery, the given strings can contain | |
2057 | magic calls (%magic), special shell access (!cmd), etc.""" |
|
2054 | magic calls (%magic), special shell access (!cmd), etc.""" | |
2058 |
|
2055 | |||
2059 | # We must start with a clean buffer, in case this is run from an |
|
2056 | # We must start with a clean buffer, in case this is run from an | |
2060 | # interactive IPython session (via a magic, for example). |
|
2057 | # interactive IPython session (via a magic, for example). | |
2061 | self.resetbuffer() |
|
2058 | self.resetbuffer() | |
2062 | lines = lines.split('\n') |
|
2059 | lines = lines.split('\n') | |
2063 | more = 0 |
|
2060 | more = 0 | |
2064 |
|
2061 | |||
2065 | for line in lines: |
|
2062 | for line in lines: | |
2066 | # skip blank lines so we don't mess up the prompt counter, but do |
|
2063 | # skip blank lines so we don't mess up the prompt counter, but do | |
2067 | # NOT skip even a blank line if we are in a code block (more is |
|
2064 | # NOT skip even a blank line if we are in a code block (more is | |
2068 | # true) |
|
2065 | # true) | |
2069 |
|
2066 | |||
2070 | if line or more: |
|
2067 | if line or more: | |
2071 | # push to raw history, so hist line numbers stay in sync |
|
2068 | # push to raw history, so hist line numbers stay in sync | |
2072 | self.input_hist_raw.append("# " + line + "\n") |
|
2069 | self.input_hist_raw.append("# " + line + "\n") | |
2073 | more = self.push(self.prefilter(line,more)) |
|
2070 | more = self.push(self.prefilter(line,more)) | |
2074 | # IPython's runsource returns None if there was an error |
|
2071 | # IPython's runsource returns None if there was an error | |
2075 | # compiling the code. This allows us to stop processing right |
|
2072 | # compiling the code. This allows us to stop processing right | |
2076 | # away, so the user gets the error message at the right place. |
|
2073 | # away, so the user gets the error message at the right place. | |
2077 | if more is None: |
|
2074 | if more is None: | |
2078 | break |
|
2075 | break | |
2079 | else: |
|
2076 | else: | |
2080 | self.input_hist_raw.append("\n") |
|
2077 | self.input_hist_raw.append("\n") | |
2081 | # final newline in case the input didn't have it, so that the code |
|
2078 | # final newline in case the input didn't have it, so that the code | |
2082 | # actually does get executed |
|
2079 | # actually does get executed | |
2083 | if more: |
|
2080 | if more: | |
2084 | self.push('\n') |
|
2081 | self.push('\n') | |
2085 |
|
2082 | |||
2086 | def runsource(self, source, filename='<input>', symbol='single'): |
|
2083 | def runsource(self, source, filename='<input>', symbol='single'): | |
2087 | """Compile and run some source in the interpreter. |
|
2084 | """Compile and run some source in the interpreter. | |
2088 |
|
2085 | |||
2089 | Arguments are as for compile_command(). |
|
2086 | Arguments are as for compile_command(). | |
2090 |
|
2087 | |||
2091 | One several things can happen: |
|
2088 | One several things can happen: | |
2092 |
|
2089 | |||
2093 | 1) The input is incorrect; compile_command() raised an |
|
2090 | 1) The input is incorrect; compile_command() raised an | |
2094 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2091 | exception (SyntaxError or OverflowError). A syntax traceback | |
2095 | will be printed by calling the showsyntaxerror() method. |
|
2092 | will be printed by calling the showsyntaxerror() method. | |
2096 |
|
2093 | |||
2097 | 2) The input is incomplete, and more input is required; |
|
2094 | 2) The input is incomplete, and more input is required; | |
2098 | compile_command() returned None. Nothing happens. |
|
2095 | compile_command() returned None. Nothing happens. | |
2099 |
|
2096 | |||
2100 | 3) The input is complete; compile_command() returned a code |
|
2097 | 3) The input is complete; compile_command() returned a code | |
2101 | object. The code is executed by calling self.runcode() (which |
|
2098 | object. The code is executed by calling self.runcode() (which | |
2102 | also handles run-time exceptions, except for SystemExit). |
|
2099 | also handles run-time exceptions, except for SystemExit). | |
2103 |
|
2100 | |||
2104 | The return value is: |
|
2101 | The return value is: | |
2105 |
|
2102 | |||
2106 | - True in case 2 |
|
2103 | - True in case 2 | |
2107 |
|
2104 | |||
2108 | - False in the other cases, unless an exception is raised, where |
|
2105 | - False in the other cases, unless an exception is raised, where | |
2109 | None is returned instead. This can be used by external callers to |
|
2106 | None is returned instead. This can be used by external callers to | |
2110 | know whether to continue feeding input or not. |
|
2107 | know whether to continue feeding input or not. | |
2111 |
|
2108 | |||
2112 | The return value can be used to decide whether to use sys.ps1 or |
|
2109 | The return value can be used to decide whether to use sys.ps1 or | |
2113 | sys.ps2 to prompt the next line.""" |
|
2110 | sys.ps2 to prompt the next line.""" | |
2114 |
|
2111 | |||
2115 | # if the source code has leading blanks, add 'if 1:\n' to it |
|
2112 | # if the source code has leading blanks, add 'if 1:\n' to it | |
2116 | # this allows execution of indented pasted code. It is tempting |
|
2113 | # this allows execution of indented pasted code. It is tempting | |
2117 | # to add '\n' at the end of source to run commands like ' a=1' |
|
2114 | # to add '\n' at the end of source to run commands like ' a=1' | |
2118 | # directly, but this fails for more complicated scenarios |
|
2115 | # directly, but this fails for more complicated scenarios | |
2119 | source=source.encode(self.stdin_encoding) |
|
2116 | source=source.encode(self.stdin_encoding) | |
2120 | if source[:1] in [' ', '\t']: |
|
2117 | if source[:1] in [' ', '\t']: | |
2121 | source = 'if 1:\n%s' % source |
|
2118 | source = 'if 1:\n%s' % source | |
2122 |
|
2119 | |||
2123 | try: |
|
2120 | try: | |
2124 | code = self.compile(source,filename,symbol) |
|
2121 | code = self.compile(source,filename,symbol) | |
2125 | except (OverflowError, SyntaxError, ValueError, TypeError): |
|
2122 | except (OverflowError, SyntaxError, ValueError, TypeError): | |
2126 | # Case 1 |
|
2123 | # Case 1 | |
2127 | self.showsyntaxerror(filename) |
|
2124 | self.showsyntaxerror(filename) | |
2128 | return None |
|
2125 | return None | |
2129 |
|
2126 | |||
2130 | if code is None: |
|
2127 | if code is None: | |
2131 | # Case 2 |
|
2128 | # Case 2 | |
2132 | return True |
|
2129 | return True | |
2133 |
|
2130 | |||
2134 | # Case 3 |
|
2131 | # Case 3 | |
2135 | # We store the code object so that threaded shells and |
|
2132 | # We store the code object so that threaded shells and | |
2136 | # custom exception handlers can access all this info if needed. |
|
2133 | # custom exception handlers can access all this info if needed. | |
2137 | # The source corresponding to this can be obtained from the |
|
2134 | # The source corresponding to this can be obtained from the | |
2138 | # buffer attribute as '\n'.join(self.buffer). |
|
2135 | # buffer attribute as '\n'.join(self.buffer). | |
2139 | self.code_to_run = code |
|
2136 | self.code_to_run = code | |
2140 | # now actually execute the code object |
|
2137 | # now actually execute the code object | |
2141 | if self.runcode(code) == 0: |
|
2138 | if self.runcode(code) == 0: | |
2142 | return False |
|
2139 | return False | |
2143 | else: |
|
2140 | else: | |
2144 | return None |
|
2141 | return None | |
2145 |
|
2142 | |||
2146 | def runcode(self,code_obj): |
|
2143 | def runcode(self,code_obj): | |
2147 | """Execute a code object. |
|
2144 | """Execute a code object. | |
2148 |
|
2145 | |||
2149 | When an exception occurs, self.showtraceback() is called to display a |
|
2146 | When an exception occurs, self.showtraceback() is called to display a | |
2150 | traceback. |
|
2147 | traceback. | |
2151 |
|
2148 | |||
2152 | Return value: a flag indicating whether the code to be run completed |
|
2149 | Return value: a flag indicating whether the code to be run completed | |
2153 | successfully: |
|
2150 | successfully: | |
2154 |
|
2151 | |||
2155 | - 0: successful execution. |
|
2152 | - 0: successful execution. | |
2156 | - 1: an error occurred. |
|
2153 | - 1: an error occurred. | |
2157 | """ |
|
2154 | """ | |
2158 |
|
2155 | |||
2159 | # Set our own excepthook in case the user code tries to call it |
|
2156 | # Set our own excepthook in case the user code tries to call it | |
2160 | # directly, so that the IPython crash handler doesn't get triggered |
|
2157 | # directly, so that the IPython crash handler doesn't get triggered | |
2161 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2158 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
2162 |
|
2159 | |||
2163 | # we save the original sys.excepthook in the instance, in case config |
|
2160 | # we save the original sys.excepthook in the instance, in case config | |
2164 | # code (such as magics) needs access to it. |
|
2161 | # code (such as magics) needs access to it. | |
2165 | self.sys_excepthook = old_excepthook |
|
2162 | self.sys_excepthook = old_excepthook | |
2166 | outflag = 1 # happens in more places, so it's easier as default |
|
2163 | outflag = 1 # happens in more places, so it's easier as default | |
2167 | try: |
|
2164 | try: | |
2168 | try: |
|
2165 | try: | |
2169 | self.hooks.pre_runcode_hook() |
|
2166 | self.hooks.pre_runcode_hook() | |
2170 | exec code_obj in self.user_global_ns, self.user_ns |
|
2167 | exec code_obj in self.user_global_ns, self.user_ns | |
2171 | finally: |
|
2168 | finally: | |
2172 | # Reset our crash handler in place |
|
2169 | # Reset our crash handler in place | |
2173 | sys.excepthook = old_excepthook |
|
2170 | sys.excepthook = old_excepthook | |
2174 | except SystemExit: |
|
2171 | except SystemExit: | |
2175 | self.resetbuffer() |
|
2172 | self.resetbuffer() | |
2176 | self.showtraceback() |
|
2173 | self.showtraceback() | |
2177 | warn("Type %exit or %quit to exit IPython " |
|
2174 | warn("Type %exit or %quit to exit IPython " | |
2178 | "(%Exit or %Quit do so unconditionally).",level=1) |
|
2175 | "(%Exit or %Quit do so unconditionally).",level=1) | |
2179 | except self.custom_exceptions: |
|
2176 | except self.custom_exceptions: | |
2180 | etype,value,tb = sys.exc_info() |
|
2177 | etype,value,tb = sys.exc_info() | |
2181 | self.CustomTB(etype,value,tb) |
|
2178 | self.CustomTB(etype,value,tb) | |
2182 | except: |
|
2179 | except: | |
2183 | self.showtraceback() |
|
2180 | self.showtraceback() | |
2184 | else: |
|
2181 | else: | |
2185 | outflag = 0 |
|
2182 | outflag = 0 | |
2186 | if softspace(sys.stdout, 0): |
|
2183 | if softspace(sys.stdout, 0): | |
2187 |
|
2184 | |||
2188 | # Flush out code object which has been run (and source) |
|
2185 | # Flush out code object which has been run (and source) | |
2189 | self.code_to_run = None |
|
2186 | self.code_to_run = None | |
2190 | return outflag |
|
2187 | return outflag | |
2191 |
|
2188 | |||
2192 | def push(self, line): |
|
2189 | def push(self, line): | |
2193 | """Push a line to the interpreter. |
|
2190 | """Push a line to the interpreter. | |
2194 |
|
2191 | |||
2195 | The line should not have a trailing newline; it may have |
|
2192 | The line should not have a trailing newline; it may have | |
2196 | internal newlines. The line is appended to a buffer and the |
|
2193 | internal newlines. The line is appended to a buffer and the | |
2197 | interpreter's runsource() method is called with the |
|
2194 | interpreter's runsource() method is called with the | |
2198 | concatenated contents of the buffer as source. If this |
|
2195 | concatenated contents of the buffer as source. If this | |
2199 | indicates that the command was executed or invalid, the buffer |
|
2196 | indicates that the command was executed or invalid, the buffer | |
2200 | is reset; otherwise, the command is incomplete, and the buffer |
|
2197 | is reset; otherwise, the command is incomplete, and the buffer | |
2201 | is left as it was after the line was appended. The return |
|
2198 | is left as it was after the line was appended. The return | |
2202 | value is 1 if more input is required, 0 if the line was dealt |
|
2199 | value is 1 if more input is required, 0 if the line was dealt | |
2203 | with in some way (this is the same as runsource()). |
|
2200 | with in some way (this is the same as runsource()). | |
2204 | """ |
|
2201 | """ | |
2205 |
|
2202 | |||
2206 | # autoindent management should be done here, and not in the |
|
2203 | # autoindent management should be done here, and not in the | |
2207 | # interactive loop, since that one is only seen by keyboard input. We |
|
2204 | # interactive loop, since that one is only seen by keyboard input. We | |
2208 | # need this done correctly even for code run via runlines (which uses |
|
2205 | # need this done correctly even for code run via runlines (which uses | |
2209 | # push). |
|
2206 | # push). | |
2210 |
|
2207 | |||
2211 | #print 'push line: <%s>' % line # dbg |
|
2208 | #print 'push line: <%s>' % line # dbg | |
2212 | for subline in line.splitlines(): |
|
2209 | for subline in line.splitlines(): | |
2213 | self.autoindent_update(subline) |
|
2210 | self.autoindent_update(subline) | |
2214 | self.buffer.append(line) |
|
2211 | self.buffer.append(line) | |
2215 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
2212 | more = self.runsource('\n'.join(self.buffer), self.filename) | |
2216 | if not more: |
|
2213 | if not more: | |
2217 | self.resetbuffer() |
|
2214 | self.resetbuffer() | |
2218 | return more |
|
2215 | return more | |
2219 |
|
2216 | |||
2220 | def split_user_input(self, line): |
|
2217 | def split_user_input(self, line): | |
2221 | # This is really a hold-over to support ipapi and some extensions |
|
2218 | # This is really a hold-over to support ipapi and some extensions | |
2222 | return prefilter.splitUserInput(line) |
|
2219 | return prefilter.splitUserInput(line) | |
2223 |
|
2220 | |||
2224 | def resetbuffer(self): |
|
2221 | def resetbuffer(self): | |
2225 | """Reset the input buffer.""" |
|
2222 | """Reset the input buffer.""" | |
2226 | self.buffer[:] = [] |
|
2223 | self.buffer[:] = [] | |
2227 |
|
2224 | |||
2228 | def raw_input(self,prompt='',continue_prompt=False): |
|
2225 | def raw_input(self,prompt='',continue_prompt=False): | |
2229 | """Write a prompt and read a line. |
|
2226 | """Write a prompt and read a line. | |
2230 |
|
2227 | |||
2231 | The returned line does not include the trailing newline. |
|
2228 | The returned line does not include the trailing newline. | |
2232 | When the user enters the EOF key sequence, EOFError is raised. |
|
2229 | When the user enters the EOF key sequence, EOFError is raised. | |
2233 |
|
2230 | |||
2234 | Optional inputs: |
|
2231 | Optional inputs: | |
2235 |
|
2232 | |||
2236 | - prompt(''): a string to be printed to prompt the user. |
|
2233 | - prompt(''): a string to be printed to prompt the user. | |
2237 |
|
2234 | |||
2238 | - continue_prompt(False): whether this line is the first one or a |
|
2235 | - continue_prompt(False): whether this line is the first one or a | |
2239 | continuation in a sequence of inputs. |
|
2236 | continuation in a sequence of inputs. | |
2240 | """ |
|
2237 | """ | |
2241 |
|
2238 | |||
2242 | # Code run by the user may have modified the readline completer state. |
|
2239 | # Code run by the user may have modified the readline completer state. | |
2243 | # We must ensure that our completer is back in place. |
|
2240 | # We must ensure that our completer is back in place. | |
2244 | if self.has_readline: |
|
2241 | if self.has_readline: | |
2245 | self.set_completer() |
|
2242 | self.set_completer() | |
2246 |
|
2243 | |||
2247 | try: |
|
2244 | try: | |
2248 | line = raw_input_original(prompt).decode(self.stdin_encoding) |
|
2245 | line = raw_input_original(prompt).decode(self.stdin_encoding) | |
2249 | except ValueError: |
|
2246 | except ValueError: | |
2250 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
2247 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" | |
2251 | " or sys.stdout.close()!\nExiting IPython!") |
|
2248 | " or sys.stdout.close()!\nExiting IPython!") | |
2252 | self.ask_exit() |
|
2249 | self.ask_exit() | |
2253 | return "" |
|
2250 | return "" | |
2254 |
|
2251 | |||
2255 | # Try to be reasonably smart about not re-indenting pasted input more |
|
2252 | # Try to be reasonably smart about not re-indenting pasted input more | |
2256 | # than necessary. We do this by trimming out the auto-indent initial |
|
2253 | # than necessary. We do this by trimming out the auto-indent initial | |
2257 | # spaces, if the user's actual input started itself with whitespace. |
|
2254 | # spaces, if the user's actual input started itself with whitespace. | |
2258 | #debugx('self.buffer[-1]') |
|
2255 | #debugx('self.buffer[-1]') | |
2259 |
|
2256 | |||
2260 | if self.autoindent: |
|
2257 | if self.autoindent: | |
2261 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
2258 | if num_ini_spaces(line) > self.indent_current_nsp: | |
2262 | line = line[self.indent_current_nsp:] |
|
2259 | line = line[self.indent_current_nsp:] | |
2263 | self.indent_current_nsp = 0 |
|
2260 | self.indent_current_nsp = 0 | |
2264 |
|
2261 | |||
2265 | # store the unfiltered input before the user has any chance to modify |
|
2262 | # store the unfiltered input before the user has any chance to modify | |
2266 | # it. |
|
2263 | # it. | |
2267 | if line.strip(): |
|
2264 | if line.strip(): | |
2268 | if continue_prompt: |
|
2265 | if continue_prompt: | |
2269 | self.input_hist_raw[-1] += '%s\n' % line |
|
2266 | self.input_hist_raw[-1] += '%s\n' % line | |
2270 | if self.has_readline: # and some config option is set? |
|
2267 | if self.has_readline: # and some config option is set? | |
2271 | try: |
|
2268 | try: | |
2272 | histlen = self.readline.get_current_history_length() |
|
2269 | histlen = self.readline.get_current_history_length() | |
2273 | if histlen > 1: |
|
2270 | if histlen > 1: | |
2274 | newhist = self.input_hist_raw[-1].rstrip() |
|
2271 | newhist = self.input_hist_raw[-1].rstrip() | |
2275 | self.readline.remove_history_item(histlen-1) |
|
2272 | self.readline.remove_history_item(histlen-1) | |
2276 | self.readline.replace_history_item(histlen-2, |
|
2273 | self.readline.replace_history_item(histlen-2, | |
2277 | newhist.encode(self.stdin_encoding)) |
|
2274 | newhist.encode(self.stdin_encoding)) | |
2278 | except AttributeError: |
|
2275 | except AttributeError: | |
2279 | pass # re{move,place}_history_item are new in 2.4. |
|
2276 | pass # re{move,place}_history_item are new in 2.4. | |
2280 | else: |
|
2277 | else: | |
2281 | self.input_hist_raw.append('%s\n' % line) |
|
2278 | self.input_hist_raw.append('%s\n' % line) | |
2282 | # only entries starting at first column go to shadow history |
|
2279 | # only entries starting at first column go to shadow history | |
2283 | if line.lstrip() == line: |
|
2280 | if line.lstrip() == line: | |
2284 | self.shadowhist.add(line.strip()) |
|
2281 | self.shadowhist.add(line.strip()) | |
2285 | elif not continue_prompt: |
|
2282 | elif not continue_prompt: | |
2286 | self.input_hist_raw.append('\n') |
|
2283 | self.input_hist_raw.append('\n') | |
2287 | try: |
|
2284 | try: | |
2288 | lineout = self.prefilter(line,continue_prompt) |
|
2285 | lineout = self.prefilter(line,continue_prompt) | |
2289 | except: |
|
2286 | except: | |
2290 | # blanket except, in case a user-defined prefilter crashes, so it |
|
2287 | # blanket except, in case a user-defined prefilter crashes, so it | |
2291 | # can't take all of ipython with it. |
|
2288 | # can't take all of ipython with it. | |
2292 | self.showtraceback() |
|
2289 | self.showtraceback() | |
2293 | return '' |
|
2290 | return '' | |
2294 | else: |
|
2291 | else: | |
2295 | return lineout |
|
2292 | return lineout | |
2296 |
|
2293 | |||
2297 | def _prefilter(self, line, continue_prompt): |
|
2294 | def _prefilter(self, line, continue_prompt): | |
2298 | """Calls different preprocessors, depending on the form of line.""" |
|
2295 | """Calls different preprocessors, depending on the form of line.""" | |
2299 |
|
2296 | |||
2300 | # All handlers *must* return a value, even if it's blank (''). |
|
2297 | # All handlers *must* return a value, even if it's blank (''). | |
2301 |
|
2298 | |||
2302 | # Lines are NOT logged here. Handlers should process the line as |
|
2299 | # Lines are NOT logged here. Handlers should process the line as | |
2303 | # needed, update the cache AND log it (so that the input cache array |
|
2300 | # needed, update the cache AND log it (so that the input cache array | |
2304 | # stays synced). |
|
2301 | # stays synced). | |
2305 |
|
2302 | |||
2306 | #..................................................................... |
|
2303 | #..................................................................... | |
2307 | # Code begins |
|
2304 | # Code begins | |
2308 |
|
2305 | |||
2309 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg |
|
2306 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg | |
2310 |
|
2307 | |||
2311 | # save the line away in case we crash, so the post-mortem handler can |
|
2308 | # save the line away in case we crash, so the post-mortem handler can | |
2312 | # record it |
|
2309 | # record it | |
2313 | self._last_input_line = line |
|
2310 | self._last_input_line = line | |
2314 |
|
2311 | |||
2315 | #print '***line: <%s>' % line # dbg |
|
2312 | #print '***line: <%s>' % line # dbg | |
2316 |
|
2313 | |||
2317 | if not line: |
|
2314 | if not line: | |
2318 | # Return immediately on purely empty lines, so that if the user |
|
2315 | # Return immediately on purely empty lines, so that if the user | |
2319 | # previously typed some whitespace that started a continuation |
|
2316 | # previously typed some whitespace that started a continuation | |
2320 | # prompt, he can break out of that loop with just an empty line. |
|
2317 | # prompt, he can break out of that loop with just an empty line. | |
2321 | # This is how the default python prompt works. |
|
2318 | # This is how the default python prompt works. | |
2322 |
|
2319 | |||
2323 | # Only return if the accumulated input buffer was just whitespace! |
|
2320 | # Only return if the accumulated input buffer was just whitespace! | |
2324 | if ''.join(self.buffer).isspace(): |
|
2321 | if ''.join(self.buffer).isspace(): | |
2325 | self.buffer[:] = [] |
|
2322 | self.buffer[:] = [] | |
2326 | return '' |
|
2323 | return '' | |
2327 |
|
2324 | |||
2328 | line_info = prefilter.LineInfo(line, continue_prompt) |
|
2325 | line_info = prefilter.LineInfo(line, continue_prompt) | |
2329 |
|
2326 | |||
2330 | # the input history needs to track even empty lines |
|
2327 | # the input history needs to track even empty lines | |
2331 | stripped = line.strip() |
|
2328 | stripped = line.strip() | |
2332 |
|
2329 | |||
2333 | if not stripped: |
|
2330 | if not stripped: | |
2334 | if not continue_prompt: |
|
2331 | if not continue_prompt: | |
2335 | self.outputcache.prompt_count -= 1 |
|
2332 | self.outputcache.prompt_count -= 1 | |
2336 | return self.handle_normal(line_info) |
|
2333 | return self.handle_normal(line_info) | |
2337 |
|
2334 | |||
2338 | # print '***cont',continue_prompt # dbg |
|
2335 | # print '***cont',continue_prompt # dbg | |
2339 | # special handlers are only allowed for single line statements |
|
2336 | # special handlers are only allowed for single line statements | |
2340 | if continue_prompt and not self.rc.multi_line_specials: |
|
2337 | if continue_prompt and not self.rc.multi_line_specials: | |
2341 | return self.handle_normal(line_info) |
|
2338 | return self.handle_normal(line_info) | |
2342 |
|
2339 | |||
2343 |
|
2340 | |||
2344 | # See whether any pre-existing handler can take care of it |
|
2341 | # See whether any pre-existing handler can take care of it | |
2345 | rewritten = self.hooks.input_prefilter(stripped) |
|
2342 | rewritten = self.hooks.input_prefilter(stripped) | |
2346 | if rewritten != stripped: # ok, some prefilter did something |
|
2343 | if rewritten != stripped: # ok, some prefilter did something | |
2347 | rewritten = line_info.pre + rewritten # add indentation |
|
2344 | rewritten = line_info.pre + rewritten # add indentation | |
2348 | return self.handle_normal(prefilter.LineInfo(rewritten, |
|
2345 | return self.handle_normal(prefilter.LineInfo(rewritten, | |
2349 | continue_prompt)) |
|
2346 | continue_prompt)) | |
2350 |
|
2347 | |||
2351 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2348 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
2352 |
|
2349 | |||
2353 | return prefilter.prefilter(line_info, self) |
|
2350 | return prefilter.prefilter(line_info, self) | |
2354 |
|
2351 | |||
2355 |
|
2352 | |||
2356 | def _prefilter_dumb(self, line, continue_prompt): |
|
2353 | def _prefilter_dumb(self, line, continue_prompt): | |
2357 | """simple prefilter function, for debugging""" |
|
2354 | """simple prefilter function, for debugging""" | |
2358 | return self.handle_normal(line,continue_prompt) |
|
2355 | return self.handle_normal(line,continue_prompt) | |
2359 |
|
2356 | |||
2360 |
|
2357 | |||
2361 | def multiline_prefilter(self, line, continue_prompt): |
|
2358 | def multiline_prefilter(self, line, continue_prompt): | |
2362 | """ Run _prefilter for each line of input |
|
2359 | """ Run _prefilter for each line of input | |
2363 |
|
2360 | |||
2364 | Covers cases where there are multiple lines in the user entry, |
|
2361 | Covers cases where there are multiple lines in the user entry, | |
2365 | which is the case when the user goes back to a multiline history |
|
2362 | which is the case when the user goes back to a multiline history | |
2366 | entry and presses enter. |
|
2363 | entry and presses enter. | |
2367 |
|
2364 | |||
2368 | """ |
|
2365 | """ | |
2369 | out = [] |
|
2366 | out = [] | |
2370 | for l in line.rstrip('\n').split('\n'): |
|
2367 | for l in line.rstrip('\n').split('\n'): | |
2371 | out.append(self._prefilter(l, continue_prompt)) |
|
2368 | out.append(self._prefilter(l, continue_prompt)) | |
2372 | return '\n'.join(out) |
|
2369 | return '\n'.join(out) | |
2373 |
|
2370 | |||
2374 | # Set the default prefilter() function (this can be user-overridden) |
|
2371 | # Set the default prefilter() function (this can be user-overridden) | |
2375 | prefilter = multiline_prefilter |
|
2372 | prefilter = multiline_prefilter | |
2376 |
|
2373 | |||
2377 | def handle_normal(self,line_info): |
|
2374 | def handle_normal(self,line_info): | |
2378 | """Handle normal input lines. Use as a template for handlers.""" |
|
2375 | """Handle normal input lines. Use as a template for handlers.""" | |
2379 |
|
2376 | |||
2380 | # With autoindent on, we need some way to exit the input loop, and I |
|
2377 | # With autoindent on, we need some way to exit the input loop, and I | |
2381 | # don't want to force the user to have to backspace all the way to |
|
2378 | # don't want to force the user to have to backspace all the way to | |
2382 | # clear the line. The rule will be in this case, that either two |
|
2379 | # clear the line. The rule will be in this case, that either two | |
2383 | # lines of pure whitespace in a row, or a line of pure whitespace but |
|
2380 | # lines of pure whitespace in a row, or a line of pure whitespace but | |
2384 | # of a size different to the indent level, will exit the input loop. |
|
2381 | # of a size different to the indent level, will exit the input loop. | |
2385 | line = line_info.line |
|
2382 | line = line_info.line | |
2386 | continue_prompt = line_info.continue_prompt |
|
2383 | continue_prompt = line_info.continue_prompt | |
2387 |
|
2384 | |||
2388 | if (continue_prompt and self.autoindent and line.isspace() and |
|
2385 | if (continue_prompt and self.autoindent and line.isspace() and | |
2389 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or |
|
2386 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or | |
2390 | (self.buffer[-1]).isspace() )): |
|
2387 | (self.buffer[-1]).isspace() )): | |
2391 | line = '' |
|
2388 | line = '' | |
2392 |
|
2389 | |||
2393 | self.log(line,line,continue_prompt) |
|
2390 | self.log(line,line,continue_prompt) | |
2394 | return line |
|
2391 | return line | |
2395 |
|
2392 | |||
2396 | def handle_alias(self,line_info): |
|
2393 | def handle_alias(self,line_info): | |
2397 | """Handle alias input lines. """ |
|
2394 | """Handle alias input lines. """ | |
2398 | tgt = self.alias_table[line_info.iFun] |
|
2395 | tgt = self.alias_table[line_info.iFun] | |
2399 | # print "=>",tgt #dbg |
|
2396 | # print "=>",tgt #dbg | |
2400 | if callable(tgt): |
|
2397 | if callable(tgt): | |
2401 | if '$' in line_info.line: |
|
2398 | if '$' in line_info.line: | |
2402 | call_meth = '(_ip, _ip.itpl(%s))' |
|
2399 | call_meth = '(_ip, _ip.itpl(%s))' | |
2403 | else: |
|
2400 | else: | |
2404 | call_meth = '(_ip,%s)' |
|
2401 | call_meth = '(_ip,%s)' | |
2405 | line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace, |
|
2402 | line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace, | |
2406 | line_info.iFun, |
|
2403 | line_info.iFun, | |
2407 | make_quoted_expr(line_info.line)) |
|
2404 | make_quoted_expr(line_info.line)) | |
2408 | else: |
|
2405 | else: | |
2409 | transformed = self.expand_aliases(line_info.iFun,line_info.theRest) |
|
2406 | transformed = self.expand_aliases(line_info.iFun,line_info.theRest) | |
2410 |
|
2407 | |||
2411 | # pre is needed, because it carries the leading whitespace. Otherwise |
|
2408 | # pre is needed, because it carries the leading whitespace. Otherwise | |
2412 | # aliases won't work in indented sections. |
|
2409 | # aliases won't work in indented sections. | |
2413 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
2410 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, | |
2414 | make_quoted_expr( transformed )) |
|
2411 | make_quoted_expr( transformed )) | |
2415 |
|
2412 | |||
2416 | self.log(line_info.line,line_out,line_info.continue_prompt) |
|
2413 | self.log(line_info.line,line_out,line_info.continue_prompt) | |
2417 | #print 'line out:',line_out # dbg |
|
2414 | #print 'line out:',line_out # dbg | |
2418 | return line_out |
|
2415 | return line_out | |
2419 |
|
2416 | |||
2420 | def handle_shell_escape(self, line_info): |
|
2417 | def handle_shell_escape(self, line_info): | |
2421 | """Execute the line in a shell, empty return value""" |
|
2418 | """Execute the line in a shell, empty return value""" | |
2422 | #print 'line in :', `line` # dbg |
|
2419 | #print 'line in :', `line` # dbg | |
2423 | line = line_info.line |
|
2420 | line = line_info.line | |
2424 | if line.lstrip().startswith('!!'): |
|
2421 | if line.lstrip().startswith('!!'): | |
2425 | # rewrite LineInfo's line, iFun and theRest to properly hold the |
|
2422 | # rewrite LineInfo's line, iFun and theRest to properly hold the | |
2426 | # call to %sx and the actual command to be executed, so |
|
2423 | # call to %sx and the actual command to be executed, so | |
2427 | # handle_magic can work correctly. Note that this works even if |
|
2424 | # handle_magic can work correctly. Note that this works even if | |
2428 | # the line is indented, so it handles multi_line_specials |
|
2425 | # the line is indented, so it handles multi_line_specials | |
2429 | # properly. |
|
2426 | # properly. | |
2430 | new_rest = line.lstrip()[2:] |
|
2427 | new_rest = line.lstrip()[2:] | |
2431 | line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest) |
|
2428 | line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest) | |
2432 | line_info.iFun = 'sx' |
|
2429 | line_info.iFun = 'sx' | |
2433 | line_info.theRest = new_rest |
|
2430 | line_info.theRest = new_rest | |
2434 | return self.handle_magic(line_info) |
|
2431 | return self.handle_magic(line_info) | |
2435 | else: |
|
2432 | else: | |
2436 | cmd = line.lstrip().lstrip('!') |
|
2433 | cmd = line.lstrip().lstrip('!') | |
2437 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
2434 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, | |
2438 | make_quoted_expr(cmd)) |
|
2435 | make_quoted_expr(cmd)) | |
2439 | # update cache/log and return |
|
2436 | # update cache/log and return | |
2440 | self.log(line,line_out,line_info.continue_prompt) |
|
2437 | self.log(line,line_out,line_info.continue_prompt) | |
2441 | return line_out |
|
2438 | return line_out | |
2442 |
|
2439 | |||
2443 | def handle_magic(self, line_info): |
|
2440 | def handle_magic(self, line_info): | |
2444 | """Execute magic functions.""" |
|
2441 | """Execute magic functions.""" | |
2445 | iFun = line_info.iFun |
|
2442 | iFun = line_info.iFun | |
2446 | theRest = line_info.theRest |
|
2443 | theRest = line_info.theRest | |
2447 | cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace, |
|
2444 | cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace, | |
2448 | make_quoted_expr(iFun + " " + theRest)) |
|
2445 | make_quoted_expr(iFun + " " + theRest)) | |
2449 | self.log(line_info.line,cmd,line_info.continue_prompt) |
|
2446 | self.log(line_info.line,cmd,line_info.continue_prompt) | |
2450 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg |
|
2447 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg | |
2451 | return cmd |
|
2448 | return cmd | |
2452 |
|
2449 | |||
2453 | def handle_auto(self, line_info): |
|
2450 | def handle_auto(self, line_info): | |
2454 | """Hande lines which can be auto-executed, quoting if requested.""" |
|
2451 | """Hande lines which can be auto-executed, quoting if requested.""" | |
2455 |
|
2452 | |||
2456 | line = line_info.line |
|
2453 | line = line_info.line | |
2457 | iFun = line_info.iFun |
|
2454 | iFun = line_info.iFun | |
2458 | theRest = line_info.theRest |
|
2455 | theRest = line_info.theRest | |
2459 | pre = line_info.pre |
|
2456 | pre = line_info.pre | |
2460 | continue_prompt = line_info.continue_prompt |
|
2457 | continue_prompt = line_info.continue_prompt | |
2461 | obj = line_info.ofind(self)['obj'] |
|
2458 | obj = line_info.ofind(self)['obj'] | |
2462 |
|
2459 | |||
2463 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2460 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
2464 |
|
2461 | |||
2465 | # This should only be active for single-line input! |
|
2462 | # This should only be active for single-line input! | |
2466 | if continue_prompt: |
|
2463 | if continue_prompt: | |
2467 | self.log(line,line,continue_prompt) |
|
2464 | self.log(line,line,continue_prompt) | |
2468 | return line |
|
2465 | return line | |
2469 |
|
2466 | |||
2470 | force_auto = isinstance(obj, IPython.ipapi.IPyAutocall) |
|
2467 | force_auto = isinstance(obj, IPython.ipapi.IPyAutocall) | |
2471 | auto_rewrite = True |
|
2468 | auto_rewrite = True | |
2472 |
|
2469 | |||
2473 | if pre == self.ESC_QUOTE: |
|
2470 | if pre == self.ESC_QUOTE: | |
2474 | # Auto-quote splitting on whitespace |
|
2471 | # Auto-quote splitting on whitespace | |
2475 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) |
|
2472 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) | |
2476 | elif pre == self.ESC_QUOTE2: |
|
2473 | elif pre == self.ESC_QUOTE2: | |
2477 | # Auto-quote whole string |
|
2474 | # Auto-quote whole string | |
2478 | newcmd = '%s("%s")' % (iFun,theRest) |
|
2475 | newcmd = '%s("%s")' % (iFun,theRest) | |
2479 | elif pre == self.ESC_PAREN: |
|
2476 | elif pre == self.ESC_PAREN: | |
2480 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) |
|
2477 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) | |
2481 | else: |
|
2478 | else: | |
2482 | # Auto-paren. |
|
2479 | # Auto-paren. | |
2483 | # We only apply it to argument-less calls if the autocall |
|
2480 | # We only apply it to argument-less calls if the autocall | |
2484 | # parameter is set to 2. We only need to check that autocall is < |
|
2481 | # parameter is set to 2. We only need to check that autocall is < | |
2485 | # 2, since this function isn't called unless it's at least 1. |
|
2482 | # 2, since this function isn't called unless it's at least 1. | |
2486 | if not theRest and (self.rc.autocall < 2) and not force_auto: |
|
2483 | if not theRest and (self.rc.autocall < 2) and not force_auto: | |
2487 | newcmd = '%s %s' % (iFun,theRest) |
|
2484 | newcmd = '%s %s' % (iFun,theRest) | |
2488 | auto_rewrite = False |
|
2485 | auto_rewrite = False | |
2489 | else: |
|
2486 | else: | |
2490 | if not force_auto and theRest.startswith('['): |
|
2487 | if not force_auto and theRest.startswith('['): | |
2491 | if hasattr(obj,'__getitem__'): |
|
2488 | if hasattr(obj,'__getitem__'): | |
2492 | # Don't autocall in this case: item access for an object |
|
2489 | # Don't autocall in this case: item access for an object | |
2493 | # which is BOTH callable and implements __getitem__. |
|
2490 | # which is BOTH callable and implements __getitem__. | |
2494 | newcmd = '%s %s' % (iFun,theRest) |
|
2491 | newcmd = '%s %s' % (iFun,theRest) | |
2495 | auto_rewrite = False |
|
2492 | auto_rewrite = False | |
2496 | else: |
|
2493 | else: | |
2497 | # if the object doesn't support [] access, go ahead and |
|
2494 | # if the object doesn't support [] access, go ahead and | |
2498 | # autocall |
|
2495 | # autocall | |
2499 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) |
|
2496 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) | |
2500 | elif theRest.endswith(';'): |
|
2497 | elif theRest.endswith(';'): | |
2501 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) |
|
2498 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) | |
2502 | else: |
|
2499 | else: | |
2503 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) |
|
2500 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) | |
2504 |
|
2501 | |||
2505 | if auto_rewrite: |
|
2502 | if auto_rewrite: | |
2506 | rw = self.outputcache.prompt1.auto_rewrite() + newcmd |
|
2503 | rw = self.outputcache.prompt1.auto_rewrite() + newcmd | |
2507 |
|
2504 | |||
2508 | try: |
|
2505 | try: | |
2509 | # plain ascii works better w/ pyreadline, on some machines, so |
|
2506 | # plain ascii works better w/ pyreadline, on some machines, so | |
2510 | # we use it and only print uncolored rewrite if we have unicode |
|
2507 | # we use it and only print uncolored rewrite if we have unicode | |
2511 | rw = str(rw) |
|
2508 | rw = str(rw) | |
2512 | print >>Term.cout, rw |
|
2509 | print >>Term.cout, rw | |
2513 | except UnicodeEncodeError: |
|
2510 | except UnicodeEncodeError: | |
2514 | print "-------------->" + newcmd |
|
2511 | print "-------------->" + newcmd | |
2515 |
|
2512 | |||
2516 | # log what is now valid Python, not the actual user input (without the |
|
2513 | # log what is now valid Python, not the actual user input (without the | |
2517 | # final newline) |
|
2514 | # final newline) | |
2518 | self.log(line,newcmd,continue_prompt) |
|
2515 | self.log(line,newcmd,continue_prompt) | |
2519 | return newcmd |
|
2516 | return newcmd | |
2520 |
|
2517 | |||
2521 | def handle_help(self, line_info): |
|
2518 | def handle_help(self, line_info): | |
2522 | """Try to get some help for the object. |
|
2519 | """Try to get some help for the object. | |
2523 |
|
2520 | |||
2524 | obj? or ?obj -> basic information. |
|
2521 | obj? or ?obj -> basic information. | |
2525 | obj?? or ??obj -> more details. |
|
2522 | obj?? or ??obj -> more details. | |
2526 | """ |
|
2523 | """ | |
2527 |
|
2524 | |||
2528 | line = line_info.line |
|
2525 | line = line_info.line | |
2529 | # We need to make sure that we don't process lines which would be |
|
2526 | # We need to make sure that we don't process lines which would be | |
2530 | # otherwise valid python, such as "x=1 # what?" |
|
2527 | # otherwise valid python, such as "x=1 # what?" | |
2531 | try: |
|
2528 | try: | |
2532 | codeop.compile_command(line) |
|
2529 | codeop.compile_command(line) | |
2533 | except SyntaxError: |
|
2530 | except SyntaxError: | |
2534 | # We should only handle as help stuff which is NOT valid syntax |
|
2531 | # We should only handle as help stuff which is NOT valid syntax | |
2535 | if line[0]==self.ESC_HELP: |
|
2532 | if line[0]==self.ESC_HELP: | |
2536 | line = line[1:] |
|
2533 | line = line[1:] | |
2537 | elif line[-1]==self.ESC_HELP: |
|
2534 | elif line[-1]==self.ESC_HELP: | |
2538 | line = line[:-1] |
|
2535 | line = line[:-1] | |
2539 | self.log(line,'#?'+line,line_info.continue_prompt) |
|
2536 | self.log(line,'#?'+line,line_info.continue_prompt) | |
2540 | if line: |
|
2537 | if line: | |
2541 | #print 'line:<%r>' % line # dbg |
|
2538 | #print 'line:<%r>' % line # dbg | |
2542 | self.magic_pinfo(line) |
|
2539 | self.magic_pinfo(line) | |
2543 | else: |
|
2540 | else: | |
2544 | page(self.usage,screen_lines=self.rc.screen_length) |
|
2541 | page(self.usage,screen_lines=self.rc.screen_length) | |
2545 | return '' # Empty string is needed here! |
|
2542 | return '' # Empty string is needed here! | |
2546 | except: |
|
2543 | except: | |
2547 | # Pass any other exceptions through to the normal handler |
|
2544 | # Pass any other exceptions through to the normal handler | |
2548 | return self.handle_normal(line_info) |
|
2545 | return self.handle_normal(line_info) | |
2549 | else: |
|
2546 | else: | |
2550 | # If the code compiles ok, we should handle it normally |
|
2547 | # If the code compiles ok, we should handle it normally | |
2551 | return self.handle_normal(line_info) |
|
2548 | return self.handle_normal(line_info) | |
2552 |
|
2549 | |||
2553 | def getapi(self): |
|
2550 | def getapi(self): | |
2554 | """ Get an IPApi object for this shell instance |
|
2551 | """ Get an IPApi object for this shell instance | |
2555 |
|
2552 | |||
2556 | Getting an IPApi object is always preferable to accessing the shell |
|
2553 | Getting an IPApi object is always preferable to accessing the shell | |
2557 | directly, but this holds true especially for extensions. |
|
2554 | directly, but this holds true especially for extensions. | |
2558 |
|
2555 | |||
2559 | It should always be possible to implement an extension with IPApi |
|
2556 | It should always be possible to implement an extension with IPApi | |
2560 | alone. If not, contact maintainer to request an addition. |
|
2557 | alone. If not, contact maintainer to request an addition. | |
2561 |
|
2558 | |||
2562 | """ |
|
2559 | """ | |
2563 | return self.api |
|
2560 | return self.api | |
2564 |
|
2561 | |||
2565 | def handle_emacs(self, line_info): |
|
2562 | def handle_emacs(self, line_info): | |
2566 | """Handle input lines marked by python-mode.""" |
|
2563 | """Handle input lines marked by python-mode.""" | |
2567 |
|
2564 | |||
2568 | # Currently, nothing is done. Later more functionality can be added |
|
2565 | # Currently, nothing is done. Later more functionality can be added | |
2569 | # here if needed. |
|
2566 | # here if needed. | |
2570 |
|
2567 | |||
2571 | # The input cache shouldn't be updated |
|
2568 | # The input cache shouldn't be updated | |
2572 | return line_info.line |
|
2569 | return line_info.line | |
2573 |
|
2570 | |||
2574 |
|
2571 | |||
2575 | def mktempfile(self,data=None): |
|
2572 | def mktempfile(self,data=None): | |
2576 | """Make a new tempfile and return its filename. |
|
2573 | """Make a new tempfile and return its filename. | |
2577 |
|
2574 | |||
2578 | This makes a call to tempfile.mktemp, but it registers the created |
|
2575 | This makes a call to tempfile.mktemp, but it registers the created | |
2579 | filename internally so ipython cleans it up at exit time. |
|
2576 | filename internally so ipython cleans it up at exit time. | |
2580 |
|
2577 | |||
2581 | Optional inputs: |
|
2578 | Optional inputs: | |
2582 |
|
2579 | |||
2583 | - data(None): if data is given, it gets written out to the temp file |
|
2580 | - data(None): if data is given, it gets written out to the temp file | |
2584 | immediately, and the file is closed again.""" |
|
2581 | immediately, and the file is closed again.""" | |
2585 |
|
2582 | |||
2586 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
2583 | filename = tempfile.mktemp('.py','ipython_edit_') | |
2587 | self.tempfiles.append(filename) |
|
2584 | self.tempfiles.append(filename) | |
2588 |
|
2585 | |||
2589 | if data: |
|
2586 | if data: | |
2590 | tmp_file = open(filename,'w') |
|
2587 | tmp_file = open(filename,'w') | |
2591 | tmp_file.write(data) |
|
2588 | tmp_file.write(data) | |
2592 | tmp_file.close() |
|
2589 | tmp_file.close() | |
2593 | return filename |
|
2590 | return filename | |
2594 |
|
2591 | |||
2595 | def write(self,data): |
|
2592 | def write(self,data): | |
2596 | """Write a string to the default output""" |
|
2593 | """Write a string to the default output""" | |
2597 | Term.cout.write(data) |
|
2594 | Term.cout.write(data) | |
2598 |
|
2595 | |||
2599 | def write_err(self,data): |
|
2596 | def write_err(self,data): | |
2600 | """Write a string to the default error output""" |
|
2597 | """Write a string to the default error output""" | |
2601 | Term.cerr.write(data) |
|
2598 | Term.cerr.write(data) | |
2602 |
|
2599 | |||
2603 | def ask_exit(self): |
|
2600 | def ask_exit(self): | |
2604 | """ Call for exiting. Can be overiden and used as a callback. """ |
|
2601 | """ Call for exiting. Can be overiden and used as a callback. """ | |
2605 | self.exit_now = True |
|
2602 | self.exit_now = True | |
2606 |
|
2603 | |||
2607 | def exit(self): |
|
2604 | def exit(self): | |
2608 | """Handle interactive exit. |
|
2605 | """Handle interactive exit. | |
2609 |
|
2606 | |||
2610 | This method calls the ask_exit callback.""" |
|
2607 | This method calls the ask_exit callback.""" | |
2611 |
|
2608 | |||
2612 | if self.rc.confirm_exit: |
|
2609 | if self.rc.confirm_exit: | |
2613 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
2610 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): | |
2614 | self.ask_exit() |
|
2611 | self.ask_exit() | |
2615 | else: |
|
2612 | else: | |
2616 | self.ask_exit() |
|
2613 | self.ask_exit() | |
2617 |
|
2614 | |||
2618 | def safe_execfile(self,fname,*where,**kw): |
|
2615 | def safe_execfile(self,fname,*where,**kw): | |
2619 | """A safe version of the builtin execfile(). |
|
2616 | """A safe version of the builtin execfile(). | |
2620 |
|
2617 | |||
2621 | This version will never throw an exception, and knows how to handle |
|
2618 | This version will never throw an exception, and knows how to handle | |
2622 | ipython logs as well. |
|
2619 | ipython logs as well. | |
2623 |
|
2620 | |||
2624 | :Parameters: |
|
2621 | :Parameters: | |
2625 | fname : string |
|
2622 | fname : string | |
2626 | Name of the file to be executed. |
|
2623 | Name of the file to be executed. | |
2627 |
|
2624 | |||
2628 | where : tuple |
|
2625 | where : tuple | |
2629 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2626 | One or two namespaces, passed to execfile() as (globals,locals). | |
2630 | If only one is given, it is passed as both. |
|
2627 | If only one is given, it is passed as both. | |
2631 |
|
2628 | |||
2632 | :Keywords: |
|
2629 | :Keywords: | |
2633 | islog : boolean (False) |
|
2630 | islog : boolean (False) | |
2634 |
|
2631 | |||
2635 | quiet : boolean (True) |
|
2632 | quiet : boolean (True) | |
2636 |
|
2633 | |||
2637 | exit_ignore : boolean (False) |
|
2634 | exit_ignore : boolean (False) | |
2638 | """ |
|
2635 | """ | |
2639 |
|
2636 | |||
2640 | def syspath_cleanup(): |
|
2637 | def syspath_cleanup(): | |
2641 | """Internal cleanup routine for sys.path.""" |
|
2638 | """Internal cleanup routine for sys.path.""" | |
2642 | if add_dname: |
|
2639 | if add_dname: | |
2643 | try: |
|
2640 | try: | |
2644 | sys.path.remove(dname) |
|
2641 | sys.path.remove(dname) | |
2645 | except ValueError: |
|
2642 | except ValueError: | |
2646 | # For some reason the user has already removed it, ignore. |
|
2643 | # For some reason the user has already removed it, ignore. | |
2647 | pass |
|
2644 | pass | |
2648 |
|
2645 | |||
2649 | fname = os.path.expanduser(fname) |
|
2646 | fname = os.path.expanduser(fname) | |
2650 |
|
2647 | |||
2651 | # Find things also in current directory. This is needed to mimic the |
|
2648 | # Find things also in current directory. This is needed to mimic the | |
2652 | # behavior of running a script from the system command line, where |
|
2649 | # behavior of running a script from the system command line, where | |
2653 | # Python inserts the script's directory into sys.path |
|
2650 | # Python inserts the script's directory into sys.path | |
2654 | dname = os.path.dirname(os.path.abspath(fname)) |
|
2651 | dname = os.path.dirname(os.path.abspath(fname)) | |
2655 | add_dname = False |
|
2652 | add_dname = False | |
2656 | if dname not in sys.path: |
|
2653 | if dname not in sys.path: | |
2657 | sys.path.insert(0,dname) |
|
2654 | sys.path.insert(0,dname) | |
2658 | add_dname = True |
|
2655 | add_dname = True | |
2659 |
|
2656 | |||
2660 | try: |
|
2657 | try: | |
2661 | xfile = open(fname) |
|
2658 | xfile = open(fname) | |
2662 | except: |
|
2659 | except: | |
2663 | print >> Term.cerr, \ |
|
2660 | print >> Term.cerr, \ | |
2664 | 'Could not open file <%s> for safe execution.' % fname |
|
2661 | 'Could not open file <%s> for safe execution.' % fname | |
2665 | syspath_cleanup() |
|
2662 | syspath_cleanup() | |
2666 | return None |
|
2663 | return None | |
2667 |
|
2664 | |||
2668 | kw.setdefault('islog',0) |
|
2665 | kw.setdefault('islog',0) | |
2669 | kw.setdefault('quiet',1) |
|
2666 | kw.setdefault('quiet',1) | |
2670 | kw.setdefault('exit_ignore',0) |
|
2667 | kw.setdefault('exit_ignore',0) | |
2671 |
|
2668 | |||
2672 | first = xfile.readline() |
|
2669 | first = xfile.readline() | |
2673 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() |
|
2670 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() | |
2674 | xfile.close() |
|
2671 | xfile.close() | |
2675 | # line by line execution |
|
2672 | # line by line execution | |
2676 | if first.startswith(loghead) or kw['islog']: |
|
2673 | if first.startswith(loghead) or kw['islog']: | |
2677 | print 'Loading log file <%s> one line at a time...' % fname |
|
2674 | print 'Loading log file <%s> one line at a time...' % fname | |
2678 | if kw['quiet']: |
|
2675 | if kw['quiet']: | |
2679 | stdout_save = sys.stdout |
|
2676 | stdout_save = sys.stdout | |
2680 | sys.stdout = StringIO.StringIO() |
|
2677 | sys.stdout = StringIO.StringIO() | |
2681 | try: |
|
2678 | try: | |
2682 | globs,locs = where[0:2] |
|
2679 | globs,locs = where[0:2] | |
2683 | except: |
|
2680 | except: | |
2684 | try: |
|
2681 | try: | |
2685 | globs = locs = where[0] |
|
2682 | globs = locs = where[0] | |
2686 | except: |
|
2683 | except: | |
2687 | globs = locs = globals() |
|
2684 | globs = locs = globals() | |
2688 | badblocks = [] |
|
2685 | badblocks = [] | |
2689 |
|
2686 | |||
2690 | # we also need to identify indented blocks of code when replaying |
|
2687 | # we also need to identify indented blocks of code when replaying | |
2691 | # logs and put them together before passing them to an exec |
|
2688 | # logs and put them together before passing them to an exec | |
2692 | # statement. This takes a bit of regexp and look-ahead work in the |
|
2689 | # statement. This takes a bit of regexp and look-ahead work in the | |
2693 | # file. It's easiest if we swallow the whole thing in memory |
|
2690 | # file. It's easiest if we swallow the whole thing in memory | |
2694 | # first, and manually walk through the lines list moving the |
|
2691 | # first, and manually walk through the lines list moving the | |
2695 | # counter ourselves. |
|
2692 | # counter ourselves. | |
2696 | indent_re = re.compile('\s+\S') |
|
2693 | indent_re = re.compile('\s+\S') | |
2697 | xfile = open(fname) |
|
2694 | xfile = open(fname) | |
2698 | filelines = xfile.readlines() |
|
2695 | filelines = xfile.readlines() | |
2699 | xfile.close() |
|
2696 | xfile.close() | |
2700 | nlines = len(filelines) |
|
2697 | nlines = len(filelines) | |
2701 | lnum = 0 |
|
2698 | lnum = 0 | |
2702 | while lnum < nlines: |
|
2699 | while lnum < nlines: | |
2703 | line = filelines[lnum] |
|
2700 | line = filelines[lnum] | |
2704 | lnum += 1 |
|
2701 | lnum += 1 | |
2705 | # don't re-insert logger status info into cache |
|
2702 | # don't re-insert logger status info into cache | |
2706 | if line.startswith('#log#'): |
|
2703 | if line.startswith('#log#'): | |
2707 | continue |
|
2704 | continue | |
2708 | else: |
|
2705 | else: | |
2709 | # build a block of code (maybe a single line) for execution |
|
2706 | # build a block of code (maybe a single line) for execution | |
2710 | block = line |
|
2707 | block = line | |
2711 | try: |
|
2708 | try: | |
2712 | next = filelines[lnum] # lnum has already incremented |
|
2709 | next = filelines[lnum] # lnum has already incremented | |
2713 | except: |
|
2710 | except: | |
2714 | next = None |
|
2711 | next = None | |
2715 | while next and indent_re.match(next): |
|
2712 | while next and indent_re.match(next): | |
2716 | block += next |
|
2713 | block += next | |
2717 | lnum += 1 |
|
2714 | lnum += 1 | |
2718 | try: |
|
2715 | try: | |
2719 | next = filelines[lnum] |
|
2716 | next = filelines[lnum] | |
2720 | except: |
|
2717 | except: | |
2721 | next = None |
|
2718 | next = None | |
2722 | # now execute the block of one or more lines |
|
2719 | # now execute the block of one or more lines | |
2723 | try: |
|
2720 | try: | |
2724 | exec block in globs,locs |
|
2721 | exec block in globs,locs | |
2725 | except SystemExit: |
|
2722 | except SystemExit: | |
2726 | pass |
|
2723 | pass | |
2727 | except: |
|
2724 | except: | |
2728 | badblocks.append(block.rstrip()) |
|
2725 | badblocks.append(block.rstrip()) | |
2729 | if kw['quiet']: # restore stdout |
|
2726 | if kw['quiet']: # restore stdout | |
2730 | sys.stdout.close() |
|
2727 | sys.stdout.close() | |
2731 | sys.stdout = stdout_save |
|
2728 | sys.stdout = stdout_save | |
2732 | print 'Finished replaying log file <%s>' % fname |
|
2729 | print 'Finished replaying log file <%s>' % fname | |
2733 | if badblocks: |
|
2730 | if badblocks: | |
2734 | print >> sys.stderr, ('\nThe following lines/blocks in file ' |
|
2731 | print >> sys.stderr, ('\nThe following lines/blocks in file ' | |
2735 | '<%s> reported errors:' % fname) |
|
2732 | '<%s> reported errors:' % fname) | |
2736 |
|
2733 | |||
2737 | for badline in badblocks: |
|
2734 | for badline in badblocks: | |
2738 | print >> sys.stderr, badline |
|
2735 | print >> sys.stderr, badline | |
2739 | else: # regular file execution |
|
2736 | else: # regular file execution | |
2740 | try: |
|
2737 | try: | |
2741 | if sys.platform == 'win32' and sys.version_info < (2,5,1): |
|
2738 | if sys.platform == 'win32' and sys.version_info < (2,5,1): | |
2742 | # Work around a bug in Python for Windows. The bug was |
|
2739 | # Work around a bug in Python for Windows. The bug was | |
2743 | # fixed in in Python 2.5 r54159 and 54158, but that's still |
|
2740 | # fixed in in Python 2.5 r54159 and 54158, but that's still | |
2744 | # SVN Python as of March/07. For details, see: |
|
2741 | # SVN Python as of March/07. For details, see: | |
2745 | # http://projects.scipy.org/ipython/ipython/ticket/123 |
|
2742 | # http://projects.scipy.org/ipython/ipython/ticket/123 | |
2746 | try: |
|
2743 | try: | |
2747 | globs,locs = where[0:2] |
|
2744 | globs,locs = where[0:2] | |
2748 | except: |
|
2745 | except: | |
2749 | try: |
|
2746 | try: | |
2750 | globs = locs = where[0] |
|
2747 | globs = locs = where[0] | |
2751 | except: |
|
2748 | except: | |
2752 | globs = locs = globals() |
|
2749 | globs = locs = globals() | |
2753 | exec file(fname) in globs,locs |
|
2750 | exec file(fname) in globs,locs | |
2754 | else: |
|
2751 | else: | |
2755 | execfile(fname,*where) |
|
2752 | execfile(fname,*where) | |
2756 | except SyntaxError: |
|
2753 | except SyntaxError: | |
2757 | self.showsyntaxerror() |
|
2754 | self.showsyntaxerror() | |
2758 | warn('Failure executing file: <%s>' % fname) |
|
2755 | warn('Failure executing file: <%s>' % fname) | |
2759 | except SystemExit,status: |
|
2756 | except SystemExit,status: | |
2760 | # Code that correctly sets the exit status flag to success (0) |
|
2757 | # Code that correctly sets the exit status flag to success (0) | |
2761 | # shouldn't be bothered with a traceback. Note that a plain |
|
2758 | # shouldn't be bothered with a traceback. Note that a plain | |
2762 | # sys.exit() does NOT set the message to 0 (it's empty) so that |
|
2759 | # sys.exit() does NOT set the message to 0 (it's empty) so that | |
2763 | # will still get a traceback. Note that the structure of the |
|
2760 | # will still get a traceback. Note that the structure of the | |
2764 | # SystemExit exception changed between Python 2.4 and 2.5, so |
|
2761 | # SystemExit exception changed between Python 2.4 and 2.5, so | |
2765 | # the checks must be done in a version-dependent way. |
|
2762 | # the checks must be done in a version-dependent way. | |
2766 | show = False |
|
2763 | show = False | |
2767 |
|
2764 | |||
2768 | if sys.version_info[:2] > (2,5): |
|
2765 | if sys.version_info[:2] > (2,5): | |
2769 | if status.message!=0 and not kw['exit_ignore']: |
|
2766 | if status.message!=0 and not kw['exit_ignore']: | |
2770 | show = True |
|
2767 | show = True | |
2771 | else: |
|
2768 | else: | |
2772 | if status.code and not kw['exit_ignore']: |
|
2769 | if status.code and not kw['exit_ignore']: | |
2773 | show = True |
|
2770 | show = True | |
2774 | if show: |
|
2771 | if show: | |
2775 | self.showtraceback() |
|
2772 | self.showtraceback() | |
2776 | warn('Failure executing file: <%s>' % fname) |
|
2773 | warn('Failure executing file: <%s>' % fname) | |
2777 | except: |
|
2774 | except: | |
2778 | self.showtraceback() |
|
2775 | self.showtraceback() | |
2779 | warn('Failure executing file: <%s>' % fname) |
|
2776 | warn('Failure executing file: <%s>' % fname) | |
2780 |
|
2777 | |||
2781 | syspath_cleanup() |
|
2778 | syspath_cleanup() | |
2782 |
|
2779 | |||
2783 | #************************* end of file <iplib.py> ***************************** |
|
2780 | #************************* end of file <iplib.py> ***************************** |
@@ -1,373 +1,373 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 |
|
2 | |||
3 | """Test template for complete engine object""" |
|
3 | """Test template for complete engine object""" | |
4 |
|
4 | |||
5 | __docformat__ = "restructuredtext en" |
|
5 | __docformat__ = "restructuredtext en" | |
6 |
|
6 | |||
7 | #------------------------------------------------------------------------------- |
|
7 | #------------------------------------------------------------------------------- | |
8 | # Copyright (C) 2008 The IPython Development Team |
|
8 | # Copyright (C) 2008 The IPython Development Team | |
9 | # |
|
9 | # | |
10 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | # Distributed under the terms of the BSD License. The full license is in | |
11 | # the file COPYING, distributed as part of this software. |
|
11 | # the file COPYING, distributed as part of this software. | |
12 | #------------------------------------------------------------------------------- |
|
12 | #------------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | #------------------------------------------------------------------------------- |
|
14 | #------------------------------------------------------------------------------- | |
15 | # Imports |
|
15 | # Imports | |
16 | #------------------------------------------------------------------------------- |
|
16 | #------------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | import cPickle as pickle |
|
18 | import cPickle as pickle | |
19 |
|
19 | |||
20 | from twisted.internet import defer, reactor |
|
20 | from twisted.internet import defer, reactor | |
21 | from twisted.python import failure |
|
21 | from twisted.python import failure | |
22 | from twisted.application import service |
|
22 | from twisted.application import service | |
23 | import zope.interface as zi |
|
23 | import zope.interface as zi | |
24 |
|
24 | |||
25 | from IPython.kernel import newserialized |
|
25 | from IPython.kernel import newserialized | |
26 | from IPython.kernel import error |
|
26 | from IPython.kernel import error | |
27 | from IPython.kernel.pickleutil import can, uncan |
|
27 | from IPython.kernel.pickleutil import can, uncan | |
28 | import IPython.kernel.engineservice as es |
|
28 | import IPython.kernel.engineservice as es | |
29 | from IPython.kernel.core.interpreter import Interpreter |
|
29 | from IPython.kernel.core.interpreter import Interpreter | |
30 | from IPython.testing.parametric import Parametric, parametric |
|
30 | from IPython.testing.parametric import Parametric, parametric | |
31 |
|
31 | |||
32 | #------------------------------------------------------------------------------- |
|
32 | #------------------------------------------------------------------------------- | |
33 | # Tests |
|
33 | # Tests | |
34 | #------------------------------------------------------------------------------- |
|
34 | #------------------------------------------------------------------------------- | |
35 |
|
35 | |||
36 |
|
36 | |||
37 | # A sequence of valid commands run through execute |
|
37 | # A sequence of valid commands run through execute | |
38 | validCommands = ['a=5', |
|
38 | validCommands = ['a=5', | |
39 | 'b=10', |
|
39 | 'b=10', | |
40 | 'a=5; b=10; c=a+b', |
|
40 | 'a=5; b=10; c=a+b', | |
41 | 'import math; 2.0*math.pi', |
|
41 | 'import math; 2.0*math.pi', | |
42 | """def f(): |
|
42 | """def f(): | |
43 | result = 0.0 |
|
43 | result = 0.0 | |
44 | for i in range(10): |
|
44 | for i in range(10): | |
45 | result += i |
|
45 | result += i | |
46 | """, |
|
46 | """, | |
47 | 'if 1<2: a=5', |
|
47 | 'if 1<2: a=5', | |
48 | """import time |
|
48 | """import time | |
49 | time.sleep(0.1)""", |
|
49 | time.sleep(0.1)""", | |
50 | """from math import cos; |
|
50 | """from math import cos; | |
51 | x = 1.0*cos(0.5)""", # Semicolons lead to Discard ast nodes that should be discarded |
|
51 | x = 1.0*cos(0.5)""", # Semicolons lead to Discard ast nodes that should be discarded | |
52 |
""" |
|
52 | """s = 1 | |
53 |
s = |
|
53 | s = set() | |
54 | """, # Trailing whitespace should be allowed. |
|
54 | """, # Trailing whitespace should be allowed. | |
55 | """import math |
|
55 | """import math | |
56 | math.cos(1.0)""", # Test a method call with a discarded return value |
|
56 | math.cos(1.0)""", # Test a method call with a discarded return value | |
57 | """x=1.0234 |
|
57 | """x=1.0234 | |
58 | a=5; b=10""", # Test an embedded semicolon |
|
58 | a=5; b=10""", # Test an embedded semicolon | |
59 | """x=1.0234 |
|
59 | """x=1.0234 | |
60 | a=5; b=10;""" # Test both an embedded and trailing semicolon |
|
60 | a=5; b=10;""" # Test both an embedded and trailing semicolon | |
61 | ] |
|
61 | ] | |
62 |
|
62 | |||
63 | # A sequence of commands that raise various exceptions |
|
63 | # A sequence of commands that raise various exceptions | |
64 | invalidCommands = [('a=1/0',ZeroDivisionError), |
|
64 | invalidCommands = [('a=1/0',ZeroDivisionError), | |
65 | ('print v',NameError), |
|
65 | ('print v',NameError), | |
66 | ('l=[];l[0]',IndexError), |
|
66 | ('l=[];l[0]',IndexError), | |
67 | ("d={};d['a']",KeyError), |
|
67 | ("d={};d['a']",KeyError), | |
68 | ("assert 1==0",AssertionError), |
|
68 | ("assert 1==0",AssertionError), | |
69 | ("import abababsdbfsbaljasdlja",ImportError), |
|
69 | ("import abababsdbfsbaljasdlja",ImportError), | |
70 | ("raise Exception()",Exception)] |
|
70 | ("raise Exception()",Exception)] | |
71 |
|
71 | |||
72 | def testf(x): |
|
72 | def testf(x): | |
73 | return 2.0*x |
|
73 | return 2.0*x | |
74 |
|
74 | |||
75 | globala = 99 |
|
75 | globala = 99 | |
76 |
|
76 | |||
77 | def testg(x): |
|
77 | def testg(x): | |
78 | return globala*x |
|
78 | return globala*x | |
79 |
|
79 | |||
80 | class IEngineCoreTestCase(object): |
|
80 | class IEngineCoreTestCase(object): | |
81 | """Test an IEngineCore implementer.""" |
|
81 | """Test an IEngineCore implementer.""" | |
82 |
|
82 | |||
83 | def createShell(self): |
|
83 | def createShell(self): | |
84 | return Interpreter() |
|
84 | return Interpreter() | |
85 |
|
85 | |||
86 | def catchQueueCleared(self, f): |
|
86 | def catchQueueCleared(self, f): | |
87 | try: |
|
87 | try: | |
88 | f.raiseException() |
|
88 | f.raiseException() | |
89 | except error.QueueCleared: |
|
89 | except error.QueueCleared: | |
90 | pass |
|
90 | pass | |
91 |
|
91 | |||
92 | def testIEngineCoreInterface(self): |
|
92 | def testIEngineCoreInterface(self): | |
93 | """Does self.engine claim to implement IEngineCore?""" |
|
93 | """Does self.engine claim to implement IEngineCore?""" | |
94 | self.assert_(es.IEngineCore.providedBy(self.engine)) |
|
94 | self.assert_(es.IEngineCore.providedBy(self.engine)) | |
95 |
|
95 | |||
96 | def testIEngineCoreInterfaceMethods(self): |
|
96 | def testIEngineCoreInterfaceMethods(self): | |
97 | """Does self.engine have the methods and attributes in IEngineCore.""" |
|
97 | """Does self.engine have the methods and attributes in IEngineCore.""" | |
98 | for m in list(es.IEngineCore): |
|
98 | for m in list(es.IEngineCore): | |
99 | self.assert_(hasattr(self.engine, m)) |
|
99 | self.assert_(hasattr(self.engine, m)) | |
100 |
|
100 | |||
101 | def testIEngineCoreDeferreds(self): |
|
101 | def testIEngineCoreDeferreds(self): | |
102 | d = self.engine.execute('a=5') |
|
102 | d = self.engine.execute('a=5') | |
103 | d.addCallback(lambda _: self.engine.pull('a')) |
|
103 | d.addCallback(lambda _: self.engine.pull('a')) | |
104 | d.addCallback(lambda _: self.engine.get_result()) |
|
104 | d.addCallback(lambda _: self.engine.get_result()) | |
105 | d.addCallback(lambda _: self.engine.keys()) |
|
105 | d.addCallback(lambda _: self.engine.keys()) | |
106 | d.addCallback(lambda _: self.engine.push(dict(a=10))) |
|
106 | d.addCallback(lambda _: self.engine.push(dict(a=10))) | |
107 | return d |
|
107 | return d | |
108 |
|
108 | |||
109 | def runTestExecute(self, cmd): |
|
109 | def runTestExecute(self, cmd): | |
110 | self.shell = Interpreter() |
|
110 | self.shell = Interpreter() | |
111 | actual = self.shell.execute(cmd) |
|
111 | actual = self.shell.execute(cmd) | |
112 | def compare(computed): |
|
112 | def compare(computed): | |
113 | actual['id'] = computed['id'] |
|
113 | actual['id'] = computed['id'] | |
114 | self.assertEquals(actual, computed) |
|
114 | self.assertEquals(actual, computed) | |
115 | d = self.engine.execute(cmd) |
|
115 | d = self.engine.execute(cmd) | |
116 | d.addCallback(compare) |
|
116 | d.addCallback(compare) | |
117 | return d |
|
117 | return d | |
118 |
|
118 | |||
119 | @parametric |
|
119 | @parametric | |
120 | def testExecute(cls): |
|
120 | def testExecute(cls): | |
121 | return [(cls.runTestExecute, cmd) for cmd in validCommands] |
|
121 | return [(cls.runTestExecute, cmd) for cmd in validCommands] | |
122 |
|
122 | |||
123 | def runTestExecuteFailures(self, cmd, exc): |
|
123 | def runTestExecuteFailures(self, cmd, exc): | |
124 | def compare(f): |
|
124 | def compare(f): | |
125 | self.assertRaises(exc, f.raiseException) |
|
125 | self.assertRaises(exc, f.raiseException) | |
126 | d = self.engine.execute(cmd) |
|
126 | d = self.engine.execute(cmd) | |
127 | d.addErrback(compare) |
|
127 | d.addErrback(compare) | |
128 | return d |
|
128 | return d | |
129 |
|
129 | |||
130 | @parametric |
|
130 | @parametric | |
131 | def testExecuteFailuresEngineService(cls): |
|
131 | def testExecuteFailuresEngineService(cls): | |
132 | return [(cls.runTestExecuteFailures, cmd, exc) |
|
132 | return [(cls.runTestExecuteFailures, cmd, exc) | |
133 | for cmd, exc in invalidCommands] |
|
133 | for cmd, exc in invalidCommands] | |
134 |
|
134 | |||
135 | def runTestPushPull(self, o): |
|
135 | def runTestPushPull(self, o): | |
136 | d = self.engine.push(dict(a=o)) |
|
136 | d = self.engine.push(dict(a=o)) | |
137 | d.addCallback(lambda r: self.engine.pull('a')) |
|
137 | d.addCallback(lambda r: self.engine.pull('a')) | |
138 | d.addCallback(lambda r: self.assertEquals(o,r)) |
|
138 | d.addCallback(lambda r: self.assertEquals(o,r)) | |
139 | return d |
|
139 | return d | |
140 |
|
140 | |||
141 | @parametric |
|
141 | @parametric | |
142 | def testPushPull(cls): |
|
142 | def testPushPull(cls): | |
143 | objs = [10,"hi there",1.2342354,{"p":(1,2)},None] |
|
143 | objs = [10,"hi there",1.2342354,{"p":(1,2)},None] | |
144 | return [(cls.runTestPushPull, o) for o in objs] |
|
144 | return [(cls.runTestPushPull, o) for o in objs] | |
145 |
|
145 | |||
146 | def testPullNameError(self): |
|
146 | def testPullNameError(self): | |
147 | d = self.engine.push(dict(a=5)) |
|
147 | d = self.engine.push(dict(a=5)) | |
148 | d.addCallback(lambda _:self.engine.reset()) |
|
148 | d.addCallback(lambda _:self.engine.reset()) | |
149 | d.addCallback(lambda _: self.engine.pull("a")) |
|
149 | d.addCallback(lambda _: self.engine.pull("a")) | |
150 | d.addErrback(lambda f: self.assertRaises(NameError, f.raiseException)) |
|
150 | d.addErrback(lambda f: self.assertRaises(NameError, f.raiseException)) | |
151 | return d |
|
151 | return d | |
152 |
|
152 | |||
153 | def testPushPullFailures(self): |
|
153 | def testPushPullFailures(self): | |
154 | d = self.engine.pull('a') |
|
154 | d = self.engine.pull('a') | |
155 | d.addErrback(lambda f: self.assertRaises(NameError, f.raiseException)) |
|
155 | d.addErrback(lambda f: self.assertRaises(NameError, f.raiseException)) | |
156 | d.addCallback(lambda _: self.engine.execute('l = lambda x: x')) |
|
156 | d.addCallback(lambda _: self.engine.execute('l = lambda x: x')) | |
157 | d.addCallback(lambda _: self.engine.pull('l')) |
|
157 | d.addCallback(lambda _: self.engine.pull('l')) | |
158 | d.addErrback(lambda f: self.assertRaises(pickle.PicklingError, f.raiseException)) |
|
158 | d.addErrback(lambda f: self.assertRaises(pickle.PicklingError, f.raiseException)) | |
159 | d.addCallback(lambda _: self.engine.push(dict(l=lambda x: x))) |
|
159 | d.addCallback(lambda _: self.engine.push(dict(l=lambda x: x))) | |
160 | d.addErrback(lambda f: self.assertRaises(pickle.PicklingError, f.raiseException)) |
|
160 | d.addErrback(lambda f: self.assertRaises(pickle.PicklingError, f.raiseException)) | |
161 | return d |
|
161 | return d | |
162 |
|
162 | |||
163 | def testPushPullArray(self): |
|
163 | def testPushPullArray(self): | |
164 | try: |
|
164 | try: | |
165 | import numpy |
|
165 | import numpy | |
166 | except: |
|
166 | except: | |
167 | return |
|
167 | return | |
168 | a = numpy.random.random(1000) |
|
168 | a = numpy.random.random(1000) | |
169 | d = self.engine.push(dict(a=a)) |
|
169 | d = self.engine.push(dict(a=a)) | |
170 | d.addCallback(lambda _: self.engine.pull('a')) |
|
170 | d.addCallback(lambda _: self.engine.pull('a')) | |
171 | d.addCallback(lambda b: b==a) |
|
171 | d.addCallback(lambda b: b==a) | |
172 | d.addCallback(lambda c: c.all()) |
|
172 | d.addCallback(lambda c: c.all()) | |
173 | return self.assertDeferredEquals(d, True) |
|
173 | return self.assertDeferredEquals(d, True) | |
174 |
|
174 | |||
175 | def testPushFunction(self): |
|
175 | def testPushFunction(self): | |
176 |
|
176 | |||
177 | d = self.engine.push_function(dict(f=testf)) |
|
177 | d = self.engine.push_function(dict(f=testf)) | |
178 | d.addCallback(lambda _: self.engine.execute('result = f(10)')) |
|
178 | d.addCallback(lambda _: self.engine.execute('result = f(10)')) | |
179 | d.addCallback(lambda _: self.engine.pull('result')) |
|
179 | d.addCallback(lambda _: self.engine.pull('result')) | |
180 | d.addCallback(lambda r: self.assertEquals(r, testf(10))) |
|
180 | d.addCallback(lambda r: self.assertEquals(r, testf(10))) | |
181 | return d |
|
181 | return d | |
182 |
|
182 | |||
183 | def testPullFunction(self): |
|
183 | def testPullFunction(self): | |
184 | d = self.engine.push_function(dict(f=testf, g=testg)) |
|
184 | d = self.engine.push_function(dict(f=testf, g=testg)) | |
185 | d.addCallback(lambda _: self.engine.pull_function(('f','g'))) |
|
185 | d.addCallback(lambda _: self.engine.pull_function(('f','g'))) | |
186 | d.addCallback(lambda r: self.assertEquals(r[0](10), testf(10))) |
|
186 | d.addCallback(lambda r: self.assertEquals(r[0](10), testf(10))) | |
187 | return d |
|
187 | return d | |
188 |
|
188 | |||
189 | def testPushFunctionGlobal(self): |
|
189 | def testPushFunctionGlobal(self): | |
190 | """Make sure that pushed functions pick up the user's namespace for globals.""" |
|
190 | """Make sure that pushed functions pick up the user's namespace for globals.""" | |
191 | d = self.engine.push(dict(globala=globala)) |
|
191 | d = self.engine.push(dict(globala=globala)) | |
192 | d.addCallback(lambda _: self.engine.push_function(dict(g=testg))) |
|
192 | d.addCallback(lambda _: self.engine.push_function(dict(g=testg))) | |
193 | d.addCallback(lambda _: self.engine.execute('result = g(10)')) |
|
193 | d.addCallback(lambda _: self.engine.execute('result = g(10)')) | |
194 | d.addCallback(lambda _: self.engine.pull('result')) |
|
194 | d.addCallback(lambda _: self.engine.pull('result')) | |
195 | d.addCallback(lambda r: self.assertEquals(r, testg(10))) |
|
195 | d.addCallback(lambda r: self.assertEquals(r, testg(10))) | |
196 | return d |
|
196 | return d | |
197 |
|
197 | |||
198 | def testGetResultFailure(self): |
|
198 | def testGetResultFailure(self): | |
199 | d = self.engine.get_result(None) |
|
199 | d = self.engine.get_result(None) | |
200 | d.addErrback(lambda f: self.assertRaises(IndexError, f.raiseException)) |
|
200 | d.addErrback(lambda f: self.assertRaises(IndexError, f.raiseException)) | |
201 | d.addCallback(lambda _: self.engine.get_result(10)) |
|
201 | d.addCallback(lambda _: self.engine.get_result(10)) | |
202 | d.addErrback(lambda f: self.assertRaises(IndexError, f.raiseException)) |
|
202 | d.addErrback(lambda f: self.assertRaises(IndexError, f.raiseException)) | |
203 | return d |
|
203 | return d | |
204 |
|
204 | |||
205 | def runTestGetResult(self, cmd): |
|
205 | def runTestGetResult(self, cmd): | |
206 | self.shell = Interpreter() |
|
206 | self.shell = Interpreter() | |
207 | actual = self.shell.execute(cmd) |
|
207 | actual = self.shell.execute(cmd) | |
208 | def compare(computed): |
|
208 | def compare(computed): | |
209 | actual['id'] = computed['id'] |
|
209 | actual['id'] = computed['id'] | |
210 | self.assertEquals(actual, computed) |
|
210 | self.assertEquals(actual, computed) | |
211 | d = self.engine.execute(cmd) |
|
211 | d = self.engine.execute(cmd) | |
212 | d.addCallback(lambda r: self.engine.get_result(r['number'])) |
|
212 | d.addCallback(lambda r: self.engine.get_result(r['number'])) | |
213 | d.addCallback(compare) |
|
213 | d.addCallback(compare) | |
214 | return d |
|
214 | return d | |
215 |
|
215 | |||
216 | @parametric |
|
216 | @parametric | |
217 | def testGetResult(cls): |
|
217 | def testGetResult(cls): | |
218 | return [(cls.runTestGetResult, cmd) for cmd in validCommands] |
|
218 | return [(cls.runTestGetResult, cmd) for cmd in validCommands] | |
219 |
|
219 | |||
220 | def testGetResultDefault(self): |
|
220 | def testGetResultDefault(self): | |
221 | cmd = 'a=5' |
|
221 | cmd = 'a=5' | |
222 | shell = self.createShell() |
|
222 | shell = self.createShell() | |
223 | shellResult = shell.execute(cmd) |
|
223 | shellResult = shell.execute(cmd) | |
224 | def popit(dikt, key): |
|
224 | def popit(dikt, key): | |
225 | dikt.pop(key) |
|
225 | dikt.pop(key) | |
226 | return dikt |
|
226 | return dikt | |
227 | d = self.engine.execute(cmd) |
|
227 | d = self.engine.execute(cmd) | |
228 | d.addCallback(lambda _: self.engine.get_result()) |
|
228 | d.addCallback(lambda _: self.engine.get_result()) | |
229 | d.addCallback(lambda r: self.assertEquals(shellResult, popit(r,'id'))) |
|
229 | d.addCallback(lambda r: self.assertEquals(shellResult, popit(r,'id'))) | |
230 | return d |
|
230 | return d | |
231 |
|
231 | |||
232 | def testKeys(self): |
|
232 | def testKeys(self): | |
233 | d = self.engine.keys() |
|
233 | d = self.engine.keys() | |
234 | d.addCallback(lambda s: isinstance(s, list)) |
|
234 | d.addCallback(lambda s: isinstance(s, list)) | |
235 | d.addCallback(lambda r: self.assertEquals(r, True)) |
|
235 | d.addCallback(lambda r: self.assertEquals(r, True)) | |
236 | return d |
|
236 | return d | |
237 |
|
237 | |||
238 | Parametric(IEngineCoreTestCase) |
|
238 | Parametric(IEngineCoreTestCase) | |
239 |
|
239 | |||
240 | class IEngineSerializedTestCase(object): |
|
240 | class IEngineSerializedTestCase(object): | |
241 | """Test an IEngineCore implementer.""" |
|
241 | """Test an IEngineCore implementer.""" | |
242 |
|
242 | |||
243 | def testIEngineSerializedInterface(self): |
|
243 | def testIEngineSerializedInterface(self): | |
244 | """Does self.engine claim to implement IEngineCore?""" |
|
244 | """Does self.engine claim to implement IEngineCore?""" | |
245 | self.assert_(es.IEngineSerialized.providedBy(self.engine)) |
|
245 | self.assert_(es.IEngineSerialized.providedBy(self.engine)) | |
246 |
|
246 | |||
247 | def testIEngineSerializedInterfaceMethods(self): |
|
247 | def testIEngineSerializedInterfaceMethods(self): | |
248 | """Does self.engine have the methods and attributes in IEngineCore.""" |
|
248 | """Does self.engine have the methods and attributes in IEngineCore.""" | |
249 | for m in list(es.IEngineSerialized): |
|
249 | for m in list(es.IEngineSerialized): | |
250 | self.assert_(hasattr(self.engine, m)) |
|
250 | self.assert_(hasattr(self.engine, m)) | |
251 |
|
251 | |||
252 | def testIEngineSerializedDeferreds(self): |
|
252 | def testIEngineSerializedDeferreds(self): | |
253 | dList = [] |
|
253 | dList = [] | |
254 | d = self.engine.push_serialized(dict(key=newserialized.serialize(12345))) |
|
254 | d = self.engine.push_serialized(dict(key=newserialized.serialize(12345))) | |
255 | self.assert_(isinstance(d, defer.Deferred)) |
|
255 | self.assert_(isinstance(d, defer.Deferred)) | |
256 | dList.append(d) |
|
256 | dList.append(d) | |
257 | d = self.engine.pull_serialized('key') |
|
257 | d = self.engine.pull_serialized('key') | |
258 | self.assert_(isinstance(d, defer.Deferred)) |
|
258 | self.assert_(isinstance(d, defer.Deferred)) | |
259 | dList.append(d) |
|
259 | dList.append(d) | |
260 | D = defer.DeferredList(dList) |
|
260 | D = defer.DeferredList(dList) | |
261 | return D |
|
261 | return D | |
262 |
|
262 | |||
263 | def testPushPullSerialized(self): |
|
263 | def testPushPullSerialized(self): | |
264 | objs = [10,"hi there",1.2342354,{"p":(1,2)}] |
|
264 | objs = [10,"hi there",1.2342354,{"p":(1,2)}] | |
265 | d = defer.succeed(None) |
|
265 | d = defer.succeed(None) | |
266 | for o in objs: |
|
266 | for o in objs: | |
267 | self.engine.push_serialized(dict(key=newserialized.serialize(o))) |
|
267 | self.engine.push_serialized(dict(key=newserialized.serialize(o))) | |
268 | value = self.engine.pull_serialized('key') |
|
268 | value = self.engine.pull_serialized('key') | |
269 | value.addCallback(lambda serial: newserialized.IUnSerialized(serial).getObject()) |
|
269 | value.addCallback(lambda serial: newserialized.IUnSerialized(serial).getObject()) | |
270 | d = self.assertDeferredEquals(value,o,d) |
|
270 | d = self.assertDeferredEquals(value,o,d) | |
271 | return d |
|
271 | return d | |
272 |
|
272 | |||
273 | def testPullSerializedFailures(self): |
|
273 | def testPullSerializedFailures(self): | |
274 | d = self.engine.pull_serialized('a') |
|
274 | d = self.engine.pull_serialized('a') | |
275 | d.addErrback(lambda f: self.assertRaises(NameError, f.raiseException)) |
|
275 | d.addErrback(lambda f: self.assertRaises(NameError, f.raiseException)) | |
276 | d.addCallback(lambda _: self.engine.execute('l = lambda x: x')) |
|
276 | d.addCallback(lambda _: self.engine.execute('l = lambda x: x')) | |
277 | d.addCallback(lambda _: self.engine.pull_serialized('l')) |
|
277 | d.addCallback(lambda _: self.engine.pull_serialized('l')) | |
278 | d.addErrback(lambda f: self.assertRaises(pickle.PicklingError, f.raiseException)) |
|
278 | d.addErrback(lambda f: self.assertRaises(pickle.PicklingError, f.raiseException)) | |
279 | return d |
|
279 | return d | |
280 |
|
280 | |||
281 | Parametric(IEngineSerializedTestCase) |
|
281 | Parametric(IEngineSerializedTestCase) | |
282 |
|
282 | |||
283 | class IEngineQueuedTestCase(object): |
|
283 | class IEngineQueuedTestCase(object): | |
284 | """Test an IEngineQueued implementer.""" |
|
284 | """Test an IEngineQueued implementer.""" | |
285 |
|
285 | |||
286 | def testIEngineQueuedInterface(self): |
|
286 | def testIEngineQueuedInterface(self): | |
287 | """Does self.engine claim to implement IEngineQueued?""" |
|
287 | """Does self.engine claim to implement IEngineQueued?""" | |
288 | self.assert_(es.IEngineQueued.providedBy(self.engine)) |
|
288 | self.assert_(es.IEngineQueued.providedBy(self.engine)) | |
289 |
|
289 | |||
290 | def testIEngineQueuedInterfaceMethods(self): |
|
290 | def testIEngineQueuedInterfaceMethods(self): | |
291 | """Does self.engine have the methods and attributes in IEngineQueued.""" |
|
291 | """Does self.engine have the methods and attributes in IEngineQueued.""" | |
292 | for m in list(es.IEngineQueued): |
|
292 | for m in list(es.IEngineQueued): | |
293 | self.assert_(hasattr(self.engine, m)) |
|
293 | self.assert_(hasattr(self.engine, m)) | |
294 |
|
294 | |||
295 | def testIEngineQueuedDeferreds(self): |
|
295 | def testIEngineQueuedDeferreds(self): | |
296 | dList = [] |
|
296 | dList = [] | |
297 | d = self.engine.clear_queue() |
|
297 | d = self.engine.clear_queue() | |
298 | self.assert_(isinstance(d, defer.Deferred)) |
|
298 | self.assert_(isinstance(d, defer.Deferred)) | |
299 | dList.append(d) |
|
299 | dList.append(d) | |
300 | d = self.engine.queue_status() |
|
300 | d = self.engine.queue_status() | |
301 | self.assert_(isinstance(d, defer.Deferred)) |
|
301 | self.assert_(isinstance(d, defer.Deferred)) | |
302 | dList.append(d) |
|
302 | dList.append(d) | |
303 | D = defer.DeferredList(dList) |
|
303 | D = defer.DeferredList(dList) | |
304 | return D |
|
304 | return D | |
305 |
|
305 | |||
306 | def testClearQueue(self): |
|
306 | def testClearQueue(self): | |
307 | result = self.engine.clear_queue() |
|
307 | result = self.engine.clear_queue() | |
308 | d1 = self.assertDeferredEquals(result, None) |
|
308 | d1 = self.assertDeferredEquals(result, None) | |
309 | d1.addCallback(lambda _: self.engine.queue_status()) |
|
309 | d1.addCallback(lambda _: self.engine.queue_status()) | |
310 | d2 = self.assertDeferredEquals(d1, {'queue':[], 'pending':'None'}) |
|
310 | d2 = self.assertDeferredEquals(d1, {'queue':[], 'pending':'None'}) | |
311 | return d2 |
|
311 | return d2 | |
312 |
|
312 | |||
313 | def testQueueStatus(self): |
|
313 | def testQueueStatus(self): | |
314 | result = self.engine.queue_status() |
|
314 | result = self.engine.queue_status() | |
315 | result.addCallback(lambda r: 'queue' in r and 'pending' in r) |
|
315 | result.addCallback(lambda r: 'queue' in r and 'pending' in r) | |
316 | d = self.assertDeferredEquals(result, True) |
|
316 | d = self.assertDeferredEquals(result, True) | |
317 | return d |
|
317 | return d | |
318 |
|
318 | |||
319 | Parametric(IEngineQueuedTestCase) |
|
319 | Parametric(IEngineQueuedTestCase) | |
320 |
|
320 | |||
321 | class IEnginePropertiesTestCase(object): |
|
321 | class IEnginePropertiesTestCase(object): | |
322 | """Test an IEngineProperties implementor.""" |
|
322 | """Test an IEngineProperties implementor.""" | |
323 |
|
323 | |||
324 | def testIEnginePropertiesInterface(self): |
|
324 | def testIEnginePropertiesInterface(self): | |
325 | """Does self.engine claim to implement IEngineProperties?""" |
|
325 | """Does self.engine claim to implement IEngineProperties?""" | |
326 | self.assert_(es.IEngineProperties.providedBy(self.engine)) |
|
326 | self.assert_(es.IEngineProperties.providedBy(self.engine)) | |
327 |
|
327 | |||
328 | def testIEnginePropertiesInterfaceMethods(self): |
|
328 | def testIEnginePropertiesInterfaceMethods(self): | |
329 | """Does self.engine have the methods and attributes in IEngineProperties.""" |
|
329 | """Does self.engine have the methods and attributes in IEngineProperties.""" | |
330 | for m in list(es.IEngineProperties): |
|
330 | for m in list(es.IEngineProperties): | |
331 | self.assert_(hasattr(self.engine, m)) |
|
331 | self.assert_(hasattr(self.engine, m)) | |
332 |
|
332 | |||
333 | def testGetSetProperties(self): |
|
333 | def testGetSetProperties(self): | |
334 | dikt = dict(a=5, b='asdf', c=True, d=None, e=range(5)) |
|
334 | dikt = dict(a=5, b='asdf', c=True, d=None, e=range(5)) | |
335 | d = self.engine.set_properties(dikt) |
|
335 | d = self.engine.set_properties(dikt) | |
336 | d.addCallback(lambda r: self.engine.get_properties()) |
|
336 | d.addCallback(lambda r: self.engine.get_properties()) | |
337 | d = self.assertDeferredEquals(d, dikt) |
|
337 | d = self.assertDeferredEquals(d, dikt) | |
338 | d.addCallback(lambda r: self.engine.get_properties(('c',))) |
|
338 | d.addCallback(lambda r: self.engine.get_properties(('c',))) | |
339 | d = self.assertDeferredEquals(d, {'c': dikt['c']}) |
|
339 | d = self.assertDeferredEquals(d, {'c': dikt['c']}) | |
340 | d.addCallback(lambda r: self.engine.set_properties(dict(c=False))) |
|
340 | d.addCallback(lambda r: self.engine.set_properties(dict(c=False))) | |
341 | d.addCallback(lambda r: self.engine.get_properties(('c', 'd'))) |
|
341 | d.addCallback(lambda r: self.engine.get_properties(('c', 'd'))) | |
342 | d = self.assertDeferredEquals(d, dict(c=False, d=None)) |
|
342 | d = self.assertDeferredEquals(d, dict(c=False, d=None)) | |
343 | return d |
|
343 | return d | |
344 |
|
344 | |||
345 | def testClearProperties(self): |
|
345 | def testClearProperties(self): | |
346 | dikt = dict(a=5, b='asdf', c=True, d=None, e=range(5)) |
|
346 | dikt = dict(a=5, b='asdf', c=True, d=None, e=range(5)) | |
347 | d = self.engine.set_properties(dikt) |
|
347 | d = self.engine.set_properties(dikt) | |
348 | d.addCallback(lambda r: self.engine.clear_properties()) |
|
348 | d.addCallback(lambda r: self.engine.clear_properties()) | |
349 | d.addCallback(lambda r: self.engine.get_properties()) |
|
349 | d.addCallback(lambda r: self.engine.get_properties()) | |
350 | d = self.assertDeferredEquals(d, {}) |
|
350 | d = self.assertDeferredEquals(d, {}) | |
351 | return d |
|
351 | return d | |
352 |
|
352 | |||
353 | def testDelHasProperties(self): |
|
353 | def testDelHasProperties(self): | |
354 | dikt = dict(a=5, b='asdf', c=True, d=None, e=range(5)) |
|
354 | dikt = dict(a=5, b='asdf', c=True, d=None, e=range(5)) | |
355 | d = self.engine.set_properties(dikt) |
|
355 | d = self.engine.set_properties(dikt) | |
356 | d.addCallback(lambda r: self.engine.del_properties(('b','e'))) |
|
356 | d.addCallback(lambda r: self.engine.del_properties(('b','e'))) | |
357 | d.addCallback(lambda r: self.engine.has_properties(('a','b','c','d','e'))) |
|
357 | d.addCallback(lambda r: self.engine.has_properties(('a','b','c','d','e'))) | |
358 | d = self.assertDeferredEquals(d, [True, False, True, True, False]) |
|
358 | d = self.assertDeferredEquals(d, [True, False, True, True, False]) | |
359 | return d |
|
359 | return d | |
360 |
|
360 | |||
361 | def testStrictDict(self): |
|
361 | def testStrictDict(self): | |
362 | s = """from IPython.kernel.engineservice import get_engine |
|
362 | s = """from IPython.kernel.engineservice import get_engine | |
363 | p = get_engine(%s).properties"""%self.engine.id |
|
363 | p = get_engine(%s).properties"""%self.engine.id | |
364 | d = self.engine.execute(s) |
|
364 | d = self.engine.execute(s) | |
365 | d.addCallback(lambda r: self.engine.execute("p['a'] = lambda _:None")) |
|
365 | d.addCallback(lambda r: self.engine.execute("p['a'] = lambda _:None")) | |
366 | d = self.assertDeferredRaises(d, error.InvalidProperty) |
|
366 | d = self.assertDeferredRaises(d, error.InvalidProperty) | |
367 | d.addCallback(lambda r: self.engine.execute("p['a'] = range(5)")) |
|
367 | d.addCallback(lambda r: self.engine.execute("p['a'] = range(5)")) | |
368 | d.addCallback(lambda r: self.engine.execute("p['a'].append(5)")) |
|
368 | d.addCallback(lambda r: self.engine.execute("p['a'].append(5)")) | |
369 | d.addCallback(lambda r: self.engine.get_properties('a')) |
|
369 | d.addCallback(lambda r: self.engine.get_properties('a')) | |
370 | d = self.assertDeferredEquals(d, dict(a=range(5))) |
|
370 | d = self.assertDeferredEquals(d, dict(a=range(5))) | |
371 | return d |
|
371 | return d | |
372 |
|
372 | |||
373 | Parametric(IEnginePropertiesTestCase) |
|
373 | Parametric(IEnginePropertiesTestCase) |
General Comments 0
You need to be logged in to leave comments.
Login now