##// END OF EJS Templates
Merge with upstream
Fernando Perez -
r1483:3d01fd53 merge
parent child Browse files
Show More
@@ -1,592 +1,578 b''
1 """ ILeo - Leo plugin for IPython
1 """ ILeo - Leo plugin for IPython
2
2
3
3
4 """
4 """
5 import IPython.ipapi
5 import IPython.ipapi
6 import IPython.genutils
6 import IPython.genutils
7 import IPython.generics
7 import IPython.generics
8 from IPython.hooks import CommandChainDispatcher
8 from IPython.hooks import CommandChainDispatcher
9 import re
9 import re
10 import UserDict
10 import UserDict
11 from IPython.ipapi import TryNext
11 from IPython.ipapi import TryNext
12 import IPython.macro
12 import IPython.macro
13 import IPython.Shell
13 import IPython.Shell
14
14
15 def init_ipython(ipy):
15 def init_ipython(ipy):
16 """ This will be run by _ip.load('ipy_leo')
16 """ This will be run by _ip.load('ipy_leo')
17
17
18 Leo still needs to run update_commander() after this.
18 Leo still needs to run update_commander() after this.
19
19
20 """
20 """
21 global ip
21 global ip
22 ip = ipy
22 ip = ipy
23 IPython.Shell.hijack_tk()
23 IPython.Shell.hijack_tk()
24 ip.set_hook('complete_command', mb_completer, str_key = '%mb')
24 ip.set_hook('complete_command', mb_completer, str_key = '%mb')
25 ip.expose_magic('mb',mb_f)
25 ip.expose_magic('mb',mb_f)
26 ip.expose_magic('lee',lee_f)
26 ip.expose_magic('lee',lee_f)
27 ip.expose_magic('leoref',leoref_f)
27 ip.expose_magic('leoref',leoref_f)
28 expose_ileo_push(push_cl_node,100)
28 expose_ileo_push(push_cl_node,100)
29 # this should be the LAST one that will be executed, and it will never raise TryNext
29 # this should be the LAST one that will be executed, and it will never raise TryNext
30 expose_ileo_push(push_ipython_script, 1000)
30 expose_ileo_push(push_ipython_script, 1000)
31 expose_ileo_push(push_plain_python, 100)
31 expose_ileo_push(push_plain_python, 100)
32 expose_ileo_push(push_ev_node, 100)
32 expose_ileo_push(push_ev_node, 100)
33 global wb
33 global wb
34 wb = LeoWorkbook()
34 wb = LeoWorkbook()
35 ip.user_ns['wb'] = wb
35 ip.user_ns['wb'] = wb
36
36
37 show_welcome()
37 show_welcome()
38
38
39
39
40 def update_commander(new_leox):
40 def update_commander(new_leox):
41 """ Set the Leo commander to use
41 """ Set the Leo commander to use
42
42
43 This will be run every time Leo does ipython-launch; basically,
43 This will be run every time Leo does ipython-launch; basically,
44 when the user switches the document he is focusing on, he should do
44 when the user switches the document he is focusing on, he should do
45 ipython-launch to tell ILeo what document the commands apply to.
45 ipython-launch to tell ILeo what document the commands apply to.
46
46
47 """
47 """
48
48
49 global c,g
49 global c,g
50 c,g = new_leox.c, new_leox.g
50 c,g = new_leox.c, new_leox.g
51 print "Set Leo Commander:",c.frame.getTitle()
51 print "Set Leo Commander:",c.frame.getTitle()
52
52
53 # will probably be overwritten by user, but handy for experimentation early on
53 # will probably be overwritten by user, but handy for experimentation early on
54 ip.user_ns['c'] = c
54 ip.user_ns['c'] = c
55 ip.user_ns['g'] = g
55 ip.user_ns['g'] = g
56 ip.user_ns['_leo'] = new_leox
56 ip.user_ns['_leo'] = new_leox
57
57
58 new_leox.push = push_position_from_leo
58 new_leox.push = push_position_from_leo
59 run_leo_startup_node()
59 run_leo_startup_node()
60
60
61 from IPython.external.simplegeneric import generic
61 from IPython.external.simplegeneric import generic
62 import pprint
62 import pprint
63
63
64 def es(s):
64 def es(s):
65 g.es(s, tabName = 'IPython')
65 g.es(s, tabName = 'IPython')
66 pass
66 pass
67
67
68 @generic
68 @generic
69 def format_for_leo(obj):
69 def format_for_leo(obj):
70 """ Convert obj to string representiation (for editing in Leo)"""
70 """ Convert obj to string representiation (for editing in Leo)"""
71 return pprint.pformat(obj)
71 return pprint.pformat(obj)
72
72
73 @format_for_leo.when_type(list)
73 @format_for_leo.when_type(list)
74 def format_list(obj):
74 def format_list(obj):
75 return "\n".join(str(s) for s in obj)
75 return "\n".join(str(s) for s in obj)
76
76
77
77
78 attribute_re = re.compile('^[a-zA-Z_][a-zA-Z0-9_]*$')
78 attribute_re = re.compile('^[a-zA-Z_][a-zA-Z0-9_]*$')
79 def valid_attribute(s):
79 def valid_attribute(s):
80 return attribute_re.match(s)
80 return attribute_re.match(s)
81
81
82 _rootnode = None
82 _rootnode = None
83 def rootnode():
83 def rootnode():
84 """ Get ileo root node (@ipy-root)
84 """ Get ileo root node (@ipy-root)
85
85
86 if node has become invalid or has not been set, return None
86 if node has become invalid or has not been set, return None
87
87
88 Note that the root is the *first* @ipy-root item found
88 Note that the root is the *first* @ipy-root item found
89 """
89 """
90 global _rootnode
90 global _rootnode
91 if _rootnode is None:
91 if _rootnode is None:
92 return None
92 return None
93 if c.positionExists(_rootnode.p):
93 if c.positionExists(_rootnode.p):
94 return _rootnode
94 return _rootnode
95 _rootnode = None
95 _rootnode = None
96 return None
96 return None
97
97
98 def all_cells():
98 def all_cells():
99 global _rootnode
99 global _rootnode
100 d = {}
100 d = {}
101 r = rootnode()
101 r = rootnode()
102 if r is not None:
102 if r is not None:
103 nodes = r.p.children_iter()
103 nodes = r.p.children_iter()
104 else:
104 else:
105 nodes = c.allNodes_iter()
105 nodes = c.allNodes_iter()
106
106
107 for p in nodes:
107 for p in nodes:
108 h = p.headString()
108 h = p.headString()
109 if h.strip() == '@ipy-root':
109 if h.strip() == '@ipy-root':
110 # update root node (found it for the first time)
110 # update root node (found it for the first time)
111 _rootnode = LeoNode(p)
111 _rootnode = LeoNode(p)
112 # the next recursive call will use the children of new root
112 # the next recursive call will use the children of new root
113 return all_cells()
113 return all_cells()
114
114
115 if h.startswith('@a '):
115 if h.startswith('@a '):
116 d[h.lstrip('@a ').strip()] = p.parent().copy()
116 d[h.lstrip('@a ').strip()] = p.parent().copy()
117 elif not valid_attribute(h):
117 elif not valid_attribute(h):
118 continue
118 continue
119 d[h] = p.copy()
119 d[h] = p.copy()
120 return d
120 return d
121
121
122 def eval_node(n):
122 def eval_node(n):
123 body = n.b
123 body = n.b
124 if not body.startswith('@cl'):
124 if not body.startswith('@cl'):
125 # plain python repr node, just eval it
125 # plain python repr node, just eval it
126 return ip.ev(n.b)
126 return ip.ev(n.b)
127 # @cl nodes deserve special treatment - first eval the first line (minus cl), then use it to call the rest of body
127 # @cl nodes deserve special treatment - first eval the first line (minus cl), then use it to call the rest of body
128 first, rest = body.split('\n',1)
128 first, rest = body.split('\n',1)
129 tup = first.split(None, 1)
129 tup = first.split(None, 1)
130 # @cl alone SPECIAL USE-> dump var to user_ns
130 # @cl alone SPECIAL USE-> dump var to user_ns
131 if len(tup) == 1:
131 if len(tup) == 1:
132 val = ip.ev(rest)
132 val = ip.ev(rest)
133 ip.user_ns[n.h] = val
133 ip.user_ns[n.h] = val
134 es("%s = %s" % (n.h, repr(val)[:20] ))
134 es("%s = %s" % (n.h, repr(val)[:20] ))
135 return val
135 return val
136
136
137 cl, hd = tup
137 cl, hd = tup
138
138
139 xformer = ip.ev(hd.strip())
139 xformer = ip.ev(hd.strip())
140 es('Transform w/ %s' % repr(xformer))
140 es('Transform w/ %s' % repr(xformer))
141 return xformer(rest, n)
141 return xformer(rest, n)
142
142
143 class LeoNode(object, UserDict.DictMixin):
143 class LeoNode(object, UserDict.DictMixin):
144 """ Node in Leo outline
144 """ Node in Leo outline
145
145
146 Most important attributes (getters/setters available:
146 Most important attributes (getters/setters available:
147 .v - evaluate node, can also be alligned
147 .v - evaluate node, can also be alligned
148 .b, .h - body string, headline string
148 .b, .h - body string, headline string
149 .l - value as string list
149 .l - value as string list
150
150
151 Also supports iteration,
151 Also supports iteration,
152
152
153 setitem / getitem (indexing):
153 setitem / getitem (indexing):
154 wb.foo['key'] = 12
154 wb.foo['key'] = 12
155 assert wb.foo['key'].v == 12
155 assert wb.foo['key'].v == 12
156
156
157 Note the asymmetry on setitem and getitem! Also other
157 Note the asymmetry on setitem and getitem! Also other
158 dict methods are available.
158 dict methods are available.
159
159
160 .ipush() - run push-to-ipython
160 .ipush() - run push-to-ipython
161
161
162 Minibuffer command access (tab completion works):
162 Minibuffer command access (tab completion works):
163
163
164 mb save-to-file
164 mb save-to-file
165
165
166 """
166 """
167 def __init__(self,p):
167 def __init__(self,p):
168 self.p = p.copy()
168 self.p = p.copy()
169
169
170 def __str__(self):
170 def __str__(self):
171 return "<LeoNode %s>" % str(self.p)
171 return "<LeoNode %s>" % str(self.p)
172
172
173 __repr__ = __str__
173 __repr__ = __str__
174
174
175 def __get_h(self): return self.p.headString()
175 def __get_h(self): return self.p.headString()
176 def __set_h(self,val):
176 def __set_h(self,val):
177 print "set head",val
177 c.setHeadString(self.p,val)
178 c.beginUpdate()
178 c.redraw()
179 try:
180 c.setHeadString(self.p,val)
181 finally:
182 c.endUpdate()
183
179
184 h = property( __get_h, __set_h, doc = "Node headline string")
180 h = property( __get_h, __set_h, doc = "Node headline string")
185
181
186 def __get_b(self): return self.p.bodyString()
182 def __get_b(self): return self.p.bodyString()
187 def __set_b(self,val):
183 def __set_b(self,val):
188 print "set body",val
184 c.setBodyString(self.p, val)
189 c.beginUpdate()
185 c.redraw()
190 try:
191 c.setBodyString(self.p, val)
192 finally:
193 c.endUpdate()
194
186
195 b = property(__get_b, __set_b, doc = "Nody body string")
187 b = property(__get_b, __set_b, doc = "Nody body string")
196
188
197 def __set_val(self, val):
189 def __set_val(self, val):
198 self.b = format_for_leo(val)
190 self.b = format_for_leo(val)
199
191
200 v = property(lambda self: eval_node(self), __set_val, doc = "Node evaluated value")
192 v = property(lambda self: eval_node(self), __set_val, doc = "Node evaluated value")
201
193
202 def __set_l(self,val):
194 def __set_l(self,val):
203 self.b = '\n'.join(val )
195 self.b = '\n'.join(val )
204 l = property(lambda self : IPython.genutils.SList(self.b.splitlines()),
196 l = property(lambda self : IPython.genutils.SList(self.b.splitlines()),
205 __set_l, doc = "Node value as string list")
197 __set_l, doc = "Node value as string list")
206
198
207 def __iter__(self):
199 def __iter__(self):
208 """ Iterate through nodes direct children """
200 """ Iterate through nodes direct children """
209
201
210 return (LeoNode(p) for p in self.p.children_iter())
202 return (LeoNode(p) for p in self.p.children_iter())
211
203
212 def __children(self):
204 def __children(self):
213 d = {}
205 d = {}
214 for child in self:
206 for child in self:
215 head = child.h
207 head = child.h
216 tup = head.split(None,1)
208 tup = head.split(None,1)
217 if len(tup) > 1 and tup[0] == '@k':
209 if len(tup) > 1 and tup[0] == '@k':
218 d[tup[1]] = child
210 d[tup[1]] = child
219 continue
211 continue
220
212
221 if not valid_attribute(head):
213 if not valid_attribute(head):
222 d[head] = child
214 d[head] = child
223 continue
215 continue
224 return d
216 return d
225 def keys(self):
217 def keys(self):
226 d = self.__children()
218 d = self.__children()
227 return d.keys()
219 return d.keys()
228 def __getitem__(self, key):
220 def __getitem__(self, key):
229 """ wb.foo['Some stuff'] Return a child node with headline 'Some stuff'
221 """ wb.foo['Some stuff'] Return a child node with headline 'Some stuff'
230
222
231 If key is a valid python name (e.g. 'foo'), look for headline '@k foo' as well
223 If key is a valid python name (e.g. 'foo'), look for headline '@k foo' as well
232 """
224 """
233 key = str(key)
225 key = str(key)
234 d = self.__children()
226 d = self.__children()
235 return d[key]
227 return d[key]
236 def __setitem__(self, key, val):
228 def __setitem__(self, key, val):
237 """ You can do wb.foo['My Stuff'] = 12 to create children
229 """ You can do wb.foo['My Stuff'] = 12 to create children
238
230
239 This will create 'My Stuff' as a child of foo (if it does not exist), and
231 This will create 'My Stuff' as a child of foo (if it does not exist), and
240 do .v = 12 assignment.
232 do .v = 12 assignment.
241
233
242 Exception:
234 Exception:
243
235
244 wb.foo['bar'] = 12
236 wb.foo['bar'] = 12
245
237
246 will create a child with headline '@k bar', because bar is a valid python name
238 will create a child with headline '@k bar', because bar is a valid python name
247 and we don't want to crowd the WorkBook namespace with (possibly numerous) entries
239 and we don't want to crowd the WorkBook namespace with (possibly numerous) entries
248 """
240 """
249 key = str(key)
241 key = str(key)
250 d = self.__children()
242 d = self.__children()
251 if key in d:
243 if key in d:
252 d[key].v = val
244 d[key].v = val
253 return
245 return
254
246
255 if not valid_attribute(key):
247 if not valid_attribute(key):
256 head = key
248 head = key
257 else:
249 else:
258 head = '@k ' + key
250 head = '@k ' + key
259 p = c.createLastChildNode(self.p, head, '')
251 p = c.createLastChildNode(self.p, head, '')
260 LeoNode(p).v = val
252 LeoNode(p).v = val
261
253
262 def ipush(self):
254 def ipush(self):
263 """ Does push-to-ipython on the node """
255 """ Does push-to-ipython on the node """
264 push_from_leo(self)
256 push_from_leo(self)
265
257
266 def go(self):
258 def go(self):
267 """ Set node as current node (to quickly see it in Outline) """
259 """ Set node as current node (to quickly see it in Outline) """
268 c.beginUpdate()
260 c.setCurrentPosition(self.p)
269 try:
261 c.redraw()
270 c.setCurrentPosition(self.p)
271 finally:
272 c.endUpdate()
273
262
274 def script(self):
263 def script(self):
275 """ Method to get the 'tangled' contents of the node
264 """ Method to get the 'tangled' contents of the node
276
265
277 (parse @others, << section >> references etc.)
266 (parse @others, << section >> references etc.)
278 """
267 """
279 return g.getScript(c,self.p,useSelectedText=False,useSentinels=False)
268 return g.getScript(c,self.p,useSelectedText=False,useSentinels=False)
280
269
281 def __get_uA(self):
270 def __get_uA(self):
282 p = self.p
271 p = self.p
283 # Create the uA if necessary.
272 # Create the uA if necessary.
284 if not hasattr(p.v.t,'unknownAttributes'):
273 if not hasattr(p.v.t,'unknownAttributes'):
285 p.v.t.unknownAttributes = {}
274 p.v.t.unknownAttributes = {}
286
275
287 d = p.v.t.unknownAttributes.setdefault('ipython', {})
276 d = p.v.t.unknownAttributes.setdefault('ipython', {})
288 return d
277 return d
289
278
290 uA = property(__get_uA, doc = "Access persistent unknownAttributes of node")
279 uA = property(__get_uA, doc = "Access persistent unknownAttributes of node")
291
280
292
281
293 class LeoWorkbook:
282 class LeoWorkbook:
294 """ class for 'advanced' node access
283 """ class for 'advanced' node access
295
284
296 Has attributes for all "discoverable" nodes. Node is discoverable if it
285 Has attributes for all "discoverable" nodes. Node is discoverable if it
297 either
286 either
298
287
299 - has a valid python name (Foo, bar_12)
288 - has a valid python name (Foo, bar_12)
300 - is a parent of an anchor node (if it has a child '@a foo', it is visible as foo)
289 - is a parent of an anchor node (if it has a child '@a foo', it is visible as foo)
301
290
302 """
291 """
303 def __getattr__(self, key):
292 def __getattr__(self, key):
304 if key.startswith('_') or key == 'trait_names' or not valid_attribute(key):
293 if key.startswith('_') or key == 'trait_names' or not valid_attribute(key):
305 raise AttributeError
294 raise AttributeError
306 cells = all_cells()
295 cells = all_cells()
307 p = cells.get(key, None)
296 p = cells.get(key, None)
308 if p is None:
297 if p is None:
309 return add_var(key)
298 return add_var(key)
310
299
311 return LeoNode(p)
300 return LeoNode(p)
312
301
313 def __str__(self):
302 def __str__(self):
314 return "<LeoWorkbook>"
303 return "<LeoWorkbook>"
315 def __setattr__(self,key, val):
304 def __setattr__(self,key, val):
316 raise AttributeError("Direct assignment to workbook denied, try wb.%s.v = %s" % (key,val))
305 raise AttributeError("Direct assignment to workbook denied, try wb.%s.v = %s" % (key,val))
317
306
318 __repr__ = __str__
307 __repr__ = __str__
319
308
320 def __iter__(self):
309 def __iter__(self):
321 """ Iterate all (even non-exposed) nodes """
310 """ Iterate all (even non-exposed) nodes """
322 cells = all_cells()
311 cells = all_cells()
323 return (LeoNode(p) for p in c.allNodes_iter())
312 return (LeoNode(p) for p in c.allNodes_iter())
324
313
325 current = property(lambda self: LeoNode(c.currentPosition()), doc = "Currently selected node")
314 current = property(lambda self: LeoNode(c.currentPosition()), doc = "Currently selected node")
326
315
327 def match_h(self, regex):
316 def match_h(self, regex):
328 cmp = re.compile(regex)
317 cmp = re.compile(regex)
329 for node in self:
318 for node in self:
330 if re.match(cmp, node.h, re.IGNORECASE):
319 if re.match(cmp, node.h, re.IGNORECASE):
331 yield node
320 yield node
332 return
321 return
333
322
334 @IPython.generics.complete_object.when_type(LeoWorkbook)
323 @IPython.generics.complete_object.when_type(LeoWorkbook)
335 def workbook_complete(obj, prev):
324 def workbook_complete(obj, prev):
336 return all_cells().keys() + [s for s in prev if not s.startswith('_')]
325 return all_cells().keys() + [s for s in prev if not s.startswith('_')]
337
326
338
327
339 def add_var(varname):
328 def add_var(varname):
340 c.beginUpdate()
341 r = rootnode()
329 r = rootnode()
342 try:
330 try:
343 if r is None:
331 if r is None:
344 p2 = g.findNodeAnywhere(c,varname)
332 p2 = g.findNodeAnywhere(c,varname)
345 else:
333 else:
346 p2 = g.findNodeInChildren(c, r.p, varname)
334 p2 = g.findNodeInChildren(c, r.p, varname)
347 if p2:
335 if p2:
348 return LeoNode(p2)
336 return LeoNode(p2)
349
337
350 if r is not None:
338 if r is not None:
351 p2 = r.p.insertAsLastChild()
339 p2 = r.p.insertAsLastChild()
352
340
353 else:
341 else:
354 p2 = c.currentPosition().insertAfter()
342 p2 = c.currentPosition().insertAfter()
355
343
356 c.setHeadString(p2,varname)
344 c.setHeadString(p2,varname)
357 return LeoNode(p2)
345 return LeoNode(p2)
358 finally:
346 finally:
359 c.endUpdate()
347 c.redraw()
360
348
361 def add_file(self,fname):
349 def add_file(self,fname):
362 p2 = c.currentPosition().insertAfter()
350 p2 = c.currentPosition().insertAfter()
363
351
364 push_from_leo = CommandChainDispatcher()
352 push_from_leo = CommandChainDispatcher()
365
353
366 def expose_ileo_push(f, prio = 0):
354 def expose_ileo_push(f, prio = 0):
367 push_from_leo.add(f, prio)
355 push_from_leo.add(f, prio)
368
356
369 def push_ipython_script(node):
357 def push_ipython_script(node):
370 """ Execute the node body in IPython, as if it was entered in interactive prompt """
358 """ Execute the node body in IPython, as if it was entered in interactive prompt """
371 c.beginUpdate()
372 try:
359 try:
373 ohist = ip.IP.output_hist
360 ohist = ip.IP.output_hist
374 hstart = len(ip.IP.input_hist)
361 hstart = len(ip.IP.input_hist)
375 script = node.script()
362 script = node.script()
376
363
377 ip.user_ns['_p'] = node
364 ip.user_ns['_p'] = node
378 ip.runlines(script)
365 ip.runlines(script)
379 ip.user_ns.pop('_p',None)
366 ip.user_ns.pop('_p',None)
380
367
381 has_output = False
368 has_output = False
382 for idx in range(hstart,len(ip.IP.input_hist)):
369 for idx in range(hstart,len(ip.IP.input_hist)):
383 val = ohist.get(idx,None)
370 val = ohist.get(idx,None)
384 if val is None:
371 if val is None:
385 continue
372 continue
386 has_output = True
373 has_output = True
387 inp = ip.IP.input_hist[idx]
374 inp = ip.IP.input_hist[idx]
388 if inp.strip():
375 if inp.strip():
389 es('In: %s' % (inp[:40], ))
376 es('In: %s' % (inp[:40], ))
390
377
391 es('<%d> %s' % (idx, pprint.pformat(ohist[idx],width = 40)))
378 es('<%d> %s' % (idx, pprint.pformat(ohist[idx],width = 40)))
392
379
393 if not has_output:
380 if not has_output:
394 es('ipy run: %s (%d LL)' %( node.h,len(script)))
381 es('ipy run: %s (%d LL)' %( node.h,len(script)))
395 finally:
382 finally:
396 c.endUpdate()
383 c.redraw()
397
384
398
385
399 def eval_body(body):
386 def eval_body(body):
400 try:
387 try:
401 val = ip.ev(body)
388 val = ip.ev(body)
402 except:
389 except:
403 # just use stringlist if it's not completely legal python expression
390 # just use stringlist if it's not completely legal python expression
404 val = IPython.genutils.SList(body.splitlines())
391 val = IPython.genutils.SList(body.splitlines())
405 return val
392 return val
406
393
407 def push_plain_python(node):
394 def push_plain_python(node):
408 if not node.h.endswith('P'):
395 if not node.h.endswith('P'):
409 raise TryNext
396 raise TryNext
410 script = node.script()
397 script = node.script()
411 lines = script.count('\n')
398 lines = script.count('\n')
412 try:
399 try:
413 exec script in ip.user_ns
400 exec script in ip.user_ns
414 except:
401 except:
415 print " -- Exception in script:\n"+script + "\n --"
402 print " -- Exception in script:\n"+script + "\n --"
416 raise
403 raise
417 es('ipy plain: %s (%d LL)' % (node.h,lines))
404 es('ipy plain: %s (%d LL)' % (node.h,lines))
418
405
419
406
420 def push_cl_node(node):
407 def push_cl_node(node):
421 """ If node starts with @cl, eval it
408 """ If node starts with @cl, eval it
422
409
423 The result is put as last child of @ipy-results node, if it exists
410 The result is put as last child of @ipy-results node, if it exists
424 """
411 """
425 if not node.b.startswith('@cl'):
412 if not node.b.startswith('@cl'):
426 raise TryNext
413 raise TryNext
427
414
428 p2 = g.findNodeAnywhere(c,'@ipy-results')
415 p2 = g.findNodeAnywhere(c,'@ipy-results')
429 val = node.v
416 val = node.v
430 if p2:
417 if p2:
431 es("=> @ipy-results")
418 es("=> @ipy-results")
432 LeoNode(p2).v = val
419 LeoNode(p2).v = val
433 es(val)
420 es(val)
434
421
435 def push_ev_node(node):
422 def push_ev_node(node):
436 """ If headline starts with @ev, eval it and put result in body """
423 """ If headline starts with @ev, eval it and put result in body """
437 if not node.h.startswith('@ev '):
424 if not node.h.startswith('@ev '):
438 raise TryNext
425 raise TryNext
439 expr = node.h.lstrip('@ev ')
426 expr = node.h.lstrip('@ev ')
440 es('ipy eval ' + expr)
427 es('ipy eval ' + expr)
441 res = ip.ev(expr)
428 res = ip.ev(expr)
442 node.v = res
429 node.v = res
443
430
444
431
445 def push_position_from_leo(p):
432 def push_position_from_leo(p):
446 try:
433 try:
447 push_from_leo(LeoNode(p))
434 push_from_leo(LeoNode(p))
448 except AttributeError,e:
435 except AttributeError,e:
449 if e.args == ("Commands instance has no attribute 'frame'",):
436 if e.args == ("Commands instance has no attribute 'frame'",):
450 es("Error: ILeo not associated with .leo document")
437 es("Error: ILeo not associated with .leo document")
451 es("Press alt+shift+I to fix!")
438 es("Press alt+shift+I to fix!")
452 else:
439 else:
453 raise
440 raise
454
441
455 @generic
442 @generic
456 def edit_object_in_leo(obj, varname):
443 def edit_object_in_leo(obj, varname):
457 """ Make it @cl node so it can be pushed back directly by alt+I """
444 """ Make it @cl node so it can be pushed back directly by alt+I """
458 node = add_var(varname)
445 node = add_var(varname)
459 formatted = format_for_leo(obj)
446 formatted = format_for_leo(obj)
460 if not formatted.startswith('@cl'):
447 if not formatted.startswith('@cl'):
461 formatted = '@cl\n' + formatted
448 formatted = '@cl\n' + formatted
462 node.b = formatted
449 node.b = formatted
463 node.go()
450 node.go()
464
451
465 @edit_object_in_leo.when_type(IPython.macro.Macro)
452 @edit_object_in_leo.when_type(IPython.macro.Macro)
466 def edit_macro(obj,varname):
453 def edit_macro(obj,varname):
467 bod = '_ip.defmacro("""\\\n' + obj.value + '""")'
454 bod = '_ip.defmacro("""\\\n' + obj.value + '""")'
468 node = add_var('Macro_' + varname)
455 node = add_var('Macro_' + varname)
469 node.b = bod
456 node.b = bod
470 node.go()
457 node.go()
471
458
472 def get_history(hstart = 0):
459 def get_history(hstart = 0):
473 res = []
460 res = []
474 ohist = ip.IP.output_hist
461 ohist = ip.IP.output_hist
475
462
476 for idx in range(hstart, len(ip.IP.input_hist)):
463 for idx in range(hstart, len(ip.IP.input_hist)):
477 val = ohist.get(idx,None)
464 val = ohist.get(idx,None)
478 has_output = True
465 has_output = True
479 inp = ip.IP.input_hist_raw[idx]
466 inp = ip.IP.input_hist_raw[idx]
480 if inp.strip():
467 if inp.strip():
481 res.append('In [%d]: %s' % (idx, inp))
468 res.append('In [%d]: %s' % (idx, inp))
482 if val:
469 if val:
483 res.append(pprint.pformat(val))
470 res.append(pprint.pformat(val))
484 res.append('\n')
471 res.append('\n')
485 return ''.join(res)
472 return ''.join(res)
486
473
487
474
488 def lee_f(self,s):
475 def lee_f(self,s):
489 """ Open file(s)/objects in Leo
476 """ Open file(s)/objects in Leo
490
477
491 - %lee hist -> open full session history in leo
478 - %lee hist -> open full session history in leo
492 - Takes an object. l = [1,2,"hello"]; %lee l. Alt+I in leo pushes the object back
479 - Takes an object. l = [1,2,"hello"]; %lee l. Alt+I in leo pushes the object back
493 - Takes an mglob pattern, e.g. '%lee *.cpp' or %lee 'rec:*.cpp'
480 - Takes an mglob pattern, e.g. '%lee *.cpp' or %lee 'rec:*.cpp'
494 - Takes input history indices: %lee 4 6-8 10 12-47
481 - Takes input history indices: %lee 4 6-8 10 12-47
495 """
482 """
496 import os
483 import os
497
484
498 c.beginUpdate()
499 try:
485 try:
500 if s == 'hist':
486 if s == 'hist':
501 wb.ipython_history.b = get_history()
487 wb.ipython_history.b = get_history()
502 wb.ipython_history.go()
488 wb.ipython_history.go()
503 return
489 return
504
490
505
491
506 if s and s[0].isdigit():
492 if s and s[0].isdigit():
507 # numbers; push input slices to leo
493 # numbers; push input slices to leo
508 lines = self.extract_input_slices(s.strip().split(), True)
494 lines = self.extract_input_slices(s.strip().split(), True)
509 v = add_var('stored_ipython_input')
495 v = add_var('stored_ipython_input')
510 v.b = '\n'.join(lines)
496 v.b = '\n'.join(lines)
511 return
497 return
512
498
513
499
514 # try editing the object directly
500 # try editing the object directly
515 obj = ip.user_ns.get(s, None)
501 obj = ip.user_ns.get(s, None)
516 if obj is not None:
502 if obj is not None:
517 edit_object_in_leo(obj,s)
503 edit_object_in_leo(obj,s)
518 return
504 return
519
505
520
506
521 # if it's not object, it's a file name / mglob pattern
507 # if it's not object, it's a file name / mglob pattern
522 from IPython.external import mglob
508 from IPython.external import mglob
523
509
524 files = (os.path.abspath(f) for f in mglob.expand(s))
510 files = (os.path.abspath(f) for f in mglob.expand(s))
525 for fname in files:
511 for fname in files:
526 p = g.findNodeAnywhere(c,'@auto ' + fname)
512 p = g.findNodeAnywhere(c,'@auto ' + fname)
527 if not p:
513 if not p:
528 p = c.currentPosition().insertAfter()
514 p = c.currentPosition().insertAfter()
529
515
530 p.setHeadString('@auto ' + fname)
516 p.setHeadString('@auto ' + fname)
531 if os.path.isfile(fname):
517 if os.path.isfile(fname):
532 c.setBodyString(p,open(fname).read())
518 c.setBodyString(p,open(fname).read())
533 c.selectPosition(p)
519 c.selectPosition(p)
534 print "Editing file(s), press ctrl+shift+w in Leo to write @auto nodes"
520 print "Editing file(s), press ctrl+shift+w in Leo to write @auto nodes"
535 finally:
521 finally:
536 c.endUpdate()
522 c.redraw()
537
523
538
524
539
525
540 def leoref_f(self,s):
526 def leoref_f(self,s):
541 """ Quick reference for ILeo """
527 """ Quick reference for ILeo """
542 import textwrap
528 import textwrap
543 print textwrap.dedent("""\
529 print textwrap.dedent("""\
544 %leoe file/object - open file / object in leo
530 %leoe file/object - open file / object in leo
545 wb.foo.v - eval node foo (i.e. headstring is 'foo' or '@ipy foo')
531 wb.foo.v - eval node foo (i.e. headstring is 'foo' or '@ipy foo')
546 wb.foo.v = 12 - assign to body of node foo
532 wb.foo.v = 12 - assign to body of node foo
547 wb.foo.b - read or write the body of node foo
533 wb.foo.b - read or write the body of node foo
548 wb.foo.l - body of node foo as string list
534 wb.foo.l - body of node foo as string list
549
535
550 for el in wb.foo:
536 for el in wb.foo:
551 print el.v
537 print el.v
552
538
553 """
539 """
554 )
540 )
555
541
556
542
557
543
558 def mb_f(self, arg):
544 def mb_f(self, arg):
559 """ Execute leo minibuffer commands
545 """ Execute leo minibuffer commands
560
546
561 Example:
547 Example:
562 mb save-to-file
548 mb save-to-file
563 """
549 """
564 c.executeMinibufferCommand(arg)
550 c.executeMinibufferCommand(arg)
565
551
566 def mb_completer(self,event):
552 def mb_completer(self,event):
567 """ Custom completer for minibuffer """
553 """ Custom completer for minibuffer """
568 cmd_param = event.line.split()
554 cmd_param = event.line.split()
569 if event.line.endswith(' '):
555 if event.line.endswith(' '):
570 cmd_param.append('')
556 cmd_param.append('')
571 if len(cmd_param) > 2:
557 if len(cmd_param) > 2:
572 return ip.IP.Completer.file_matches(event.symbol)
558 return ip.IP.Completer.file_matches(event.symbol)
573 cmds = c.commandsDict.keys()
559 cmds = c.commandsDict.keys()
574 cmds.sort()
560 cmds.sort()
575 return cmds
561 return cmds
576
562
577 def show_welcome():
563 def show_welcome():
578 print "------------------"
564 print "------------------"
579 print "Welcome to Leo-enabled IPython session!"
565 print "Welcome to Leo-enabled IPython session!"
580 print "Try %leoref for quick reference."
566 print "Try %leoref for quick reference."
581 import IPython.platutils
567 import IPython.platutils
582 IPython.platutils.set_term_title('ILeo')
568 IPython.platutils.set_term_title('ILeo')
583 IPython.platutils.freeze_term_title()
569 IPython.platutils.freeze_term_title()
584
570
585 def run_leo_startup_node():
571 def run_leo_startup_node():
586 p = g.findNodeAnywhere(c,'@ipy-startup')
572 p = g.findNodeAnywhere(c,'@ipy-startup')
587 if p:
573 if p:
588 print "Running @ipy-startup nodes"
574 print "Running @ipy-startup nodes"
589 for n in LeoNode(p):
575 for n in LeoNode(p):
590 push_from_leo(n)
576 push_from_leo(n)
591
577
592
578
@@ -1,1235 +1,1236 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """IPython Shell classes.
2 """IPython Shell classes.
3
3
4 All the matplotlib support code was co-developed with John Hunter,
4 All the matplotlib support code was co-developed with John Hunter,
5 matplotlib's author.
5 matplotlib's author.
6
6
7 $Id: Shell.py 3024 2008-02-07 15:34:42Z darren.dale $"""
7 $Id: Shell.py 3024 2008-02-07 15:34:42Z darren.dale $"""
8
8
9 #*****************************************************************************
9 #*****************************************************************************
10 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
10 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
11 #
11 #
12 # Distributed under the terms of the BSD License. The full license is in
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
13 # the file COPYING, distributed as part of this software.
14 #*****************************************************************************
14 #*****************************************************************************
15
15
16 from IPython import Release
16 from IPython import Release
17 __author__ = '%s <%s>' % Release.authors['Fernando']
17 __author__ = '%s <%s>' % Release.authors['Fernando']
18 __license__ = Release.license
18 __license__ = Release.license
19
19
20 # Code begins
20 # Code begins
21 # Stdlib imports
21 # Stdlib imports
22 import __builtin__
22 import __builtin__
23 import __main__
23 import __main__
24 import Queue
24 import Queue
25 import inspect
25 import inspect
26 import os
26 import os
27 import sys
27 import sys
28 import thread
28 import thread
29 import threading
29 import threading
30 import time
30 import time
31
31
32 from signal import signal, SIGINT
32 from signal import signal, SIGINT
33
33
34 try:
34 try:
35 import ctypes
35 import ctypes
36 HAS_CTYPES = True
36 HAS_CTYPES = True
37 except ImportError:
37 except ImportError:
38 HAS_CTYPES = False
38 HAS_CTYPES = False
39
39
40 # IPython imports
40 # IPython imports
41 import IPython
41 import IPython
42 from IPython import ultraTB, ipapi
42 from IPython import ultraTB, ipapi
43 from IPython.genutils import Term,warn,error,flag_calls, ask_yes_no
43 from IPython.genutils import Term,warn,error,flag_calls, ask_yes_no
44 from IPython.iplib import InteractiveShell
44 from IPython.iplib import InteractiveShell
45 from IPython.ipmaker import make_IPython
45 from IPython.ipmaker import make_IPython
46 from IPython.Magic import Magic
46 from IPython.Magic import Magic
47 from IPython.ipstruct import Struct
47 from IPython.ipstruct import Struct
48
48
49 # Globals
49 # Globals
50 # global flag to pass around information about Ctrl-C without exceptions
50 # global flag to pass around information about Ctrl-C without exceptions
51 KBINT = False
51 KBINT = False
52
52
53 # global flag to turn on/off Tk support.
53 # global flag to turn on/off Tk support.
54 USE_TK = False
54 USE_TK = False
55
55
56 # ID for the main thread, used for cross-thread exceptions
56 # ID for the main thread, used for cross-thread exceptions
57 MAIN_THREAD_ID = thread.get_ident()
57 MAIN_THREAD_ID = thread.get_ident()
58
58
59 # Tag when runcode() is active, for exception handling
59 # Tag when runcode() is active, for exception handling
60 CODE_RUN = None
60 CODE_RUN = None
61
61
62 # Default timeout for waiting for multithreaded shells (in seconds)
62 # Default timeout for waiting for multithreaded shells (in seconds)
63 GUI_TIMEOUT = 10
63 GUI_TIMEOUT = 10
64
64
65 #-----------------------------------------------------------------------------
65 #-----------------------------------------------------------------------------
66 # This class is trivial now, but I want to have it in to publish a clean
66 # This class is trivial now, but I want to have it in to publish a clean
67 # interface. Later when the internals are reorganized, code that uses this
67 # interface. Later when the internals are reorganized, code that uses this
68 # shouldn't have to change.
68 # shouldn't have to change.
69
69
70 class IPShell:
70 class IPShell:
71 """Create an IPython instance."""
71 """Create an IPython instance."""
72
72
73 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
73 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
74 debug=1,shell_class=InteractiveShell):
74 debug=1,shell_class=InteractiveShell):
75 self.IP = make_IPython(argv,user_ns=user_ns,
75 self.IP = make_IPython(argv,user_ns=user_ns,
76 user_global_ns=user_global_ns,
76 user_global_ns=user_global_ns,
77 debug=debug,shell_class=shell_class)
77 debug=debug,shell_class=shell_class)
78
78
79 def mainloop(self,sys_exit=0,banner=None):
79 def mainloop(self,sys_exit=0,banner=None):
80 self.IP.mainloop(banner)
80 self.IP.mainloop(banner)
81 if sys_exit:
81 if sys_exit:
82 sys.exit()
82 sys.exit()
83
83
84 #-----------------------------------------------------------------------------
84 #-----------------------------------------------------------------------------
85 def kill_embedded(self,parameter_s=''):
85 def kill_embedded(self,parameter_s=''):
86 """%kill_embedded : deactivate for good the current embedded IPython.
86 """%kill_embedded : deactivate for good the current embedded IPython.
87
87
88 This function (after asking for confirmation) sets an internal flag so that
88 This function (after asking for confirmation) sets an internal flag so that
89 an embedded IPython will never activate again. This is useful to
89 an embedded IPython will never activate again. This is useful to
90 permanently disable a shell that is being called inside a loop: once you've
90 permanently disable a shell that is being called inside a loop: once you've
91 figured out what you needed from it, you may then kill it and the program
91 figured out what you needed from it, you may then kill it and the program
92 will then continue to run without the interactive shell interfering again.
92 will then continue to run without the interactive shell interfering again.
93 """
93 """
94
94
95 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
95 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
96 "(y/n)? [y/N] ",'n')
96 "(y/n)? [y/N] ",'n')
97 if kill:
97 if kill:
98 self.shell.embedded_active = False
98 self.shell.embedded_active = False
99 print "This embedded IPython will not reactivate anymore once you exit."
99 print "This embedded IPython will not reactivate anymore once you exit."
100
100
101 class IPShellEmbed:
101 class IPShellEmbed:
102 """Allow embedding an IPython shell into a running program.
102 """Allow embedding an IPython shell into a running program.
103
103
104 Instances of this class are callable, with the __call__ method being an
104 Instances of this class are callable, with the __call__ method being an
105 alias to the embed() method of an InteractiveShell instance.
105 alias to the embed() method of an InteractiveShell instance.
106
106
107 Usage (see also the example-embed.py file for a running example):
107 Usage (see also the example-embed.py file for a running example):
108
108
109 ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override])
109 ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override])
110
110
111 - argv: list containing valid command-line options for IPython, as they
111 - argv: list containing valid command-line options for IPython, as they
112 would appear in sys.argv[1:].
112 would appear in sys.argv[1:].
113
113
114 For example, the following command-line options:
114 For example, the following command-line options:
115
115
116 $ ipython -prompt_in1 'Input <\\#>' -colors LightBG
116 $ ipython -prompt_in1 'Input <\\#>' -colors LightBG
117
117
118 would be passed in the argv list as:
118 would be passed in the argv list as:
119
119
120 ['-prompt_in1','Input <\\#>','-colors','LightBG']
120 ['-prompt_in1','Input <\\#>','-colors','LightBG']
121
121
122 - banner: string which gets printed every time the interpreter starts.
122 - banner: string which gets printed every time the interpreter starts.
123
123
124 - exit_msg: string which gets printed every time the interpreter exits.
124 - exit_msg: string which gets printed every time the interpreter exits.
125
125
126 - rc_override: a dict or Struct of configuration options such as those
126 - rc_override: a dict or Struct of configuration options such as those
127 used by IPython. These options are read from your ~/.ipython/ipythonrc
127 used by IPython. These options are read from your ~/.ipython/ipythonrc
128 file when the Shell object is created. Passing an explicit rc_override
128 file when the Shell object is created. Passing an explicit rc_override
129 dict with any options you want allows you to override those values at
129 dict with any options you want allows you to override those values at
130 creation time without having to modify the file. This way you can create
130 creation time without having to modify the file. This way you can create
131 embeddable instances configured in any way you want without editing any
131 embeddable instances configured in any way you want without editing any
132 global files (thus keeping your interactive IPython configuration
132 global files (thus keeping your interactive IPython configuration
133 unchanged).
133 unchanged).
134
134
135 Then the ipshell instance can be called anywhere inside your code:
135 Then the ipshell instance can be called anywhere inside your code:
136
136
137 ipshell(header='') -> Opens up an IPython shell.
137 ipshell(header='') -> Opens up an IPython shell.
138
138
139 - header: string printed by the IPython shell upon startup. This can let
139 - header: string printed by the IPython shell upon startup. This can let
140 you know where in your code you are when dropping into the shell. Note
140 you know where in your code you are when dropping into the shell. Note
141 that 'banner' gets prepended to all calls, so header is used for
141 that 'banner' gets prepended to all calls, so header is used for
142 location-specific information.
142 location-specific information.
143
143
144 For more details, see the __call__ method below.
144 For more details, see the __call__ method below.
145
145
146 When the IPython shell is exited with Ctrl-D, normal program execution
146 When the IPython shell is exited with Ctrl-D, normal program execution
147 resumes.
147 resumes.
148
148
149 This functionality was inspired by a posting on comp.lang.python by cmkl
149 This functionality was inspired by a posting on comp.lang.python by cmkl
150 <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and
150 <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and
151 by the IDL stop/continue commands."""
151 by the IDL stop/continue commands."""
152
152
153 def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None,
153 def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None,
154 user_ns=None):
154 user_ns=None):
155 """Note that argv here is a string, NOT a list."""
155 """Note that argv here is a string, NOT a list."""
156 self.set_banner(banner)
156 self.set_banner(banner)
157 self.set_exit_msg(exit_msg)
157 self.set_exit_msg(exit_msg)
158 self.set_dummy_mode(0)
158 self.set_dummy_mode(0)
159
159
160 # sys.displayhook is a global, we need to save the user's original
160 # sys.displayhook is a global, we need to save the user's original
161 # Don't rely on __displayhook__, as the user may have changed that.
161 # Don't rely on __displayhook__, as the user may have changed that.
162 self.sys_displayhook_ori = sys.displayhook
162 self.sys_displayhook_ori = sys.displayhook
163
163
164 # save readline completer status
164 # save readline completer status
165 try:
165 try:
166 #print 'Save completer',sys.ipcompleter # dbg
166 #print 'Save completer',sys.ipcompleter # dbg
167 self.sys_ipcompleter_ori = sys.ipcompleter
167 self.sys_ipcompleter_ori = sys.ipcompleter
168 except:
168 except:
169 pass # not nested with IPython
169 pass # not nested with IPython
170
170
171 self.IP = make_IPython(argv,rc_override=rc_override,
171 self.IP = make_IPython(argv,rc_override=rc_override,
172 embedded=True,
172 embedded=True,
173 user_ns=user_ns)
173 user_ns=user_ns)
174
174
175 ip = ipapi.IPApi(self.IP)
175 ip = ipapi.IPApi(self.IP)
176 ip.expose_magic("kill_embedded",kill_embedded)
176 ip.expose_magic("kill_embedded",kill_embedded)
177
177
178 # copy our own displayhook also
178 # copy our own displayhook also
179 self.sys_displayhook_embed = sys.displayhook
179 self.sys_displayhook_embed = sys.displayhook
180 # and leave the system's display hook clean
180 # and leave the system's display hook clean
181 sys.displayhook = self.sys_displayhook_ori
181 sys.displayhook = self.sys_displayhook_ori
182 # don't use the ipython crash handler so that user exceptions aren't
182 # don't use the ipython crash handler so that user exceptions aren't
183 # trapped
183 # trapped
184 sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors,
184 sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors,
185 mode = self.IP.rc.xmode,
185 mode = self.IP.rc.xmode,
186 call_pdb = self.IP.rc.pdb)
186 call_pdb = self.IP.rc.pdb)
187 self.restore_system_completer()
187 self.restore_system_completer()
188
188
189 def restore_system_completer(self):
189 def restore_system_completer(self):
190 """Restores the readline completer which was in place.
190 """Restores the readline completer which was in place.
191
191
192 This allows embedded IPython within IPython not to disrupt the
192 This allows embedded IPython within IPython not to disrupt the
193 parent's completion.
193 parent's completion.
194 """
194 """
195
195
196 try:
196 try:
197 self.IP.readline.set_completer(self.sys_ipcompleter_ori)
197 self.IP.readline.set_completer(self.sys_ipcompleter_ori)
198 sys.ipcompleter = self.sys_ipcompleter_ori
198 sys.ipcompleter = self.sys_ipcompleter_ori
199 except:
199 except:
200 pass
200 pass
201
201
202 def __call__(self,header='',local_ns=None,global_ns=None,dummy=None):
202 def __call__(self,header='',local_ns=None,global_ns=None,dummy=None):
203 """Activate the interactive interpreter.
203 """Activate the interactive interpreter.
204
204
205 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
205 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
206 the interpreter shell with the given local and global namespaces, and
206 the interpreter shell with the given local and global namespaces, and
207 optionally print a header string at startup.
207 optionally print a header string at startup.
208
208
209 The shell can be globally activated/deactivated using the
209 The shell can be globally activated/deactivated using the
210 set/get_dummy_mode methods. This allows you to turn off a shell used
210 set/get_dummy_mode methods. This allows you to turn off a shell used
211 for debugging globally.
211 for debugging globally.
212
212
213 However, *each* time you call the shell you can override the current
213 However, *each* time you call the shell you can override the current
214 state of dummy_mode with the optional keyword parameter 'dummy'. For
214 state of dummy_mode with the optional keyword parameter 'dummy'. For
215 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
215 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
216 can still have a specific call work by making it as IPShell(dummy=0).
216 can still have a specific call work by making it as IPShell(dummy=0).
217
217
218 The optional keyword parameter dummy controls whether the call
218 The optional keyword parameter dummy controls whether the call
219 actually does anything. """
219 actually does anything. """
220
220
221 # If the user has turned it off, go away
221 # If the user has turned it off, go away
222 if not self.IP.embedded_active:
222 if not self.IP.embedded_active:
223 return
223 return
224
224
225 # Normal exits from interactive mode set this flag, so the shell can't
225 # Normal exits from interactive mode set this flag, so the shell can't
226 # re-enter (it checks this variable at the start of interactive mode).
226 # re-enter (it checks this variable at the start of interactive mode).
227 self.IP.exit_now = False
227 self.IP.exit_now = False
228
228
229 # Allow the dummy parameter to override the global __dummy_mode
229 # Allow the dummy parameter to override the global __dummy_mode
230 if dummy or (dummy != 0 and self.__dummy_mode):
230 if dummy or (dummy != 0 and self.__dummy_mode):
231 return
231 return
232
232
233 # Set global subsystems (display,completions) to our values
233 # Set global subsystems (display,completions) to our values
234 sys.displayhook = self.sys_displayhook_embed
234 sys.displayhook = self.sys_displayhook_embed
235 if self.IP.has_readline:
235 if self.IP.has_readline:
236 self.IP.set_completer()
236 self.IP.set_completer()
237
237
238 if self.banner and header:
238 if self.banner and header:
239 format = '%s\n%s\n'
239 format = '%s\n%s\n'
240 else:
240 else:
241 format = '%s%s\n'
241 format = '%s%s\n'
242 banner = format % (self.banner,header)
242 banner = format % (self.banner,header)
243
243
244 # Call the embedding code with a stack depth of 1 so it can skip over
244 # Call the embedding code with a stack depth of 1 so it can skip over
245 # our call and get the original caller's namespaces.
245 # our call and get the original caller's namespaces.
246 self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1)
246 self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1)
247
247
248 if self.exit_msg:
248 if self.exit_msg:
249 print self.exit_msg
249 print self.exit_msg
250
250
251 # Restore global systems (display, completion)
251 # Restore global systems (display, completion)
252 sys.displayhook = self.sys_displayhook_ori
252 sys.displayhook = self.sys_displayhook_ori
253 self.restore_system_completer()
253 self.restore_system_completer()
254
254
255 def set_dummy_mode(self,dummy):
255 def set_dummy_mode(self,dummy):
256 """Sets the embeddable shell's dummy mode parameter.
256 """Sets the embeddable shell's dummy mode parameter.
257
257
258 set_dummy_mode(dummy): dummy = 0 or 1.
258 set_dummy_mode(dummy): dummy = 0 or 1.
259
259
260 This parameter is persistent and makes calls to the embeddable shell
260 This parameter is persistent and makes calls to the embeddable shell
261 silently return without performing any action. This allows you to
261 silently return without performing any action. This allows you to
262 globally activate or deactivate a shell you're using with a single call.
262 globally activate or deactivate a shell you're using with a single call.
263
263
264 If you need to manually"""
264 If you need to manually"""
265
265
266 if dummy not in [0,1,False,True]:
266 if dummy not in [0,1,False,True]:
267 raise ValueError,'dummy parameter must be boolean'
267 raise ValueError,'dummy parameter must be boolean'
268 self.__dummy_mode = dummy
268 self.__dummy_mode = dummy
269
269
270 def get_dummy_mode(self):
270 def get_dummy_mode(self):
271 """Return the current value of the dummy mode parameter.
271 """Return the current value of the dummy mode parameter.
272 """
272 """
273 return self.__dummy_mode
273 return self.__dummy_mode
274
274
275 def set_banner(self,banner):
275 def set_banner(self,banner):
276 """Sets the global banner.
276 """Sets the global banner.
277
277
278 This banner gets prepended to every header printed when the shell
278 This banner gets prepended to every header printed when the shell
279 instance is called."""
279 instance is called."""
280
280
281 self.banner = banner
281 self.banner = banner
282
282
283 def set_exit_msg(self,exit_msg):
283 def set_exit_msg(self,exit_msg):
284 """Sets the global exit_msg.
284 """Sets the global exit_msg.
285
285
286 This exit message gets printed upon exiting every time the embedded
286 This exit message gets printed upon exiting every time the embedded
287 shell is called. It is None by default. """
287 shell is called. It is None by default. """
288
288
289 self.exit_msg = exit_msg
289 self.exit_msg = exit_msg
290
290
291 #-----------------------------------------------------------------------------
291 #-----------------------------------------------------------------------------
292 if HAS_CTYPES:
292 if HAS_CTYPES:
293 # Add async exception support. Trick taken from:
293 # Add async exception support. Trick taken from:
294 # http://sebulba.wikispaces.com/recipe+thread2
294 # http://sebulba.wikispaces.com/recipe+thread2
295 def _async_raise(tid, exctype):
295 def _async_raise(tid, exctype):
296 """raises the exception, performs cleanup if needed"""
296 """raises the exception, performs cleanup if needed"""
297 if not inspect.isclass(exctype):
297 if not inspect.isclass(exctype):
298 raise TypeError("Only types can be raised (not instances)")
298 raise TypeError("Only types can be raised (not instances)")
299 res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid,
299 res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid,
300 ctypes.py_object(exctype))
300 ctypes.py_object(exctype))
301 if res == 0:
301 if res == 0:
302 raise ValueError("invalid thread id")
302 raise ValueError("invalid thread id")
303 elif res != 1:
303 elif res != 1:
304 # """if it returns a number greater than one, you're in trouble,
304 # """if it returns a number greater than one, you're in trouble,
305 # and you should call it again with exc=NULL to revert the effect"""
305 # and you should call it again with exc=NULL to revert the effect"""
306 ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
306 ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
307 raise SystemError("PyThreadState_SetAsyncExc failed")
307 raise SystemError("PyThreadState_SetAsyncExc failed")
308
308
309 def sigint_handler (signum,stack_frame):
309 def sigint_handler (signum,stack_frame):
310 """Sigint handler for threaded apps.
310 """Sigint handler for threaded apps.
311
311
312 This is a horrible hack to pass information about SIGINT _without_
312 This is a horrible hack to pass information about SIGINT _without_
313 using exceptions, since I haven't been able to properly manage
313 using exceptions, since I haven't been able to properly manage
314 cross-thread exceptions in GTK/WX. In fact, I don't think it can be
314 cross-thread exceptions in GTK/WX. In fact, I don't think it can be
315 done (or at least that's my understanding from a c.l.py thread where
315 done (or at least that's my understanding from a c.l.py thread where
316 this was discussed)."""
316 this was discussed)."""
317
317
318 global KBINT
318 global KBINT
319
319
320 if CODE_RUN:
320 if CODE_RUN:
321 _async_raise(MAIN_THREAD_ID,KeyboardInterrupt)
321 _async_raise(MAIN_THREAD_ID,KeyboardInterrupt)
322 else:
322 else:
323 KBINT = True
323 KBINT = True
324 print '\nKeyboardInterrupt - Press <Enter> to continue.',
324 print '\nKeyboardInterrupt - Press <Enter> to continue.',
325 Term.cout.flush()
325 Term.cout.flush()
326
326
327 else:
327 else:
328 def sigint_handler (signum,stack_frame):
328 def sigint_handler (signum,stack_frame):
329 """Sigint handler for threaded apps.
329 """Sigint handler for threaded apps.
330
330
331 This is a horrible hack to pass information about SIGINT _without_
331 This is a horrible hack to pass information about SIGINT _without_
332 using exceptions, since I haven't been able to properly manage
332 using exceptions, since I haven't been able to properly manage
333 cross-thread exceptions in GTK/WX. In fact, I don't think it can be
333 cross-thread exceptions in GTK/WX. In fact, I don't think it can be
334 done (or at least that's my understanding from a c.l.py thread where
334 done (or at least that's my understanding from a c.l.py thread where
335 this was discussed)."""
335 this was discussed)."""
336
336
337 global KBINT
337 global KBINT
338
338
339 print '\nKeyboardInterrupt - Press <Enter> to continue.',
339 print '\nKeyboardInterrupt - Press <Enter> to continue.',
340 Term.cout.flush()
340 Term.cout.flush()
341 # Set global flag so that runsource can know that Ctrl-C was hit
341 # Set global flag so that runsource can know that Ctrl-C was hit
342 KBINT = True
342 KBINT = True
343
343
344
344
345 class MTInteractiveShell(InteractiveShell):
345 class MTInteractiveShell(InteractiveShell):
346 """Simple multi-threaded shell."""
346 """Simple multi-threaded shell."""
347
347
348 # Threading strategy taken from:
348 # Threading strategy taken from:
349 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian
349 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian
350 # McErlean and John Finlay. Modified with corrections by Antoon Pardon,
350 # McErlean and John Finlay. Modified with corrections by Antoon Pardon,
351 # from the pygtk mailing list, to avoid lockups with system calls.
351 # from the pygtk mailing list, to avoid lockups with system calls.
352
352
353 # class attribute to indicate whether the class supports threads or not.
353 # class attribute to indicate whether the class supports threads or not.
354 # Subclasses with thread support should override this as needed.
354 # Subclasses with thread support should override this as needed.
355 isthreaded = True
355 isthreaded = True
356
356
357 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
357 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
358 user_ns=None,user_global_ns=None,banner2='',
358 user_ns=None,user_global_ns=None,banner2='',
359 gui_timeout=GUI_TIMEOUT,**kw):
359 gui_timeout=GUI_TIMEOUT,**kw):
360 """Similar to the normal InteractiveShell, but with threading control"""
360 """Similar to the normal InteractiveShell, but with threading control"""
361
361
362 InteractiveShell.__init__(self,name,usage,rc,user_ns,
362 InteractiveShell.__init__(self,name,usage,rc,user_ns,
363 user_global_ns,banner2)
363 user_global_ns,banner2)
364
364
365 # Timeout we wait for GUI thread
365 # Timeout we wait for GUI thread
366 self.gui_timeout = gui_timeout
366 self.gui_timeout = gui_timeout
367
367
368 # A queue to hold the code to be executed.
368 # A queue to hold the code to be executed.
369 self.code_queue = Queue.Queue()
369 self.code_queue = Queue.Queue()
370
370
371 # Stuff to do at closing time
371 # Stuff to do at closing time
372 self._kill = None
372 self._kill = None
373 on_kill = kw.get('on_kill', [])
373 on_kill = kw.get('on_kill', [])
374 # Check that all things to kill are callable:
374 # Check that all things to kill are callable:
375 for t in on_kill:
375 for t in on_kill:
376 if not callable(t):
376 if not callable(t):
377 raise TypeError,'on_kill must be a list of callables'
377 raise TypeError,'on_kill must be a list of callables'
378 self.on_kill = on_kill
378 self.on_kill = on_kill
379 # thread identity of the "worker thread" (that may execute code directly)
379 # thread identity of the "worker thread" (that may execute code directly)
380 self.worker_ident = None
380 self.worker_ident = None
381
381
382 def runsource(self, source, filename="<input>", symbol="single"):
382 def runsource(self, source, filename="<input>", symbol="single"):
383 """Compile and run some source in the interpreter.
383 """Compile and run some source in the interpreter.
384
384
385 Modified version of code.py's runsource(), to handle threading issues.
385 Modified version of code.py's runsource(), to handle threading issues.
386 See the original for full docstring details."""
386 See the original for full docstring details."""
387
387
388 global KBINT
388 global KBINT
389
389
390 # If Ctrl-C was typed, we reset the flag and return right away
390 # If Ctrl-C was typed, we reset the flag and return right away
391 if KBINT:
391 if KBINT:
392 KBINT = False
392 KBINT = False
393 return False
393 return False
394
394
395 if self._kill:
395 if self._kill:
396 # can't queue new code if we are being killed
396 # can't queue new code if we are being killed
397 return True
397 return True
398
398
399 try:
399 try:
400 code = self.compile(source, filename, symbol)
400 code = self.compile(source, filename, symbol)
401 except (OverflowError, SyntaxError, ValueError):
401 except (OverflowError, SyntaxError, ValueError):
402 # Case 1
402 # Case 1
403 self.showsyntaxerror(filename)
403 self.showsyntaxerror(filename)
404 return False
404 return False
405
405
406 if code is None:
406 if code is None:
407 # Case 2
407 # Case 2
408 return True
408 return True
409
409
410 # shortcut - if we are in worker thread, or the worker thread is not
410 # shortcut - if we are in worker thread, or the worker thread is not
411 # running, execute directly (to allow recursion and prevent deadlock if
411 # running, execute directly (to allow recursion and prevent deadlock if
412 # code is run early in IPython construction)
412 # code is run early in IPython construction)
413
413
414 if (self.worker_ident is None
414 if (self.worker_ident is None
415 or self.worker_ident == thread.get_ident() ):
415 or self.worker_ident == thread.get_ident() ):
416 InteractiveShell.runcode(self,code)
416 InteractiveShell.runcode(self,code)
417 return
417 return
418
418
419 # Case 3
419 # Case 3
420 # Store code in queue, so the execution thread can handle it.
420 # Store code in queue, so the execution thread can handle it.
421
421
422 completed_ev, received_ev = threading.Event(), threading.Event()
422 completed_ev, received_ev = threading.Event(), threading.Event()
423
423
424 self.code_queue.put((code,completed_ev, received_ev))
424 self.code_queue.put((code,completed_ev, received_ev))
425 # first make sure the message was received, with timeout
425 # first make sure the message was received, with timeout
426 received_ev.wait(self.gui_timeout)
426 received_ev.wait(self.gui_timeout)
427 if not received_ev.isSet():
427 if not received_ev.isSet():
428 # the mainloop is dead, start executing code directly
428 # the mainloop is dead, start executing code directly
429 print "Warning: Timeout for mainloop thread exceeded"
429 print "Warning: Timeout for mainloop thread exceeded"
430 print "switching to nonthreaded mode (until mainloop wakes up again)"
430 print "switching to nonthreaded mode (until mainloop wakes up again)"
431 self.worker_ident = None
431 self.worker_ident = None
432 else:
432 else:
433 completed_ev.wait()
433 completed_ev.wait()
434 return False
434 return False
435
435
436 def runcode(self):
436 def runcode(self):
437 """Execute a code object.
437 """Execute a code object.
438
438
439 Multithreaded wrapper around IPython's runcode()."""
439 Multithreaded wrapper around IPython's runcode()."""
440
440
441 global CODE_RUN
441 global CODE_RUN
442
442
443 # we are in worker thread, stash out the id for runsource()
443 # we are in worker thread, stash out the id for runsource()
444 self.worker_ident = thread.get_ident()
444 self.worker_ident = thread.get_ident()
445
445
446 if self._kill:
446 if self._kill:
447 print >>Term.cout, 'Closing threads...',
447 print >>Term.cout, 'Closing threads...',
448 Term.cout.flush()
448 Term.cout.flush()
449 for tokill in self.on_kill:
449 for tokill in self.on_kill:
450 tokill()
450 tokill()
451 print >>Term.cout, 'Done.'
451 print >>Term.cout, 'Done.'
452 # allow kill() to return
452 # allow kill() to return
453 self._kill.set()
453 self._kill.set()
454 return True
454 return True
455
455
456 # Install sigint handler. We do it every time to ensure that if user
456 # Install sigint handler. We do it every time to ensure that if user
457 # code modifies it, we restore our own handling.
457 # code modifies it, we restore our own handling.
458 try:
458 try:
459 signal(SIGINT,sigint_handler)
459 signal(SIGINT,sigint_handler)
460 except SystemError:
460 except SystemError:
461 # This happens under Windows, which seems to have all sorts
461 # This happens under Windows, which seems to have all sorts
462 # of problems with signal handling. Oh well...
462 # of problems with signal handling. Oh well...
463 pass
463 pass
464
464
465 # Flush queue of pending code by calling the run methood of the parent
465 # Flush queue of pending code by calling the run methood of the parent
466 # class with all items which may be in the queue.
466 # class with all items which may be in the queue.
467 code_to_run = None
467 code_to_run = None
468 while 1:
468 while 1:
469 try:
469 try:
470 code_to_run, completed_ev, received_ev = self.code_queue.get_nowait()
470 code_to_run, completed_ev, received_ev = self.code_queue.get_nowait()
471 except Queue.Empty:
471 except Queue.Empty:
472 break
472 break
473 received_ev.set()
473 received_ev.set()
474
474
475 # Exceptions need to be raised differently depending on which
475 # Exceptions need to be raised differently depending on which
476 # thread is active. This convoluted try/except is only there to
476 # thread is active. This convoluted try/except is only there to
477 # protect against asynchronous exceptions, to ensure that a KBINT
477 # protect against asynchronous exceptions, to ensure that a KBINT
478 # at the wrong time doesn't deadlock everything. The global
478 # at the wrong time doesn't deadlock everything. The global
479 # CODE_TO_RUN is set to true/false as close as possible to the
479 # CODE_TO_RUN is set to true/false as close as possible to the
480 # runcode() call, so that the KBINT handler is correctly informed.
480 # runcode() call, so that the KBINT handler is correctly informed.
481 try:
481 try:
482 try:
482 try:
483 CODE_RUN = True
483 CODE_RUN = True
484 InteractiveShell.runcode(self,code_to_run)
484 InteractiveShell.runcode(self,code_to_run)
485 except KeyboardInterrupt:
485 except KeyboardInterrupt:
486 print "Keyboard interrupted in mainloop"
486 print "Keyboard interrupted in mainloop"
487 while not self.code_queue.empty():
487 while not self.code_queue.empty():
488 code, ev1,ev2 = self.code_queue.get_nowait()
488 code, ev1,ev2 = self.code_queue.get_nowait()
489 ev1.set()
489 ev1.set()
490 ev2.set()
490 ev2.set()
491 break
491 break
492 finally:
492 finally:
493 CODE_RUN = False
493 CODE_RUN = False
494 # allow runsource() return from wait
494 # allow runsource() return from wait
495 completed_ev.set()
495 completed_ev.set()
496
496
497
497
498 # This MUST return true for gtk threading to work
498 # This MUST return true for gtk threading to work
499 return True
499 return True
500
500
501 def kill(self):
501 def kill(self):
502 """Kill the thread, returning when it has been shut down."""
502 """Kill the thread, returning when it has been shut down."""
503 self._kill = threading.Event()
503 self._kill = threading.Event()
504 self._kill.wait()
504 self._kill.wait()
505
505
506 class MatplotlibShellBase:
506 class MatplotlibShellBase:
507 """Mixin class to provide the necessary modifications to regular IPython
507 """Mixin class to provide the necessary modifications to regular IPython
508 shell classes for matplotlib support.
508 shell classes for matplotlib support.
509
509
510 Given Python's MRO, this should be used as the FIRST class in the
510 Given Python's MRO, this should be used as the FIRST class in the
511 inheritance hierarchy, so that it overrides the relevant methods."""
511 inheritance hierarchy, so that it overrides the relevant methods."""
512
512
513 def _matplotlib_config(self,name,user_ns):
513 def _matplotlib_config(self,name,user_ns,user_global_ns=None):
514 """Return items needed to setup the user's shell with matplotlib"""
514 """Return items needed to setup the user's shell with matplotlib"""
515
515
516 # Initialize matplotlib to interactive mode always
516 # Initialize matplotlib to interactive mode always
517 import matplotlib
517 import matplotlib
518 from matplotlib import backends
518 from matplotlib import backends
519 matplotlib.interactive(True)
519 matplotlib.interactive(True)
520
520
521 def use(arg):
521 def use(arg):
522 """IPython wrapper for matplotlib's backend switcher.
522 """IPython wrapper for matplotlib's backend switcher.
523
523
524 In interactive use, we can not allow switching to a different
524 In interactive use, we can not allow switching to a different
525 interactive backend, since thread conflicts will most likely crash
525 interactive backend, since thread conflicts will most likely crash
526 the python interpreter. This routine does a safety check first,
526 the python interpreter. This routine does a safety check first,
527 and refuses to perform a dangerous switch. It still allows
527 and refuses to perform a dangerous switch. It still allows
528 switching to non-interactive backends."""
528 switching to non-interactive backends."""
529
529
530 if arg in backends.interactive_bk and arg != self.mpl_backend:
530 if arg in backends.interactive_bk and arg != self.mpl_backend:
531 m=('invalid matplotlib backend switch.\n'
531 m=('invalid matplotlib backend switch.\n'
532 'This script attempted to switch to the interactive '
532 'This script attempted to switch to the interactive '
533 'backend: `%s`\n'
533 'backend: `%s`\n'
534 'Your current choice of interactive backend is: `%s`\n\n'
534 'Your current choice of interactive backend is: `%s`\n\n'
535 'Switching interactive matplotlib backends at runtime\n'
535 'Switching interactive matplotlib backends at runtime\n'
536 'would crash the python interpreter, '
536 'would crash the python interpreter, '
537 'and IPython has blocked it.\n\n'
537 'and IPython has blocked it.\n\n'
538 'You need to either change your choice of matplotlib backend\n'
538 'You need to either change your choice of matplotlib backend\n'
539 'by editing your .matplotlibrc file, or run this script as a \n'
539 'by editing your .matplotlibrc file, or run this script as a \n'
540 'standalone file from the command line, not using IPython.\n' %
540 'standalone file from the command line, not using IPython.\n' %
541 (arg,self.mpl_backend) )
541 (arg,self.mpl_backend) )
542 raise RuntimeError, m
542 raise RuntimeError, m
543 else:
543 else:
544 self.mpl_use(arg)
544 self.mpl_use(arg)
545 self.mpl_use._called = True
545 self.mpl_use._called = True
546
546
547 self.matplotlib = matplotlib
547 self.matplotlib = matplotlib
548 self.mpl_backend = matplotlib.rcParams['backend']
548 self.mpl_backend = matplotlib.rcParams['backend']
549
549
550 # we also need to block switching of interactive backends by use()
550 # we also need to block switching of interactive backends by use()
551 self.mpl_use = matplotlib.use
551 self.mpl_use = matplotlib.use
552 self.mpl_use._called = False
552 self.mpl_use._called = False
553 # overwrite the original matplotlib.use with our wrapper
553 # overwrite the original matplotlib.use with our wrapper
554 matplotlib.use = use
554 matplotlib.use = use
555
555
556 # This must be imported last in the matplotlib series, after
556 # This must be imported last in the matplotlib series, after
557 # backend/interactivity choices have been made
557 # backend/interactivity choices have been made
558 import matplotlib.pylab as pylab
558 import matplotlib.pylab as pylab
559 self.pylab = pylab
559 self.pylab = pylab
560
560
561 self.pylab.show._needmain = False
561 self.pylab.show._needmain = False
562 # We need to detect at runtime whether show() is called by the user.
562 # We need to detect at runtime whether show() is called by the user.
563 # For this, we wrap it into a decorator which adds a 'called' flag.
563 # For this, we wrap it into a decorator which adds a 'called' flag.
564 self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive)
564 self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive)
565
565
566 # Build a user namespace initialized with matplotlib/matlab features.
566 # Build a user namespace initialized with matplotlib/matlab features.
567 user_ns = IPython.ipapi.make_user_ns(user_ns)
567 user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns,
568 user_global_ns)
568
569
569 # Import numpy as np/pyplot as plt are conventions we're trying to
570 # Import numpy as np/pyplot as plt are conventions we're trying to
570 # somewhat standardize on. Making them available to users by default
571 # somewhat standardize on. Making them available to users by default
571 # will greatly help this.
572 # will greatly help this.
572 exec ("import numpy\n"
573 exec ("import numpy\n"
573 "import numpy as np\n"
574 "import numpy as np\n"
574 "import matplotlib\n"
575 "import matplotlib\n"
575 "import matplotlib.pylab as pylab\n"
576 "import matplotlib.pylab as pylab\n"
576 "try:\n"
577 "try:\n"
577 " import matplotlib.pyplot as plt\n"
578 " import matplotlib.pyplot as plt\n"
578 "except ImportError:\n"
579 "except ImportError:\n"
579 " pass\n"
580 " pass\n"
580 ) in user_ns
581 ) in user_ns
581
582
582 # Build matplotlib info banner
583 # Build matplotlib info banner
583 b="""
584 b="""
584 Welcome to pylab, a matplotlib-based Python environment.
585 Welcome to pylab, a matplotlib-based Python environment.
585 For more information, type 'help(pylab)'.
586 For more information, type 'help(pylab)'.
586 """
587 """
587 return user_ns,b
588 return user_ns,user_global_ns,b
588
589
589 def mplot_exec(self,fname,*where,**kw):
590 def mplot_exec(self,fname,*where,**kw):
590 """Execute a matplotlib script.
591 """Execute a matplotlib script.
591
592
592 This is a call to execfile(), but wrapped in safeties to properly
593 This is a call to execfile(), but wrapped in safeties to properly
593 handle interactive rendering and backend switching."""
594 handle interactive rendering and backend switching."""
594
595
595 #print '*** Matplotlib runner ***' # dbg
596 #print '*** Matplotlib runner ***' # dbg
596 # turn off rendering until end of script
597 # turn off rendering until end of script
597 isInteractive = self.matplotlib.rcParams['interactive']
598 isInteractive = self.matplotlib.rcParams['interactive']
598 self.matplotlib.interactive(False)
599 self.matplotlib.interactive(False)
599 self.safe_execfile(fname,*where,**kw)
600 self.safe_execfile(fname,*where,**kw)
600 self.matplotlib.interactive(isInteractive)
601 self.matplotlib.interactive(isInteractive)
601 # make rendering call now, if the user tried to do it
602 # make rendering call now, if the user tried to do it
602 if self.pylab.draw_if_interactive.called:
603 if self.pylab.draw_if_interactive.called:
603 self.pylab.draw()
604 self.pylab.draw()
604 self.pylab.draw_if_interactive.called = False
605 self.pylab.draw_if_interactive.called = False
605
606
606 # if a backend switch was performed, reverse it now
607 # if a backend switch was performed, reverse it now
607 if self.mpl_use._called:
608 if self.mpl_use._called:
608 self.matplotlib.rcParams['backend'] = self.mpl_backend
609 self.matplotlib.rcParams['backend'] = self.mpl_backend
609
610
610 def magic_run(self,parameter_s=''):
611 def magic_run(self,parameter_s=''):
611 Magic.magic_run(self,parameter_s,runner=self.mplot_exec)
612 Magic.magic_run(self,parameter_s,runner=self.mplot_exec)
612
613
613 # Fix the docstring so users see the original as well
614 # Fix the docstring so users see the original as well
614 magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__,
615 magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__,
615 "\n *** Modified %run for Matplotlib,"
616 "\n *** Modified %run for Matplotlib,"
616 " with proper interactive handling ***")
617 " with proper interactive handling ***")
617
618
618 # Now we provide 2 versions of a matplotlib-aware IPython base shells, single
619 # Now we provide 2 versions of a matplotlib-aware IPython base shells, single
619 # and multithreaded. Note that these are meant for internal use, the IPShell*
620 # and multithreaded. Note that these are meant for internal use, the IPShell*
620 # classes below are the ones meant for public consumption.
621 # classes below are the ones meant for public consumption.
621
622
622 class MatplotlibShell(MatplotlibShellBase,InteractiveShell):
623 class MatplotlibShell(MatplotlibShellBase,InteractiveShell):
623 """Single-threaded shell with matplotlib support."""
624 """Single-threaded shell with matplotlib support."""
624
625
625 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
626 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
626 user_ns=None,user_global_ns=None,**kw):
627 user_ns=None,user_global_ns=None,**kw):
627 user_ns,b2 = self._matplotlib_config(name,user_ns)
628 user_ns,user_global_ns,b2 = self._matplotlib_config(name,user_ns,user_global_ns)
628 InteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
629 InteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
629 banner2=b2,**kw)
630 banner2=b2,**kw)
630
631
631 class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell):
632 class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell):
632 """Multi-threaded shell with matplotlib support."""
633 """Multi-threaded shell with matplotlib support."""
633
634
634 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
635 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
635 user_ns=None,user_global_ns=None, **kw):
636 user_ns=None,user_global_ns=None, **kw):
636 user_ns,b2 = self._matplotlib_config(name,user_ns)
637 user_ns,b2 = self._matplotlib_config(name,user_ns)
637 MTInteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
638 MTInteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
638 banner2=b2,**kw)
639 banner2=b2,**kw)
639
640
640 #-----------------------------------------------------------------------------
641 #-----------------------------------------------------------------------------
641 # Utility functions for the different GUI enabled IPShell* classes.
642 # Utility functions for the different GUI enabled IPShell* classes.
642
643
643 def get_tk():
644 def get_tk():
644 """Tries to import Tkinter and returns a withdrawn Tkinter root
645 """Tries to import Tkinter and returns a withdrawn Tkinter root
645 window. If Tkinter is already imported or not available, this
646 window. If Tkinter is already imported or not available, this
646 returns None. This function calls `hijack_tk` underneath.
647 returns None. This function calls `hijack_tk` underneath.
647 """
648 """
648 if not USE_TK or sys.modules.has_key('Tkinter'):
649 if not USE_TK or sys.modules.has_key('Tkinter'):
649 return None
650 return None
650 else:
651 else:
651 try:
652 try:
652 import Tkinter
653 import Tkinter
653 except ImportError:
654 except ImportError:
654 return None
655 return None
655 else:
656 else:
656 hijack_tk()
657 hijack_tk()
657 r = Tkinter.Tk()
658 r = Tkinter.Tk()
658 r.withdraw()
659 r.withdraw()
659 return r
660 return r
660
661
661 def hijack_tk():
662 def hijack_tk():
662 """Modifies Tkinter's mainloop with a dummy so when a module calls
663 """Modifies Tkinter's mainloop with a dummy so when a module calls
663 mainloop, it does not block.
664 mainloop, it does not block.
664
665
665 """
666 """
666 def misc_mainloop(self, n=0):
667 def misc_mainloop(self, n=0):
667 pass
668 pass
668 def tkinter_mainloop(n=0):
669 def tkinter_mainloop(n=0):
669 pass
670 pass
670
671
671 import Tkinter
672 import Tkinter
672 Tkinter.Misc.mainloop = misc_mainloop
673 Tkinter.Misc.mainloop = misc_mainloop
673 Tkinter.mainloop = tkinter_mainloop
674 Tkinter.mainloop = tkinter_mainloop
674
675
675 def update_tk(tk):
676 def update_tk(tk):
676 """Updates the Tkinter event loop. This is typically called from
677 """Updates the Tkinter event loop. This is typically called from
677 the respective WX or GTK mainloops.
678 the respective WX or GTK mainloops.
678 """
679 """
679 if tk:
680 if tk:
680 tk.update()
681 tk.update()
681
682
682 def hijack_wx():
683 def hijack_wx():
683 """Modifies wxPython's MainLoop with a dummy so user code does not
684 """Modifies wxPython's MainLoop with a dummy so user code does not
684 block IPython. The hijacked mainloop function is returned.
685 block IPython. The hijacked mainloop function is returned.
685 """
686 """
686 def dummy_mainloop(*args, **kw):
687 def dummy_mainloop(*args, **kw):
687 pass
688 pass
688
689
689 try:
690 try:
690 import wx
691 import wx
691 except ImportError:
692 except ImportError:
692 # For very old versions of WX
693 # For very old versions of WX
693 import wxPython as wx
694 import wxPython as wx
694
695
695 ver = wx.__version__
696 ver = wx.__version__
696 orig_mainloop = None
697 orig_mainloop = None
697 if ver[:3] >= '2.5':
698 if ver[:3] >= '2.5':
698 import wx
699 import wx
699 if hasattr(wx, '_core_'): core = getattr(wx, '_core_')
700 if hasattr(wx, '_core_'): core = getattr(wx, '_core_')
700 elif hasattr(wx, '_core'): core = getattr(wx, '_core')
701 elif hasattr(wx, '_core'): core = getattr(wx, '_core')
701 else: raise AttributeError('Could not find wx core module')
702 else: raise AttributeError('Could not find wx core module')
702 orig_mainloop = core.PyApp_MainLoop
703 orig_mainloop = core.PyApp_MainLoop
703 core.PyApp_MainLoop = dummy_mainloop
704 core.PyApp_MainLoop = dummy_mainloop
704 elif ver[:3] == '2.4':
705 elif ver[:3] == '2.4':
705 orig_mainloop = wx.wxc.wxPyApp_MainLoop
706 orig_mainloop = wx.wxc.wxPyApp_MainLoop
706 wx.wxc.wxPyApp_MainLoop = dummy_mainloop
707 wx.wxc.wxPyApp_MainLoop = dummy_mainloop
707 else:
708 else:
708 warn("Unable to find either wxPython version 2.4 or >= 2.5.")
709 warn("Unable to find either wxPython version 2.4 or >= 2.5.")
709 return orig_mainloop
710 return orig_mainloop
710
711
711 def hijack_gtk():
712 def hijack_gtk():
712 """Modifies pyGTK's mainloop with a dummy so user code does not
713 """Modifies pyGTK's mainloop with a dummy so user code does not
713 block IPython. This function returns the original `gtk.mainloop`
714 block IPython. This function returns the original `gtk.mainloop`
714 function that has been hijacked.
715 function that has been hijacked.
715 """
716 """
716 def dummy_mainloop(*args, **kw):
717 def dummy_mainloop(*args, **kw):
717 pass
718 pass
718 import gtk
719 import gtk
719 if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main
720 if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main
720 else: orig_mainloop = gtk.mainloop
721 else: orig_mainloop = gtk.mainloop
721 gtk.mainloop = dummy_mainloop
722 gtk.mainloop = dummy_mainloop
722 gtk.main = dummy_mainloop
723 gtk.main = dummy_mainloop
723 return orig_mainloop
724 return orig_mainloop
724
725
725 def hijack_qt():
726 def hijack_qt():
726 """Modifies PyQt's mainloop with a dummy so user code does not
727 """Modifies PyQt's mainloop with a dummy so user code does not
727 block IPython. This function returns the original
728 block IPython. This function returns the original
728 `qt.qApp.exec_loop` function that has been hijacked.
729 `qt.qApp.exec_loop` function that has been hijacked.
729 """
730 """
730 def dummy_mainloop(*args, **kw):
731 def dummy_mainloop(*args, **kw):
731 pass
732 pass
732 import qt
733 import qt
733 orig_mainloop = qt.qApp.exec_loop
734 orig_mainloop = qt.qApp.exec_loop
734 qt.qApp.exec_loop = dummy_mainloop
735 qt.qApp.exec_loop = dummy_mainloop
735 qt.QApplication.exec_loop = dummy_mainloop
736 qt.QApplication.exec_loop = dummy_mainloop
736 return orig_mainloop
737 return orig_mainloop
737
738
738 def hijack_qt4():
739 def hijack_qt4():
739 """Modifies PyQt4's mainloop with a dummy so user code does not
740 """Modifies PyQt4's mainloop with a dummy so user code does not
740 block IPython. This function returns the original
741 block IPython. This function returns the original
741 `QtGui.qApp.exec_` function that has been hijacked.
742 `QtGui.qApp.exec_` function that has been hijacked.
742 """
743 """
743 def dummy_mainloop(*args, **kw):
744 def dummy_mainloop(*args, **kw):
744 pass
745 pass
745 from PyQt4 import QtGui, QtCore
746 from PyQt4 import QtGui, QtCore
746 orig_mainloop = QtGui.qApp.exec_
747 orig_mainloop = QtGui.qApp.exec_
747 QtGui.qApp.exec_ = dummy_mainloop
748 QtGui.qApp.exec_ = dummy_mainloop
748 QtGui.QApplication.exec_ = dummy_mainloop
749 QtGui.QApplication.exec_ = dummy_mainloop
749 QtCore.QCoreApplication.exec_ = dummy_mainloop
750 QtCore.QCoreApplication.exec_ = dummy_mainloop
750 return orig_mainloop
751 return orig_mainloop
751
752
752 #-----------------------------------------------------------------------------
753 #-----------------------------------------------------------------------------
753 # The IPShell* classes below are the ones meant to be run by external code as
754 # The IPShell* classes below are the ones meant to be run by external code as
754 # IPython instances. Note that unless a specific threading strategy is
755 # IPython instances. Note that unless a specific threading strategy is
755 # desired, the factory function start() below should be used instead (it
756 # desired, the factory function start() below should be used instead (it
756 # selects the proper threaded class).
757 # selects the proper threaded class).
757
758
758 class IPThread(threading.Thread):
759 class IPThread(threading.Thread):
759 def run(self):
760 def run(self):
760 self.IP.mainloop(self._banner)
761 self.IP.mainloop(self._banner)
761 self.IP.kill()
762 self.IP.kill()
762
763
763 class IPShellGTK(IPThread):
764 class IPShellGTK(IPThread):
764 """Run a gtk mainloop() in a separate thread.
765 """Run a gtk mainloop() in a separate thread.
765
766
766 Python commands can be passed to the thread where they will be executed.
767 Python commands can be passed to the thread where they will be executed.
767 This is implemented by periodically checking for passed code using a
768 This is implemented by periodically checking for passed code using a
768 GTK timeout callback."""
769 GTK timeout callback."""
769
770
770 TIMEOUT = 100 # Millisecond interval between timeouts.
771 TIMEOUT = 100 # Millisecond interval between timeouts.
771
772
772 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
773 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
773 debug=1,shell_class=MTInteractiveShell):
774 debug=1,shell_class=MTInteractiveShell):
774
775
775 import gtk
776 import gtk
776
777
777 self.gtk = gtk
778 self.gtk = gtk
778 self.gtk_mainloop = hijack_gtk()
779 self.gtk_mainloop = hijack_gtk()
779
780
780 # Allows us to use both Tk and GTK.
781 # Allows us to use both Tk and GTK.
781 self.tk = get_tk()
782 self.tk = get_tk()
782
783
783 if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit
784 if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit
784 else: mainquit = self.gtk.mainquit
785 else: mainquit = self.gtk.mainquit
785
786
786 self.IP = make_IPython(argv,user_ns=user_ns,
787 self.IP = make_IPython(argv,user_ns=user_ns,
787 user_global_ns=user_global_ns,
788 user_global_ns=user_global_ns,
788 debug=debug,
789 debug=debug,
789 shell_class=shell_class,
790 shell_class=shell_class,
790 on_kill=[mainquit])
791 on_kill=[mainquit])
791
792
792 # HACK: slot for banner in self; it will be passed to the mainloop
793 # HACK: slot for banner in self; it will be passed to the mainloop
793 # method only and .run() needs it. The actual value will be set by
794 # method only and .run() needs it. The actual value will be set by
794 # .mainloop().
795 # .mainloop().
795 self._banner = None
796 self._banner = None
796
797
797 threading.Thread.__init__(self)
798 threading.Thread.__init__(self)
798
799
799 def mainloop(self,sys_exit=0,banner=None):
800 def mainloop(self,sys_exit=0,banner=None):
800
801
801 self._banner = banner
802 self._banner = banner
802
803
803 if self.gtk.pygtk_version >= (2,4,0):
804 if self.gtk.pygtk_version >= (2,4,0):
804 import gobject
805 import gobject
805 gobject.idle_add(self.on_timer)
806 gobject.idle_add(self.on_timer)
806 else:
807 else:
807 self.gtk.idle_add(self.on_timer)
808 self.gtk.idle_add(self.on_timer)
808
809
809 if sys.platform != 'win32':
810 if sys.platform != 'win32':
810 try:
811 try:
811 if self.gtk.gtk_version[0] >= 2:
812 if self.gtk.gtk_version[0] >= 2:
812 self.gtk.gdk.threads_init()
813 self.gtk.gdk.threads_init()
813 except AttributeError:
814 except AttributeError:
814 pass
815 pass
815 except RuntimeError:
816 except RuntimeError:
816 error('Your pyGTK likely has not been compiled with '
817 error('Your pyGTK likely has not been compiled with '
817 'threading support.\n'
818 'threading support.\n'
818 'The exception printout is below.\n'
819 'The exception printout is below.\n'
819 'You can either rebuild pyGTK with threads, or '
820 'You can either rebuild pyGTK with threads, or '
820 'try using \n'
821 'try using \n'
821 'matplotlib with a different backend (like Tk or WX).\n'
822 'matplotlib with a different backend (like Tk or WX).\n'
822 'Note that matplotlib will most likely not work in its '
823 'Note that matplotlib will most likely not work in its '
823 'current state!')
824 'current state!')
824 self.IP.InteractiveTB()
825 self.IP.InteractiveTB()
825
826
826 self.start()
827 self.start()
827 self.gtk.gdk.threads_enter()
828 self.gtk.gdk.threads_enter()
828 self.gtk_mainloop()
829 self.gtk_mainloop()
829 self.gtk.gdk.threads_leave()
830 self.gtk.gdk.threads_leave()
830 self.join()
831 self.join()
831
832
832 def on_timer(self):
833 def on_timer(self):
833 """Called when GTK is idle.
834 """Called when GTK is idle.
834
835
835 Must return True always, otherwise GTK stops calling it"""
836 Must return True always, otherwise GTK stops calling it"""
836
837
837 update_tk(self.tk)
838 update_tk(self.tk)
838 self.IP.runcode()
839 self.IP.runcode()
839 time.sleep(0.01)
840 time.sleep(0.01)
840 return True
841 return True
841
842
842
843
843 class IPShellWX(IPThread):
844 class IPShellWX(IPThread):
844 """Run a wx mainloop() in a separate thread.
845 """Run a wx mainloop() in a separate thread.
845
846
846 Python commands can be passed to the thread where they will be executed.
847 Python commands can be passed to the thread where they will be executed.
847 This is implemented by periodically checking for passed code using a
848 This is implemented by periodically checking for passed code using a
848 GTK timeout callback."""
849 GTK timeout callback."""
849
850
850 TIMEOUT = 100 # Millisecond interval between timeouts.
851 TIMEOUT = 100 # Millisecond interval between timeouts.
851
852
852 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
853 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
853 debug=1,shell_class=MTInteractiveShell):
854 debug=1,shell_class=MTInteractiveShell):
854
855
855 self.IP = make_IPython(argv,user_ns=user_ns,
856 self.IP = make_IPython(argv,user_ns=user_ns,
856 user_global_ns=user_global_ns,
857 user_global_ns=user_global_ns,
857 debug=debug,
858 debug=debug,
858 shell_class=shell_class,
859 shell_class=shell_class,
859 on_kill=[self.wxexit])
860 on_kill=[self.wxexit])
860
861
861 wantedwxversion=self.IP.rc.wxversion
862 wantedwxversion=self.IP.rc.wxversion
862 if wantedwxversion!="0":
863 if wantedwxversion!="0":
863 try:
864 try:
864 import wxversion
865 import wxversion
865 except ImportError:
866 except ImportError:
866 error('The wxversion module is needed for WX version selection')
867 error('The wxversion module is needed for WX version selection')
867 else:
868 else:
868 try:
869 try:
869 wxversion.select(wantedwxversion)
870 wxversion.select(wantedwxversion)
870 except:
871 except:
871 self.IP.InteractiveTB()
872 self.IP.InteractiveTB()
872 error('Requested wxPython version %s could not be loaded' %
873 error('Requested wxPython version %s could not be loaded' %
873 wantedwxversion)
874 wantedwxversion)
874
875
875 import wx
876 import wx
876
877
877 threading.Thread.__init__(self)
878 threading.Thread.__init__(self)
878 self.wx = wx
879 self.wx = wx
879 self.wx_mainloop = hijack_wx()
880 self.wx_mainloop = hijack_wx()
880
881
881 # Allows us to use both Tk and GTK.
882 # Allows us to use both Tk and GTK.
882 self.tk = get_tk()
883 self.tk = get_tk()
883
884
884 # HACK: slot for banner in self; it will be passed to the mainloop
885 # HACK: slot for banner in self; it will be passed to the mainloop
885 # method only and .run() needs it. The actual value will be set by
886 # method only and .run() needs it. The actual value will be set by
886 # .mainloop().
887 # .mainloop().
887 self._banner = None
888 self._banner = None
888
889
889 self.app = None
890 self.app = None
890
891
891 def wxexit(self, *args):
892 def wxexit(self, *args):
892 if self.app is not None:
893 if self.app is not None:
893 self.app.agent.timer.Stop()
894 self.app.agent.timer.Stop()
894 self.app.ExitMainLoop()
895 self.app.ExitMainLoop()
895
896
896 def mainloop(self,sys_exit=0,banner=None):
897 def mainloop(self,sys_exit=0,banner=None):
897
898
898 self._banner = banner
899 self._banner = banner
899
900
900 self.start()
901 self.start()
901
902
902 class TimerAgent(self.wx.MiniFrame):
903 class TimerAgent(self.wx.MiniFrame):
903 wx = self.wx
904 wx = self.wx
904 IP = self.IP
905 IP = self.IP
905 tk = self.tk
906 tk = self.tk
906 def __init__(self, parent, interval):
907 def __init__(self, parent, interval):
907 style = self.wx.DEFAULT_FRAME_STYLE | self.wx.TINY_CAPTION_HORIZ
908 style = self.wx.DEFAULT_FRAME_STYLE | self.wx.TINY_CAPTION_HORIZ
908 self.wx.MiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200),
909 self.wx.MiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200),
909 size=(100, 100),style=style)
910 size=(100, 100),style=style)
910 self.Show(False)
911 self.Show(False)
911 self.interval = interval
912 self.interval = interval
912 self.timerId = self.wx.NewId()
913 self.timerId = self.wx.NewId()
913
914
914 def StartWork(self):
915 def StartWork(self):
915 self.timer = self.wx.Timer(self, self.timerId)
916 self.timer = self.wx.Timer(self, self.timerId)
916 self.wx.EVT_TIMER(self, self.timerId, self.OnTimer)
917 self.wx.EVT_TIMER(self, self.timerId, self.OnTimer)
917 self.timer.Start(self.interval)
918 self.timer.Start(self.interval)
918
919
919 def OnTimer(self, event):
920 def OnTimer(self, event):
920 update_tk(self.tk)
921 update_tk(self.tk)
921 self.IP.runcode()
922 self.IP.runcode()
922
923
923 class App(self.wx.App):
924 class App(self.wx.App):
924 wx = self.wx
925 wx = self.wx
925 TIMEOUT = self.TIMEOUT
926 TIMEOUT = self.TIMEOUT
926 def OnInit(self):
927 def OnInit(self):
927 'Create the main window and insert the custom frame'
928 'Create the main window and insert the custom frame'
928 self.agent = TimerAgent(None, self.TIMEOUT)
929 self.agent = TimerAgent(None, self.TIMEOUT)
929 self.agent.Show(False)
930 self.agent.Show(False)
930 self.agent.StartWork()
931 self.agent.StartWork()
931 return True
932 return True
932
933
933 self.app = App(redirect=False)
934 self.app = App(redirect=False)
934 self.wx_mainloop(self.app)
935 self.wx_mainloop(self.app)
935 self.join()
936 self.join()
936
937
937
938
938 class IPShellQt(IPThread):
939 class IPShellQt(IPThread):
939 """Run a Qt event loop in a separate thread.
940 """Run a Qt event loop in a separate thread.
940
941
941 Python commands can be passed to the thread where they will be executed.
942 Python commands can be passed to the thread where they will be executed.
942 This is implemented by periodically checking for passed code using a
943 This is implemented by periodically checking for passed code using a
943 Qt timer / slot."""
944 Qt timer / slot."""
944
945
945 TIMEOUT = 100 # Millisecond interval between timeouts.
946 TIMEOUT = 100 # Millisecond interval between timeouts.
946
947
947 def __init__(self, argv=None, user_ns=None, user_global_ns=None,
948 def __init__(self, argv=None, user_ns=None, user_global_ns=None,
948 debug=0, shell_class=MTInteractiveShell):
949 debug=0, shell_class=MTInteractiveShell):
949
950
950 import qt
951 import qt
951
952
952 self.exec_loop = hijack_qt()
953 self.exec_loop = hijack_qt()
953
954
954 # Allows us to use both Tk and QT.
955 # Allows us to use both Tk and QT.
955 self.tk = get_tk()
956 self.tk = get_tk()
956
957
957 self.IP = make_IPython(argv,
958 self.IP = make_IPython(argv,
958 user_ns=user_ns,
959 user_ns=user_ns,
959 user_global_ns=user_global_ns,
960 user_global_ns=user_global_ns,
960 debug=debug,
961 debug=debug,
961 shell_class=shell_class,
962 shell_class=shell_class,
962 on_kill=[qt.qApp.exit])
963 on_kill=[qt.qApp.exit])
963
964
964 # HACK: slot for banner in self; it will be passed to the mainloop
965 # HACK: slot for banner in self; it will be passed to the mainloop
965 # method only and .run() needs it. The actual value will be set by
966 # method only and .run() needs it. The actual value will be set by
966 # .mainloop().
967 # .mainloop().
967 self._banner = None
968 self._banner = None
968
969
969 threading.Thread.__init__(self)
970 threading.Thread.__init__(self)
970
971
971 def mainloop(self, sys_exit=0, banner=None):
972 def mainloop(self, sys_exit=0, banner=None):
972
973
973 import qt
974 import qt
974
975
975 self._banner = banner
976 self._banner = banner
976
977
977 if qt.QApplication.startingUp():
978 if qt.QApplication.startingUp():
978 a = qt.QApplication(sys.argv)
979 a = qt.QApplication(sys.argv)
979
980
980 self.timer = qt.QTimer()
981 self.timer = qt.QTimer()
981 qt.QObject.connect(self.timer,
982 qt.QObject.connect(self.timer,
982 qt.SIGNAL('timeout()'),
983 qt.SIGNAL('timeout()'),
983 self.on_timer)
984 self.on_timer)
984
985
985 self.start()
986 self.start()
986 self.timer.start(self.TIMEOUT, True)
987 self.timer.start(self.TIMEOUT, True)
987 while True:
988 while True:
988 if self.IP._kill: break
989 if self.IP._kill: break
989 self.exec_loop()
990 self.exec_loop()
990 self.join()
991 self.join()
991
992
992 def on_timer(self):
993 def on_timer(self):
993 update_tk(self.tk)
994 update_tk(self.tk)
994 result = self.IP.runcode()
995 result = self.IP.runcode()
995 self.timer.start(self.TIMEOUT, True)
996 self.timer.start(self.TIMEOUT, True)
996 return result
997 return result
997
998
998
999
999 class IPShellQt4(IPThread):
1000 class IPShellQt4(IPThread):
1000 """Run a Qt event loop in a separate thread.
1001 """Run a Qt event loop in a separate thread.
1001
1002
1002 Python commands can be passed to the thread where they will be executed.
1003 Python commands can be passed to the thread where they will be executed.
1003 This is implemented by periodically checking for passed code using a
1004 This is implemented by periodically checking for passed code using a
1004 Qt timer / slot."""
1005 Qt timer / slot."""
1005
1006
1006 TIMEOUT = 100 # Millisecond interval between timeouts.
1007 TIMEOUT = 100 # Millisecond interval between timeouts.
1007
1008
1008 def __init__(self, argv=None, user_ns=None, user_global_ns=None,
1009 def __init__(self, argv=None, user_ns=None, user_global_ns=None,
1009 debug=0, shell_class=MTInteractiveShell):
1010 debug=0, shell_class=MTInteractiveShell):
1010
1011
1011 from PyQt4 import QtCore, QtGui
1012 from PyQt4 import QtCore, QtGui
1012
1013
1013 try:
1014 try:
1014 # present in PyQt4-4.2.1 or later
1015 # present in PyQt4-4.2.1 or later
1015 QtCore.pyqtRemoveInputHook()
1016 QtCore.pyqtRemoveInputHook()
1016 except AttributeError:
1017 except AttributeError:
1017 pass
1018 pass
1018
1019
1019 if QtCore.PYQT_VERSION_STR == '4.3':
1020 if QtCore.PYQT_VERSION_STR == '4.3':
1020 warn('''PyQt4 version 4.3 detected.
1021 warn('''PyQt4 version 4.3 detected.
1021 If you experience repeated threading warnings, please update PyQt4.
1022 If you experience repeated threading warnings, please update PyQt4.
1022 ''')
1023 ''')
1023
1024
1024 self.exec_ = hijack_qt4()
1025 self.exec_ = hijack_qt4()
1025
1026
1026 # Allows us to use both Tk and QT.
1027 # Allows us to use both Tk and QT.
1027 self.tk = get_tk()
1028 self.tk = get_tk()
1028
1029
1029 self.IP = make_IPython(argv,
1030 self.IP = make_IPython(argv,
1030 user_ns=user_ns,
1031 user_ns=user_ns,
1031 user_global_ns=user_global_ns,
1032 user_global_ns=user_global_ns,
1032 debug=debug,
1033 debug=debug,
1033 shell_class=shell_class,
1034 shell_class=shell_class,
1034 on_kill=[QtGui.qApp.exit])
1035 on_kill=[QtGui.qApp.exit])
1035
1036
1036 # HACK: slot for banner in self; it will be passed to the mainloop
1037 # HACK: slot for banner in self; it will be passed to the mainloop
1037 # method only and .run() needs it. The actual value will be set by
1038 # method only and .run() needs it. The actual value will be set by
1038 # .mainloop().
1039 # .mainloop().
1039 self._banner = None
1040 self._banner = None
1040
1041
1041 threading.Thread.__init__(self)
1042 threading.Thread.__init__(self)
1042
1043
1043 def mainloop(self, sys_exit=0, banner=None):
1044 def mainloop(self, sys_exit=0, banner=None):
1044
1045
1045 from PyQt4 import QtCore, QtGui
1046 from PyQt4 import QtCore, QtGui
1046
1047
1047 self._banner = banner
1048 self._banner = banner
1048
1049
1049 if QtGui.QApplication.startingUp():
1050 if QtGui.QApplication.startingUp():
1050 a = QtGui.QApplication(sys.argv)
1051 a = QtGui.QApplication(sys.argv)
1051
1052
1052 self.timer = QtCore.QTimer()
1053 self.timer = QtCore.QTimer()
1053 QtCore.QObject.connect(self.timer,
1054 QtCore.QObject.connect(self.timer,
1054 QtCore.SIGNAL('timeout()'),
1055 QtCore.SIGNAL('timeout()'),
1055 self.on_timer)
1056 self.on_timer)
1056
1057
1057 self.start()
1058 self.start()
1058 self.timer.start(self.TIMEOUT)
1059 self.timer.start(self.TIMEOUT)
1059 while True:
1060 while True:
1060 if self.IP._kill: break
1061 if self.IP._kill: break
1061 self.exec_()
1062 self.exec_()
1062 self.join()
1063 self.join()
1063
1064
1064 def on_timer(self):
1065 def on_timer(self):
1065 update_tk(self.tk)
1066 update_tk(self.tk)
1066 result = self.IP.runcode()
1067 result = self.IP.runcode()
1067 self.timer.start(self.TIMEOUT)
1068 self.timer.start(self.TIMEOUT)
1068 return result
1069 return result
1069
1070
1070
1071
1071 # A set of matplotlib public IPython shell classes, for single-threaded (Tk*
1072 # A set of matplotlib public IPython shell classes, for single-threaded (Tk*
1072 # and FLTK*) and multithreaded (GTK*, WX* and Qt*) backends to use.
1073 # and FLTK*) and multithreaded (GTK*, WX* and Qt*) backends to use.
1073 def _load_pylab(user_ns):
1074 def _load_pylab(user_ns):
1074 """Allow users to disable pulling all of pylab into the top-level
1075 """Allow users to disable pulling all of pylab into the top-level
1075 namespace.
1076 namespace.
1076
1077
1077 This little utility must be called AFTER the actual ipython instance is
1078 This little utility must be called AFTER the actual ipython instance is
1078 running, since only then will the options file have been fully parsed."""
1079 running, since only then will the options file have been fully parsed."""
1079
1080
1080 ip = IPython.ipapi.get()
1081 ip = IPython.ipapi.get()
1081 if ip.options.pylab_import_all:
1082 if ip.options.pylab_import_all:
1082 ip.ex("from matplotlib.pylab import *")
1083 ip.ex("from matplotlib.pylab import *")
1083 ip.IP.user_config_ns.update(ip.user_ns)
1084 ip.IP.user_config_ns.update(ip.user_ns)
1084
1085
1085
1086
1086 class IPShellMatplotlib(IPShell):
1087 class IPShellMatplotlib(IPShell):
1087 """Subclass IPShell with MatplotlibShell as the internal shell.
1088 """Subclass IPShell with MatplotlibShell as the internal shell.
1088
1089
1089 Single-threaded class, meant for the Tk* and FLTK* backends.
1090 Single-threaded class, meant for the Tk* and FLTK* backends.
1090
1091
1091 Having this on a separate class simplifies the external driver code."""
1092 Having this on a separate class simplifies the external driver code."""
1092
1093
1093 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1094 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1094 IPShell.__init__(self,argv,user_ns,user_global_ns,debug,
1095 IPShell.__init__(self,argv,user_ns,user_global_ns,debug,
1095 shell_class=MatplotlibShell)
1096 shell_class=MatplotlibShell)
1096 _load_pylab(self.IP.user_ns)
1097 _load_pylab(self.IP.user_ns)
1097
1098
1098 class IPShellMatplotlibGTK(IPShellGTK):
1099 class IPShellMatplotlibGTK(IPShellGTK):
1099 """Subclass IPShellGTK with MatplotlibMTShell as the internal shell.
1100 """Subclass IPShellGTK with MatplotlibMTShell as the internal shell.
1100
1101
1101 Multi-threaded class, meant for the GTK* backends."""
1102 Multi-threaded class, meant for the GTK* backends."""
1102
1103
1103 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1104 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1104 IPShellGTK.__init__(self,argv,user_ns,user_global_ns,debug,
1105 IPShellGTK.__init__(self,argv,user_ns,user_global_ns,debug,
1105 shell_class=MatplotlibMTShell)
1106 shell_class=MatplotlibMTShell)
1106 _load_pylab(self.IP.user_ns)
1107 _load_pylab(self.IP.user_ns)
1107
1108
1108 class IPShellMatplotlibWX(IPShellWX):
1109 class IPShellMatplotlibWX(IPShellWX):
1109 """Subclass IPShellWX with MatplotlibMTShell as the internal shell.
1110 """Subclass IPShellWX with MatplotlibMTShell as the internal shell.
1110
1111
1111 Multi-threaded class, meant for the WX* backends."""
1112 Multi-threaded class, meant for the WX* backends."""
1112
1113
1113 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1114 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1114 IPShellWX.__init__(self,argv,user_ns,user_global_ns,debug,
1115 IPShellWX.__init__(self,argv,user_ns,user_global_ns,debug,
1115 shell_class=MatplotlibMTShell)
1116 shell_class=MatplotlibMTShell)
1116 _load_pylab(self.IP.user_ns)
1117 _load_pylab(self.IP.user_ns)
1117
1118
1118 class IPShellMatplotlibQt(IPShellQt):
1119 class IPShellMatplotlibQt(IPShellQt):
1119 """Subclass IPShellQt with MatplotlibMTShell as the internal shell.
1120 """Subclass IPShellQt with MatplotlibMTShell as the internal shell.
1120
1121
1121 Multi-threaded class, meant for the Qt* backends."""
1122 Multi-threaded class, meant for the Qt* backends."""
1122
1123
1123 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1124 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1124 IPShellQt.__init__(self,argv,user_ns,user_global_ns,debug,
1125 IPShellQt.__init__(self,argv,user_ns,user_global_ns,debug,
1125 shell_class=MatplotlibMTShell)
1126 shell_class=MatplotlibMTShell)
1126 _load_pylab(self.IP.user_ns)
1127 _load_pylab(self.IP.user_ns)
1127
1128
1128 class IPShellMatplotlibQt4(IPShellQt4):
1129 class IPShellMatplotlibQt4(IPShellQt4):
1129 """Subclass IPShellQt4 with MatplotlibMTShell as the internal shell.
1130 """Subclass IPShellQt4 with MatplotlibMTShell as the internal shell.
1130
1131
1131 Multi-threaded class, meant for the Qt4* backends."""
1132 Multi-threaded class, meant for the Qt4* backends."""
1132
1133
1133 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1134 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1134 IPShellQt4.__init__(self,argv,user_ns,user_global_ns,debug,
1135 IPShellQt4.__init__(self,argv,user_ns,user_global_ns,debug,
1135 shell_class=MatplotlibMTShell)
1136 shell_class=MatplotlibMTShell)
1136 _load_pylab(self.IP.user_ns)
1137 _load_pylab(self.IP.user_ns)
1137
1138
1138 #-----------------------------------------------------------------------------
1139 #-----------------------------------------------------------------------------
1139 # Factory functions to actually start the proper thread-aware shell
1140 # Factory functions to actually start the proper thread-aware shell
1140
1141
1141 def _select_shell(argv):
1142 def _select_shell(argv):
1142 """Select a shell from the given argv vector.
1143 """Select a shell from the given argv vector.
1143
1144
1144 This function implements the threading selection policy, allowing runtime
1145 This function implements the threading selection policy, allowing runtime
1145 control of the threading mode, both for general users and for matplotlib.
1146 control of the threading mode, both for general users and for matplotlib.
1146
1147
1147 Return:
1148 Return:
1148 Shell class to be instantiated for runtime operation.
1149 Shell class to be instantiated for runtime operation.
1149 """
1150 """
1150
1151
1151 global USE_TK
1152 global USE_TK
1152
1153
1153 mpl_shell = {'gthread' : IPShellMatplotlibGTK,
1154 mpl_shell = {'gthread' : IPShellMatplotlibGTK,
1154 'wthread' : IPShellMatplotlibWX,
1155 'wthread' : IPShellMatplotlibWX,
1155 'qthread' : IPShellMatplotlibQt,
1156 'qthread' : IPShellMatplotlibQt,
1156 'q4thread' : IPShellMatplotlibQt4,
1157 'q4thread' : IPShellMatplotlibQt4,
1157 'tkthread' : IPShellMatplotlib, # Tk is built-in
1158 'tkthread' : IPShellMatplotlib, # Tk is built-in
1158 }
1159 }
1159
1160
1160 th_shell = {'gthread' : IPShellGTK,
1161 th_shell = {'gthread' : IPShellGTK,
1161 'wthread' : IPShellWX,
1162 'wthread' : IPShellWX,
1162 'qthread' : IPShellQt,
1163 'qthread' : IPShellQt,
1163 'q4thread' : IPShellQt4,
1164 'q4thread' : IPShellQt4,
1164 'tkthread' : IPShell, # Tk is built-in
1165 'tkthread' : IPShell, # Tk is built-in
1165 }
1166 }
1166
1167
1167 backends = {'gthread' : 'GTKAgg',
1168 backends = {'gthread' : 'GTKAgg',
1168 'wthread' : 'WXAgg',
1169 'wthread' : 'WXAgg',
1169 'qthread' : 'QtAgg',
1170 'qthread' : 'QtAgg',
1170 'q4thread' :'Qt4Agg',
1171 'q4thread' :'Qt4Agg',
1171 'tkthread' :'TkAgg',
1172 'tkthread' :'TkAgg',
1172 }
1173 }
1173
1174
1174 all_opts = set(['tk','pylab','gthread','qthread','q4thread','wthread',
1175 all_opts = set(['tk','pylab','gthread','qthread','q4thread','wthread',
1175 'tkthread'])
1176 'tkthread'])
1176 user_opts = set([s.replace('-','') for s in argv[:3]])
1177 user_opts = set([s.replace('-','') for s in argv[:3]])
1177 special_opts = user_opts & all_opts
1178 special_opts = user_opts & all_opts
1178
1179
1179 if 'tk' in special_opts:
1180 if 'tk' in special_opts:
1180 USE_TK = True
1181 USE_TK = True
1181 special_opts.remove('tk')
1182 special_opts.remove('tk')
1182
1183
1183 if 'pylab' in special_opts:
1184 if 'pylab' in special_opts:
1184
1185
1185 try:
1186 try:
1186 import matplotlib
1187 import matplotlib
1187 except ImportError:
1188 except ImportError:
1188 error('matplotlib could NOT be imported! Starting normal IPython.')
1189 error('matplotlib could NOT be imported! Starting normal IPython.')
1189 return IPShell
1190 return IPShell
1190
1191
1191 special_opts.remove('pylab')
1192 special_opts.remove('pylab')
1192 # If there's any option left, it means the user wants to force the
1193 # If there's any option left, it means the user wants to force the
1193 # threading backend, else it's auto-selected from the rc file
1194 # threading backend, else it's auto-selected from the rc file
1194 if special_opts:
1195 if special_opts:
1195 th_mode = special_opts.pop()
1196 th_mode = special_opts.pop()
1196 matplotlib.rcParams['backend'] = backends[th_mode]
1197 matplotlib.rcParams['backend'] = backends[th_mode]
1197 else:
1198 else:
1198 backend = matplotlib.rcParams['backend']
1199 backend = matplotlib.rcParams['backend']
1199 if backend.startswith('GTK'):
1200 if backend.startswith('GTK'):
1200 th_mode = 'gthread'
1201 th_mode = 'gthread'
1201 elif backend.startswith('WX'):
1202 elif backend.startswith('WX'):
1202 th_mode = 'wthread'
1203 th_mode = 'wthread'
1203 elif backend.startswith('Qt4'):
1204 elif backend.startswith('Qt4'):
1204 th_mode = 'q4thread'
1205 th_mode = 'q4thread'
1205 elif backend.startswith('Qt'):
1206 elif backend.startswith('Qt'):
1206 th_mode = 'qthread'
1207 th_mode = 'qthread'
1207 else:
1208 else:
1208 # Any other backend, use plain Tk
1209 # Any other backend, use plain Tk
1209 th_mode = 'tkthread'
1210 th_mode = 'tkthread'
1210
1211
1211 return mpl_shell[th_mode]
1212 return mpl_shell[th_mode]
1212 else:
1213 else:
1213 # No pylab requested, just plain threads
1214 # No pylab requested, just plain threads
1214 try:
1215 try:
1215 th_mode = special_opts.pop()
1216 th_mode = special_opts.pop()
1216 except KeyError:
1217 except KeyError:
1217 th_mode = 'tkthread'
1218 th_mode = 'tkthread'
1218 return th_shell[th_mode]
1219 return th_shell[th_mode]
1219
1220
1220
1221
1221 # This is the one which should be called by external code.
1222 # This is the one which should be called by external code.
1222 def start(user_ns = None):
1223 def start(user_ns = None):
1223 """Return a running shell instance, dealing with threading options.
1224 """Return a running shell instance, dealing with threading options.
1224
1225
1225 This is a factory function which will instantiate the proper IPython shell
1226 This is a factory function which will instantiate the proper IPython shell
1226 based on the user's threading choice. Such a selector is needed because
1227 based on the user's threading choice. Such a selector is needed because
1227 different GUI toolkits require different thread handling details."""
1228 different GUI toolkits require different thread handling details."""
1228
1229
1229 shell = _select_shell(sys.argv)
1230 shell = _select_shell(sys.argv)
1230 return shell(user_ns = user_ns)
1231 return shell(user_ns = user_ns)
1231
1232
1232 # Some aliases for backwards compatibility
1233 # Some aliases for backwards compatibility
1233 IPythonShell = IPShell
1234 IPythonShell = IPShell
1234 IPythonShellEmbed = IPShellEmbed
1235 IPythonShellEmbed = IPShellEmbed
1235 #************************ End of file <Shell.py> ***************************
1236 #************************ End of file <Shell.py> ***************************
@@ -1,609 +1,647 b''
1 """IPython customization API
1 """IPython customization API
2
2
3 Your one-stop module for configuring & extending ipython
3 Your one-stop module for configuring & extending ipython
4
4
5 The API will probably break when ipython 1.0 is released, but so
5 The API will probably break when ipython 1.0 is released, but so
6 will the other configuration method (rc files).
6 will the other configuration method (rc files).
7
7
8 All names prefixed by underscores are for internal use, not part
8 All names prefixed by underscores are for internal use, not part
9 of the public api.
9 of the public api.
10
10
11 Below is an example that you can just put to a module and import from ipython.
11 Below is an example that you can just put to a module and import from ipython.
12
12
13 A good practice is to install the config script below as e.g.
13 A good practice is to install the config script below as e.g.
14
14
15 ~/.ipython/my_private_conf.py
15 ~/.ipython/my_private_conf.py
16
16
17 And do
17 And do
18
18
19 import_mod my_private_conf
19 import_mod my_private_conf
20
20
21 in ~/.ipython/ipythonrc
21 in ~/.ipython/ipythonrc
22
22
23 That way the module is imported at startup and you can have all your
23 That way the module is imported at startup and you can have all your
24 personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
24 personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
25 stuff) in there.
25 stuff) in there.
26
26
27 -----------------------------------------------
27 -----------------------------------------------
28 import IPython.ipapi
28 import IPython.ipapi
29 ip = IPython.ipapi.get()
29 ip = IPython.ipapi.get()
30
30
31 def ankka_f(self, arg):
31 def ankka_f(self, arg):
32 print 'Ankka',self,'says uppercase:',arg.upper()
32 print 'Ankka',self,'says uppercase:',arg.upper()
33
33
34 ip.expose_magic('ankka',ankka_f)
34 ip.expose_magic('ankka',ankka_f)
35
35
36 ip.magic('alias sayhi echo "Testing, hi ok"')
36 ip.magic('alias sayhi echo "Testing, hi ok"')
37 ip.magic('alias helloworld echo "Hello world"')
37 ip.magic('alias helloworld echo "Hello world"')
38 ip.system('pwd')
38 ip.system('pwd')
39
39
40 ip.ex('import re')
40 ip.ex('import re')
41 ip.ex('''
41 ip.ex('''
42 def funcci(a,b):
42 def funcci(a,b):
43 print a+b
43 print a+b
44 print funcci(3,4)
44 print funcci(3,4)
45 ''')
45 ''')
46 ip.ex('funcci(348,9)')
46 ip.ex('funcci(348,9)')
47
47
48 def jed_editor(self,filename, linenum=None):
48 def jed_editor(self,filename, linenum=None):
49 print 'Calling my own editor, jed ... via hook!'
49 print 'Calling my own editor, jed ... via hook!'
50 import os
50 import os
51 if linenum is None: linenum = 0
51 if linenum is None: linenum = 0
52 os.system('jed +%d %s' % (linenum, filename))
52 os.system('jed +%d %s' % (linenum, filename))
53 print 'exiting jed'
53 print 'exiting jed'
54
54
55 ip.set_hook('editor',jed_editor)
55 ip.set_hook('editor',jed_editor)
56
56
57 o = ip.options
57 o = ip.options
58 o.autocall = 2 # FULL autocall mode
58 o.autocall = 2 # FULL autocall mode
59
59
60 print 'done!'
60 print 'done!'
61 """
61 """
62
62
63 #-----------------------------------------------------------------------------
63 #-----------------------------------------------------------------------------
64 # Modules and globals
64 # Modules and globals
65
65
66 # stdlib imports
66 # stdlib imports
67 import __builtin__
67 import __builtin__
68 import sys
68 import sys
69
69
70 # contains the most recently instantiated IPApi
70 # contains the most recently instantiated IPApi
71 _RECENT_IP = None
71 _RECENT_IP = None
72
72
73 #-----------------------------------------------------------------------------
73 #-----------------------------------------------------------------------------
74 # Code begins
74 # Code begins
75
75
76 class TryNext(Exception):
76 class TryNext(Exception):
77 """Try next hook exception.
77 """Try next hook exception.
78
78
79 Raise this in your hook function to indicate that the next hook handler
79 Raise this in your hook function to indicate that the next hook handler
80 should be used to handle the operation. If you pass arguments to the
80 should be used to handle the operation. If you pass arguments to the
81 constructor those arguments will be used by the next hook instead of the
81 constructor those arguments will be used by the next hook instead of the
82 original ones.
82 original ones.
83 """
83 """
84
84
85 def __init__(self, *args, **kwargs):
85 def __init__(self, *args, **kwargs):
86 self.args = args
86 self.args = args
87 self.kwargs = kwargs
87 self.kwargs = kwargs
88
88
89
89
90 class UsageError(Exception):
90 class UsageError(Exception):
91 """ Error in magic function arguments, etc.
91 """ Error in magic function arguments, etc.
92
92
93 Something that probably won't warrant a full traceback, but should
93 Something that probably won't warrant a full traceback, but should
94 nevertheless interrupt a macro / batch file.
94 nevertheless interrupt a macro / batch file.
95 """
95 """
96
96
97
97
98 class IPyAutocall:
98 class IPyAutocall:
99 """ Instances of this class are always autocalled
99 """ Instances of this class are always autocalled
100
100
101 This happens regardless of 'autocall' variable state. Use this to
101 This happens regardless of 'autocall' variable state. Use this to
102 develop macro-like mechanisms.
102 develop macro-like mechanisms.
103 """
103 """
104
104
105 def set_ip(self,ip):
105 def set_ip(self,ip):
106 """ Will be used to set _ip point to current ipython instance b/f call
106 """ Will be used to set _ip point to current ipython instance b/f call
107
107
108 Override this method if you don't want this to happen.
108 Override this method if you don't want this to happen.
109
109
110 """
110 """
111 self._ip = ip
111 self._ip = ip
112
112
113
113
114 class IPythonNotRunning:
114 class IPythonNotRunning:
115 """Dummy do-nothing class.
115 """Dummy do-nothing class.
116
116
117 Instances of this class return a dummy attribute on all accesses, which
117 Instances of this class return a dummy attribute on all accesses, which
118 can be called and warns. This makes it easier to write scripts which use
118 can be called and warns. This makes it easier to write scripts which use
119 the ipapi.get() object for informational purposes to operate both with and
119 the ipapi.get() object for informational purposes to operate both with and
120 without ipython. Obviously code which uses the ipython object for
120 without ipython. Obviously code which uses the ipython object for
121 computations will not work, but this allows a wider range of code to
121 computations will not work, but this allows a wider range of code to
122 transparently work whether ipython is being used or not."""
122 transparently work whether ipython is being used or not."""
123
123
124 def __init__(self,warn=True):
124 def __init__(self,warn=True):
125 if warn:
125 if warn:
126 self.dummy = self._dummy_warn
126 self.dummy = self._dummy_warn
127 else:
127 else:
128 self.dummy = self._dummy_silent
128 self.dummy = self._dummy_silent
129
129
130 def __str__(self):
130 def __str__(self):
131 return "<IPythonNotRunning>"
131 return "<IPythonNotRunning>"
132
132
133 __repr__ = __str__
133 __repr__ = __str__
134
134
135 def __getattr__(self,name):
135 def __getattr__(self,name):
136 return self.dummy
136 return self.dummy
137
137
138 def _dummy_warn(self,*args,**kw):
138 def _dummy_warn(self,*args,**kw):
139 """Dummy function, which doesn't do anything but warn."""
139 """Dummy function, which doesn't do anything but warn."""
140
140
141 print ("IPython is not running, this is a dummy no-op function")
141 print ("IPython is not running, this is a dummy no-op function")
142
142
143 def _dummy_silent(self,*args,**kw):
143 def _dummy_silent(self,*args,**kw):
144 """Dummy function, which doesn't do anything and emits no warnings."""
144 """Dummy function, which doesn't do anything and emits no warnings."""
145 pass
145 pass
146
146
147
147
148 def get(allow_dummy=False,dummy_warn=True):
148 def get(allow_dummy=False,dummy_warn=True):
149 """Get an IPApi object.
149 """Get an IPApi object.
150
150
151 If allow_dummy is true, returns an instance of IPythonNotRunning
151 If allow_dummy is true, returns an instance of IPythonNotRunning
152 instead of None if not running under IPython.
152 instead of None if not running under IPython.
153
153
154 If dummy_warn is false, the dummy instance will be completely silent.
154 If dummy_warn is false, the dummy instance will be completely silent.
155
155
156 Running this should be the first thing you do when writing extensions that
156 Running this should be the first thing you do when writing extensions that
157 can be imported as normal modules. You can then direct all the
157 can be imported as normal modules. You can then direct all the
158 configuration operations against the returned object.
158 configuration operations against the returned object.
159 """
159 """
160 global _RECENT_IP
160 global _RECENT_IP
161 if allow_dummy and not _RECENT_IP:
161 if allow_dummy and not _RECENT_IP:
162 _RECENT_IP = IPythonNotRunning(dummy_warn)
162 _RECENT_IP = IPythonNotRunning(dummy_warn)
163 return _RECENT_IP
163 return _RECENT_IP
164
164
165
165
166 class IPApi(object):
166 class IPApi(object):
167 """ The actual API class for configuring IPython
167 """ The actual API class for configuring IPython
168
168
169 You should do all of the IPython configuration by getting an IPApi object
169 You should do all of the IPython configuration by getting an IPApi object
170 with IPython.ipapi.get() and using the attributes and methods of the
170 with IPython.ipapi.get() and using the attributes and methods of the
171 returned object."""
171 returned object."""
172
172
173 def __init__(self,ip):
173 def __init__(self,ip):
174
174
175 global _RECENT_IP
175 global _RECENT_IP
176
176
177 # All attributes exposed here are considered to be the public API of
177 # All attributes exposed here are considered to be the public API of
178 # IPython. As needs dictate, some of these may be wrapped as
178 # IPython. As needs dictate, some of these may be wrapped as
179 # properties.
179 # properties.
180
180
181 self.magic = ip.ipmagic
181 self.magic = ip.ipmagic
182
182
183 self.system = ip.system
183 self.system = ip.system
184
184
185 self.set_hook = ip.set_hook
185 self.set_hook = ip.set_hook
186
186
187 self.set_custom_exc = ip.set_custom_exc
187 self.set_custom_exc = ip.set_custom_exc
188
188
189 self.user_ns = ip.user_ns
189 self.user_ns = ip.user_ns
190 self.user_ns['_ip'] = self
190 self.user_ns['_ip'] = self
191
191
192 self.set_crash_handler = ip.set_crash_handler
192 self.set_crash_handler = ip.set_crash_handler
193
193
194 # Session-specific data store, which can be used to store
194 # Session-specific data store, which can be used to store
195 # data that should persist through the ipython session.
195 # data that should persist through the ipython session.
196 self.meta = ip.meta
196 self.meta = ip.meta
197
197
198 # The ipython instance provided
198 # The ipython instance provided
199 self.IP = ip
199 self.IP = ip
200
200
201 self.extensions = {}
201 self.extensions = {}
202
202
203 self.dbg = DebugTools(self)
203 self.dbg = DebugTools(self)
204
204
205 _RECENT_IP = self
205 _RECENT_IP = self
206
206
207 # Use a property for some things which are added to the instance very
207 # Use a property for some things which are added to the instance very
208 # late. I don't have time right now to disentangle the initialization
208 # late. I don't have time right now to disentangle the initialization
209 # order issues, so a property lets us delay item extraction while
209 # order issues, so a property lets us delay item extraction while
210 # providing a normal attribute API.
210 # providing a normal attribute API.
211 def get_db(self):
211 def get_db(self):
212 """A handle to persistent dict-like database (a PickleShareDB object)"""
212 """A handle to persistent dict-like database (a PickleShareDB object)"""
213 return self.IP.db
213 return self.IP.db
214
214
215 db = property(get_db,None,None,get_db.__doc__)
215 db = property(get_db,None,None,get_db.__doc__)
216
216
217 def get_options(self):
217 def get_options(self):
218 """All configurable variables."""
218 """All configurable variables."""
219
219
220 # catch typos by disabling new attribute creation. If new attr creation
220 # catch typos by disabling new attribute creation. If new attr creation
221 # is in fact wanted (e.g. when exposing new options), do
221 # is in fact wanted (e.g. when exposing new options), do
222 # allow_new_attr(True) for the received rc struct.
222 # allow_new_attr(True) for the received rc struct.
223
223
224 self.IP.rc.allow_new_attr(False)
224 self.IP.rc.allow_new_attr(False)
225 return self.IP.rc
225 return self.IP.rc
226
226
227 options = property(get_options,None,None,get_options.__doc__)
227 options = property(get_options,None,None,get_options.__doc__)
228
228
229 def expose_magic(self,magicname, func):
229 def expose_magic(self,magicname, func):
230 """Expose own function as magic function for ipython
230 """Expose own function as magic function for ipython
231
231
232 def foo_impl(self,parameter_s=''):
232 def foo_impl(self,parameter_s=''):
233 'My very own magic!. (Use docstrings, IPython reads them).'
233 'My very own magic!. (Use docstrings, IPython reads them).'
234 print 'Magic function. Passed parameter is between < >:'
234 print 'Magic function. Passed parameter is between < >:'
235 print '<%s>' % parameter_s
235 print '<%s>' % parameter_s
236 print 'The self object is:',self
236 print 'The self object is:',self
237
237
238 ipapi.expose_magic('foo',foo_impl)
238 ipapi.expose_magic('foo',foo_impl)
239 """
239 """
240
240
241 import new
241 import new
242 im = new.instancemethod(func,self.IP, self.IP.__class__)
242 im = new.instancemethod(func,self.IP, self.IP.__class__)
243 old = getattr(self.IP, "magic_" + magicname, None)
243 old = getattr(self.IP, "magic_" + magicname, None)
244 if old:
244 if old:
245 self.dbg.debug_stack("Magic redefinition '%s', old %s" %
245 self.dbg.debug_stack("Magic redefinition '%s', old %s" %
246 (magicname,old) )
246 (magicname,old) )
247
247
248 setattr(self.IP, "magic_" + magicname, im)
248 setattr(self.IP, "magic_" + magicname, im)
249
249
250 def ex(self,cmd):
250 def ex(self,cmd):
251 """ Execute a normal python statement in user namespace """
251 """ Execute a normal python statement in user namespace """
252 exec cmd in self.user_ns
252 exec cmd in self.user_ns
253
253
254 def ev(self,expr):
254 def ev(self,expr):
255 """ Evaluate python expression expr in user namespace
255 """ Evaluate python expression expr in user namespace
256
256
257 Returns the result of evaluation"""
257 Returns the result of evaluation"""
258 return eval(expr,self.user_ns)
258 return eval(expr,self.user_ns)
259
259
260 def runlines(self,lines):
260 def runlines(self,lines):
261 """ Run the specified lines in interpreter, honoring ipython directives.
261 """ Run the specified lines in interpreter, honoring ipython directives.
262
262
263 This allows %magic and !shell escape notations.
263 This allows %magic and !shell escape notations.
264
264
265 Takes either all lines in one string or list of lines.
265 Takes either all lines in one string or list of lines.
266 """
266 """
267
267
268 def cleanup_ipy_script(script):
268 def cleanup_ipy_script(script):
269 """ Make a script safe for _ip.runlines()
269 """ Make a script safe for _ip.runlines()
270
270
271 - Removes empty lines Suffixes all indented blocks that end with
271 - Removes empty lines Suffixes all indented blocks that end with
272 - unindented lines with empty lines
272 - unindented lines with empty lines
273 """
273 """
274
274
275 res = []
275 res = []
276 lines = script.splitlines()
276 lines = script.splitlines()
277
277
278 level = 0
278 level = 0
279 for l in lines:
279 for l in lines:
280 lstripped = l.lstrip()
280 lstripped = l.lstrip()
281 stripped = l.strip()
281 stripped = l.strip()
282 if not stripped:
282 if not stripped:
283 continue
283 continue
284 newlevel = len(l) - len(lstripped)
284 newlevel = len(l) - len(lstripped)
285 def is_secondary_block_start(s):
285 def is_secondary_block_start(s):
286 if not s.endswith(':'):
286 if not s.endswith(':'):
287 return False
287 return False
288 if (s.startswith('elif') or
288 if (s.startswith('elif') or
289 s.startswith('else') or
289 s.startswith('else') or
290 s.startswith('except') or
290 s.startswith('except') or
291 s.startswith('finally')):
291 s.startswith('finally')):
292 return True
292 return True
293
293
294 if level > 0 and newlevel == 0 and \
294 if level > 0 and newlevel == 0 and \
295 not is_secondary_block_start(stripped):
295 not is_secondary_block_start(stripped):
296 # add empty line
296 # add empty line
297 res.append('')
297 res.append('')
298
298
299 res.append(l)
299 res.append(l)
300 level = newlevel
300 level = newlevel
301 return '\n'.join(res) + '\n'
301 return '\n'.join(res) + '\n'
302
302
303 if isinstance(lines,basestring):
303 if isinstance(lines,basestring):
304 script = lines
304 script = lines
305 else:
305 else:
306 script = '\n'.join(lines)
306 script = '\n'.join(lines)
307 clean=cleanup_ipy_script(script)
307 clean=cleanup_ipy_script(script)
308 # print "_ip.runlines() script:\n",clean # dbg
308 # print "_ip.runlines() script:\n",clean # dbg
309 self.IP.runlines(clean)
309 self.IP.runlines(clean)
310
310
311 def to_user_ns(self,vars, interactive = True):
311 def to_user_ns(self,vars, interactive = True):
312 """Inject a group of variables into the IPython user namespace.
312 """Inject a group of variables into the IPython user namespace.
313
313
314 Inputs:
314 Inputs:
315
315
316 - vars: string with variable names separated by whitespace, or a
316 - vars: string with variable names separated by whitespace, or a
317 dict with name/value pairs.
317 dict with name/value pairs.
318
318
319 - interactive: if True (default), the var will be listed with
319 - interactive: if True (default), the var will be listed with
320 %whos et. al.
320 %whos et. al.
321
321
322 This utility routine is meant to ease interactive debugging work,
322 This utility routine is meant to ease interactive debugging work,
323 where you want to easily propagate some internal variable in your code
323 where you want to easily propagate some internal variable in your code
324 up to the interactive namespace for further exploration.
324 up to the interactive namespace for further exploration.
325
325
326 When you run code via %run, globals in your script become visible at
326 When you run code via %run, globals in your script become visible at
327 the interactive prompt, but this doesn't happen for locals inside your
327 the interactive prompt, but this doesn't happen for locals inside your
328 own functions and methods. Yet when debugging, it is common to want
328 own functions and methods. Yet when debugging, it is common to want
329 to explore some internal variables further at the interactive propmt.
329 to explore some internal variables further at the interactive propmt.
330
330
331 Examples:
331 Examples:
332
332
333 To use this, you first must obtain a handle on the ipython object as
333 To use this, you first must obtain a handle on the ipython object as
334 indicated above, via:
334 indicated above, via:
335
335
336 import IPython.ipapi
336 import IPython.ipapi
337 ip = IPython.ipapi.get()
337 ip = IPython.ipapi.get()
338
338
339 Once this is done, inside a routine foo() where you want to expose
339 Once this is done, inside a routine foo() where you want to expose
340 variables x and y, you do the following:
340 variables x and y, you do the following:
341
341
342 def foo():
342 def foo():
343 ...
343 ...
344 x = your_computation()
344 x = your_computation()
345 y = something_else()
345 y = something_else()
346
346
347 # This pushes x and y to the interactive prompt immediately, even
347 # This pushes x and y to the interactive prompt immediately, even
348 # if this routine crashes on the next line after:
348 # if this routine crashes on the next line after:
349 ip.to_user_ns('x y')
349 ip.to_user_ns('x y')
350 ...
350 ...
351
351
352 # To expose *ALL* the local variables from the function, use:
352 # To expose *ALL* the local variables from the function, use:
353 ip.to_user_ns(locals())
353 ip.to_user_ns(locals())
354
354
355 ...
355 ...
356 # return
356 # return
357
357
358
358
359 If you need to rename variables, the dict input makes it easy. For
359 If you need to rename variables, the dict input makes it easy. For
360 example, this call exposes variables 'foo' as 'x' and 'bar' as 'y'
360 example, this call exposes variables 'foo' as 'x' and 'bar' as 'y'
361 in IPython user namespace:
361 in IPython user namespace:
362
362
363 ip.to_user_ns(dict(x=foo,y=bar))
363 ip.to_user_ns(dict(x=foo,y=bar))
364 """
364 """
365
365
366 # print 'vars given:',vars # dbg
366 # print 'vars given:',vars # dbg
367
367
368 # We need a dict of name/value pairs to do namespace updates.
368 # We need a dict of name/value pairs to do namespace updates.
369 if isinstance(vars,dict):
369 if isinstance(vars,dict):
370 # If a dict was given, no need to change anything.
370 # If a dict was given, no need to change anything.
371 vdict = vars
371 vdict = vars
372 elif isinstance(vars,basestring):
372 elif isinstance(vars,basestring):
373 # If a string with names was given, get the caller's frame to
373 # If a string with names was given, get the caller's frame to
374 # evaluate the given names in
374 # evaluate the given names in
375 cf = sys._getframe(1)
375 cf = sys._getframe(1)
376 vdict = {}
376 vdict = {}
377 for name in vars.split():
377 for name in vars.split():
378 try:
378 try:
379 vdict[name] = eval(name,cf.f_globals,cf.f_locals)
379 vdict[name] = eval(name,cf.f_globals,cf.f_locals)
380 except:
380 except:
381 print ('could not get var. %s from %s' %
381 print ('could not get var. %s from %s' %
382 (name,cf.f_code.co_name))
382 (name,cf.f_code.co_name))
383 else:
383 else:
384 raise ValueError('vars must be a string or a dict')
384 raise ValueError('vars must be a string or a dict')
385
385
386 # Propagate variables to user namespace
386 # Propagate variables to user namespace
387 self.user_ns.update(vdict)
387 self.user_ns.update(vdict)
388
388
389 # And configure interactive visibility
389 # And configure interactive visibility
390 config_ns = self.IP.user_config_ns
390 config_ns = self.IP.user_config_ns
391 if interactive:
391 if interactive:
392 for name,val in vdict.iteritems():
392 for name,val in vdict.iteritems():
393 config_ns.pop(name,None)
393 config_ns.pop(name,None)
394 else:
394 else:
395 for name,val in vdict.iteritems():
395 for name,val in vdict.iteritems():
396 config_ns[name] = val
396 config_ns[name] = val
397
397
398 def expand_alias(self,line):
398 def expand_alias(self,line):
399 """ Expand an alias in the command line
399 """ Expand an alias in the command line
400
400
401 Returns the provided command line, possibly with the first word
401 Returns the provided command line, possibly with the first word
402 (command) translated according to alias expansion rules.
402 (command) translated according to alias expansion rules.
403
403
404 [ipython]|16> _ip.expand_aliases("np myfile.txt")
404 [ipython]|16> _ip.expand_aliases("np myfile.txt")
405 <16> 'q:/opt/np/notepad++.exe myfile.txt'
405 <16> 'q:/opt/np/notepad++.exe myfile.txt'
406 """
406 """
407
407
408 pre,fn,rest = self.IP.split_user_input(line)
408 pre,fn,rest = self.IP.split_user_input(line)
409 res = pre + self.IP.expand_aliases(fn,rest)
409 res = pre + self.IP.expand_aliases(fn,rest)
410 return res
410 return res
411
411
412 def itpl(self, s, depth = 1):
412 def itpl(self, s, depth = 1):
413 """ Expand Itpl format string s.
413 """ Expand Itpl format string s.
414
414
415 Only callable from command line (i.e. prefilter results);
415 Only callable from command line (i.e. prefilter results);
416 If you use in your scripts, you need to use a bigger depth!
416 If you use in your scripts, you need to use a bigger depth!
417 """
417 """
418 return self.IP.var_expand(s, depth)
418 return self.IP.var_expand(s, depth)
419
419
420 def defalias(self, name, cmd):
420 def defalias(self, name, cmd):
421 """ Define a new alias
421 """ Define a new alias
422
422
423 _ip.defalias('bb','bldmake bldfiles')
423 _ip.defalias('bb','bldmake bldfiles')
424
424
425 Creates a new alias named 'bb' in ipython user namespace
425 Creates a new alias named 'bb' in ipython user namespace
426 """
426 """
427
427
428 self.dbg.check_hotname(name)
428 self.dbg.check_hotname(name)
429
429
430 if name in self.IP.alias_table:
430 if name in self.IP.alias_table:
431 self.dbg.debug_stack("Alias redefinition: '%s' => '%s' (old '%s')"
431 self.dbg.debug_stack("Alias redefinition: '%s' => '%s' (old '%s')"
432 % (name, cmd, self.IP.alias_table[name]))
432 % (name, cmd, self.IP.alias_table[name]))
433
433
434 if callable(cmd):
434 if callable(cmd):
435 self.IP.alias_table[name] = cmd
435 self.IP.alias_table[name] = cmd
436 import IPython.shadowns
436 import IPython.shadowns
437 setattr(IPython.shadowns, name,cmd)
437 setattr(IPython.shadowns, name,cmd)
438 return
438 return
439
439
440 if isinstance(cmd,basestring):
440 if isinstance(cmd,basestring):
441 nargs = cmd.count('%s')
441 nargs = cmd.count('%s')
442 if nargs>0 and cmd.find('%l')>=0:
442 if nargs>0 and cmd.find('%l')>=0:
443 raise Exception('The %s and %l specifiers are mutually '
443 raise Exception('The %s and %l specifiers are mutually '
444 'exclusive in alias definitions.')
444 'exclusive in alias definitions.')
445
445
446 self.IP.alias_table[name] = (nargs,cmd)
446 self.IP.alias_table[name] = (nargs,cmd)
447 return
447 return
448
448
449 # just put it in - it's probably (0,'foo')
449 # just put it in - it's probably (0,'foo')
450 self.IP.alias_table[name] = cmd
450 self.IP.alias_table[name] = cmd
451
451
452 def defmacro(self, *args):
452 def defmacro(self, *args):
453 """ Define a new macro
453 """ Define a new macro
454
454
455 2 forms of calling:
455 2 forms of calling:
456
456
457 mac = _ip.defmacro('print "hello"\nprint "world"')
457 mac = _ip.defmacro('print "hello"\nprint "world"')
458
458
459 (doesn't put the created macro on user namespace)
459 (doesn't put the created macro on user namespace)
460
460
461 _ip.defmacro('build', 'bldmake bldfiles\nabld build winscw udeb')
461 _ip.defmacro('build', 'bldmake bldfiles\nabld build winscw udeb')
462
462
463 (creates a macro named 'build' in user namespace)
463 (creates a macro named 'build' in user namespace)
464 """
464 """
465
465
466 import IPython.macro
466 import IPython.macro
467
467
468 if len(args) == 1:
468 if len(args) == 1:
469 return IPython.macro.Macro(args[0])
469 return IPython.macro.Macro(args[0])
470 elif len(args) == 2:
470 elif len(args) == 2:
471 self.user_ns[args[0]] = IPython.macro.Macro(args[1])
471 self.user_ns[args[0]] = IPython.macro.Macro(args[1])
472 else:
472 else:
473 return Exception("_ip.defmacro must be called with 1 or 2 arguments")
473 return Exception("_ip.defmacro must be called with 1 or 2 arguments")
474
474
475 def set_next_input(self, s):
475 def set_next_input(self, s):
476 """ Sets the 'default' input string for the next command line.
476 """ Sets the 'default' input string for the next command line.
477
477
478 Requires readline.
478 Requires readline.
479
479
480 Example:
480 Example:
481
481
482 [D:\ipython]|1> _ip.set_next_input("Hello Word")
482 [D:\ipython]|1> _ip.set_next_input("Hello Word")
483 [D:\ipython]|2> Hello Word_ # cursor is here
483 [D:\ipython]|2> Hello Word_ # cursor is here
484 """
484 """
485
485
486 self.IP.rl_next_input = s
486 self.IP.rl_next_input = s
487
487
488 def load(self, mod):
488 def load(self, mod):
489 """ Load an extension.
489 """ Load an extension.
490
490
491 Some modules should (or must) be 'load()':ed, rather than just imported.
491 Some modules should (or must) be 'load()':ed, rather than just imported.
492
492
493 Loading will do:
493 Loading will do:
494
494
495 - run init_ipython(ip)
495 - run init_ipython(ip)
496 - run ipython_firstrun(ip)
496 - run ipython_firstrun(ip)
497 """
497 """
498
498
499 if mod in self.extensions:
499 if mod in self.extensions:
500 # just to make sure we don't init it twice
500 # just to make sure we don't init it twice
501 # note that if you 'load' a module that has already been
501 # note that if you 'load' a module that has already been
502 # imported, init_ipython gets run anyway
502 # imported, init_ipython gets run anyway
503
503
504 return self.extensions[mod]
504 return self.extensions[mod]
505 __import__(mod)
505 __import__(mod)
506 m = sys.modules[mod]
506 m = sys.modules[mod]
507 if hasattr(m,'init_ipython'):
507 if hasattr(m,'init_ipython'):
508 m.init_ipython(self)
508 m.init_ipython(self)
509
509
510 if hasattr(m,'ipython_firstrun'):
510 if hasattr(m,'ipython_firstrun'):
511 already_loaded = self.db.get('firstrun_done', set())
511 already_loaded = self.db.get('firstrun_done', set())
512 if mod not in already_loaded:
512 if mod not in already_loaded:
513 m.ipython_firstrun(self)
513 m.ipython_firstrun(self)
514 already_loaded.add(mod)
514 already_loaded.add(mod)
515 self.db['firstrun_done'] = already_loaded
515 self.db['firstrun_done'] = already_loaded
516
516
517 self.extensions[mod] = m
517 self.extensions[mod] = m
518 return m
518 return m
519
519
520
520
521 class DebugTools:
521 class DebugTools:
522 """ Used for debugging mishaps in api usage
522 """ Used for debugging mishaps in api usage
523
523
524 So far, tracing redefinitions is supported.
524 So far, tracing redefinitions is supported.
525 """
525 """
526
526
527 def __init__(self, ip):
527 def __init__(self, ip):
528 self.ip = ip
528 self.ip = ip
529 self.debugmode = False
529 self.debugmode = False
530 self.hotnames = set()
530 self.hotnames = set()
531
531
532 def hotname(self, name_to_catch):
532 def hotname(self, name_to_catch):
533 self.hotnames.add(name_to_catch)
533 self.hotnames.add(name_to_catch)
534
534
535 def debug_stack(self, msg = None):
535 def debug_stack(self, msg = None):
536 if not self.debugmode:
536 if not self.debugmode:
537 return
537 return
538
538
539 import traceback
539 import traceback
540 if msg is not None:
540 if msg is not None:
541 print '====== %s ========' % msg
541 print '====== %s ========' % msg
542 traceback.print_stack()
542 traceback.print_stack()
543
543
544 def check_hotname(self,name):
544 def check_hotname(self,name):
545 if name in self.hotnames:
545 if name in self.hotnames:
546 self.debug_stack( "HotName '%s' caught" % name)
546 self.debug_stack( "HotName '%s' caught" % name)
547
547
548
548
549 def launch_new_instance(user_ns = None,shellclass = None):
549 def launch_new_instance(user_ns = None,shellclass = None):
550 """ Make and start a new ipython instance.
550 """ Make and start a new ipython instance.
551
551
552 This can be called even without having an already initialized
552 This can be called even without having an already initialized
553 ipython session running.
553 ipython session running.
554
554
555 This is also used as the egg entry point for the 'ipython' script.
555 This is also used as the egg entry point for the 'ipython' script.
556
556
557 """
557 """
558 ses = make_session(user_ns,shellclass)
558 ses = make_session(user_ns,shellclass)
559 ses.mainloop()
559 ses.mainloop()
560
560
561
561
562 def make_user_ns(user_ns = None):
562 def make_user_ns(user_ns = None):
563 """Return a valid user interactive namespace.
563 """Return a valid user interactive namespace.
564
564
565 This builds a dict with the minimal information needed to operate as a
565 This builds a dict with the minimal information needed to operate as a
566 valid IPython user namespace, which you can pass to the various embedding
566 valid IPython user namespace, which you can pass to the various embedding
567 classes in ipython.
567 classes in ipython.
568 """
568 """
569
569
570 if user_ns is None:
570 raise NotImplementedError
571 # Set __name__ to __main__ to better match the behavior of the
572 # normal interpreter.
573 user_ns = {'__name__' :'__main__',
574 '__builtins__' : __builtin__,
575 }
576 else:
577 user_ns.setdefault('__name__','__main__')
578 user_ns.setdefault('__builtins__',__builtin__)
579
580 return user_ns
581
571
582
572
583 def make_user_global_ns(ns = None):
573 def make_user_global_ns(ns = None):
584 """Return a valid user global namespace.
574 """Return a valid user global namespace.
585
575
586 Similar to make_user_ns(), but global namespaces are really only needed in
576 Similar to make_user_ns(), but global namespaces are really only needed in
587 embedded applications, where there is a distinction between the user's
577 embedded applications, where there is a distinction between the user's
588 interactive namespace and the global one where ipython is running."""
578 interactive namespace and the global one where ipython is running."""
589
579
590 if ns is None: ns = {}
580 raise NotImplementedError
591 return ns
581
582 # Record the true objects in order to be able to test if the user has overridden
583 # these API functions.
584 _make_user_ns = make_user_ns
585 _make_user_global_ns = make_user_global_ns
586
587
588 def make_user_namespaces(user_ns = None,user_global_ns = None):
589 """Return a valid local and global user interactive namespaces.
590
591 This builds a dict with the minimal information needed to operate as a
592 valid IPython user namespace, which you can pass to the various embedding
593 classes in ipython. The default implementation returns the same dict for
594 both the locals and the globals to allow functions to refer to variables in
595 the namespace. Customized implementations can return different dicts. The
596 locals dictionary can actually be anything following the basic mapping
597 protocol of a dict, but the globals dict must be a true dict, not even
598 a subclass. It is recommended that any custom object for the locals
599 namespace synchronize with the globals dict somehow.
600
601 Raises TypeError if the provided globals namespace is not a true dict.
602 """
603
604 if user_ns is None:
605 if make_user_ns is not _make_user_ns:
606 # Old API overridden.
607 # FIXME: Issue DeprecationWarning, or just let the old API live on?
608 user_ns = make_user_ns(user_ns)
609 else:
610 # Set __name__ to __main__ to better match the behavior of the
611 # normal interpreter.
612 user_ns = {'__name__' :'__main__',
613 '__builtins__' : __builtin__,
614 }
615 else:
616 user_ns.setdefault('__name__','__main__')
617 user_ns.setdefault('__builtins__',__builtin__)
618
619 if user_global_ns is None:
620 if make_user_global_ns is not _make_user_global_ns:
621 # Old API overridden.
622 user_global_ns = make_user_global_ns(user_global_ns)
623 else:
624 user_global_ns = user_ns
625 if type(user_global_ns) is not dict:
626 raise TypeError("user_global_ns must be a true dict; got %r"
627 % type(user_global_ns))
628
629 return user_ns, user_global_ns
592
630
593
631
594 def make_session(user_ns = None, shellclass = None):
632 def make_session(user_ns = None, shellclass = None):
595 """Makes, but does not launch an IPython session.
633 """Makes, but does not launch an IPython session.
596
634
597 Later on you can call obj.mainloop() on the returned object.
635 Later on you can call obj.mainloop() on the returned object.
598
636
599 Inputs:
637 Inputs:
600
638
601 - user_ns(None): a dict to be used as the user's namespace with initial
639 - user_ns(None): a dict to be used as the user's namespace with initial
602 data.
640 data.
603
641
604 WARNING: This should *not* be run when a session exists already."""
642 WARNING: This should *not* be run when a session exists already."""
605
643
606 import IPython.Shell
644 import IPython.Shell
607 if shellclass is None:
645 if shellclass is None:
608 return IPython.Shell.start(user_ns)
646 return IPython.Shell.start(user_ns)
609 return shellclass(user_ns = user_ns)
647 return shellclass(user_ns = user_ns)
@@ -1,2691 +1,2681 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.3 or newer.
5 Requires Python 2.3 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 #*****************************************************************************
11 #*****************************************************************************
12 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
12 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
13 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
13 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
14 #
14 #
15 # Distributed under the terms of the BSD License. The full license is in
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
16 # the file COPYING, distributed as part of this software.
17 #
17 #
18 # Note: this code originally subclassed code.InteractiveConsole from the
18 # Note: this code originally subclassed code.InteractiveConsole from the
19 # Python standard library. Over time, all of that class has been copied
19 # Python standard library. Over time, all of that class has been copied
20 # verbatim here for modifications which could not be accomplished by
20 # verbatim here for modifications which could not be accomplished by
21 # subclassing. At this point, there are no dependencies at all on the code
21 # subclassing. At this point, there are no dependencies at all on the code
22 # module anymore (it is not even imported). The Python License (sec. 2)
22 # module anymore (it is not even imported). The Python License (sec. 2)
23 # allows for this, but it's always nice to acknowledge credit where credit is
23 # allows for this, but it's always nice to acknowledge credit where credit is
24 # due.
24 # due.
25 #*****************************************************************************
25 #*****************************************************************************
26
26
27 #****************************************************************************
27 #****************************************************************************
28 # Modules and globals
28 # Modules and globals
29
29
30 from IPython import Release
30 from IPython import Release
31 __author__ = '%s <%s>\n%s <%s>' % \
31 __author__ = '%s <%s>\n%s <%s>' % \
32 ( Release.authors['Janko'] + Release.authors['Fernando'] )
32 ( Release.authors['Janko'] + Release.authors['Fernando'] )
33 __license__ = Release.license
33 __license__ = Release.license
34 __version__ = Release.version
34 __version__ = Release.version
35
35
36 # Python standard modules
36 # Python standard modules
37 import __main__
37 import __main__
38 import __builtin__
38 import __builtin__
39 import StringIO
39 import StringIO
40 import bdb
40 import bdb
41 import cPickle as pickle
41 import cPickle as pickle
42 import codeop
42 import codeop
43 import exceptions
43 import exceptions
44 import glob
44 import glob
45 import inspect
45 import inspect
46 import keyword
46 import keyword
47 import new
47 import new
48 import os
48 import os
49 import pydoc
49 import pydoc
50 import re
50 import re
51 import shutil
51 import shutil
52 import string
52 import string
53 import sys
53 import sys
54 import tempfile
54 import tempfile
55 import traceback
55 import traceback
56 import types
56 import types
57 import warnings
57 import warnings
58 warnings.filterwarnings('ignore', r'.*sets module*')
58 warnings.filterwarnings('ignore', r'.*sets module*')
59 from sets import Set
59 from sets import Set
60 from pprint import pprint, pformat
60 from pprint import pprint, pformat
61
61
62 # IPython's own modules
62 # IPython's own modules
63 #import IPython
63 #import IPython
64 from IPython import Debugger,OInspect,PyColorize,ultraTB
64 from IPython import Debugger,OInspect,PyColorize,ultraTB
65 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
65 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
66 from IPython.Extensions import pickleshare
66 from IPython.Extensions import pickleshare
67 from IPython.FakeModule import FakeModule
67 from IPython.FakeModule import FakeModule
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
69 from IPython.Logger import Logger
69 from IPython.Logger import Logger
70 from IPython.Magic import Magic
70 from IPython.Magic import Magic
71 from IPython.Prompts import CachedOutput
71 from IPython.Prompts import CachedOutput
72 from IPython.ipstruct import Struct
72 from IPython.ipstruct import Struct
73 from IPython.background_jobs import BackgroundJobManager
73 from IPython.background_jobs import BackgroundJobManager
74 from IPython.usage import cmd_line_usage,interactive_usage
74 from IPython.usage import cmd_line_usage,interactive_usage
75 from IPython.genutils import *
75 from IPython.genutils import *
76 from IPython.strdispatch import StrDispatch
76 from IPython.strdispatch import StrDispatch
77 import IPython.ipapi
77 import IPython.ipapi
78 import IPython.history
78 import IPython.history
79 import IPython.prefilter as prefilter
79 import IPython.prefilter as prefilter
80 import IPython.shadowns
80 import IPython.shadowns
81 # Globals
81 # Globals
82
82
83 # store the builtin raw_input globally, and use this always, in case user code
83 # store the builtin raw_input globally, and use this always, in case user code
84 # overwrites it (like wx.py.PyShell does)
84 # overwrites it (like wx.py.PyShell does)
85 raw_input_original = raw_input
85 raw_input_original = raw_input
86
86
87 # compiled regexps for autoindent management
87 # compiled regexps for autoindent management
88 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
88 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
89
89
90
90
91 #****************************************************************************
91 #****************************************************************************
92 # Some utility function definitions
92 # Some utility function definitions
93
93
94 ini_spaces_re = re.compile(r'^(\s+)')
94 ini_spaces_re = re.compile(r'^(\s+)')
95
95
96 def num_ini_spaces(strng):
96 def num_ini_spaces(strng):
97 """Return the number of initial spaces in a string"""
97 """Return the number of initial spaces in a string"""
98
98
99 ini_spaces = ini_spaces_re.match(strng)
99 ini_spaces = ini_spaces_re.match(strng)
100 if ini_spaces:
100 if ini_spaces:
101 return ini_spaces.end()
101 return ini_spaces.end()
102 else:
102 else:
103 return 0
103 return 0
104
104
105 def softspace(file, newvalue):
105 def softspace(file, newvalue):
106 """Copied from code.py, to remove the dependency"""
106 """Copied from code.py, to remove the dependency"""
107
107
108 oldvalue = 0
108 oldvalue = 0
109 try:
109 try:
110 oldvalue = file.softspace
110 oldvalue = file.softspace
111 except AttributeError:
111 except AttributeError:
112 pass
112 pass
113 try:
113 try:
114 file.softspace = newvalue
114 file.softspace = newvalue
115 except (AttributeError, TypeError):
115 except (AttributeError, TypeError):
116 # "attribute-less object" or "read-only attributes"
116 # "attribute-less object" or "read-only attributes"
117 pass
117 pass
118 return oldvalue
118 return oldvalue
119
119
120
120
121 #****************************************************************************
121 #****************************************************************************
122 # Local use exceptions
122 # Local use exceptions
123 class SpaceInInput(exceptions.Exception): pass
123 class SpaceInInput(exceptions.Exception): pass
124
124
125
125
126 #****************************************************************************
126 #****************************************************************************
127 # Local use classes
127 # Local use classes
128 class Bunch: pass
128 class Bunch: pass
129
129
130 class Undefined: pass
130 class Undefined: pass
131
131
132 class Quitter(object):
132 class Quitter(object):
133 """Simple class to handle exit, similar to Python 2.5's.
133 """Simple class to handle exit, similar to Python 2.5's.
134
134
135 It handles exiting in an ipython-safe manner, which the one in Python 2.5
135 It handles exiting in an ipython-safe manner, which the one in Python 2.5
136 doesn't do (obviously, since it doesn't know about ipython)."""
136 doesn't do (obviously, since it doesn't know about ipython)."""
137
137
138 def __init__(self,shell,name):
138 def __init__(self,shell,name):
139 self.shell = shell
139 self.shell = shell
140 self.name = name
140 self.name = name
141
141
142 def __repr__(self):
142 def __repr__(self):
143 return 'Type %s() to exit.' % self.name
143 return 'Type %s() to exit.' % self.name
144 __str__ = __repr__
144 __str__ = __repr__
145
145
146 def __call__(self):
146 def __call__(self):
147 self.shell.exit()
147 self.shell.exit()
148
148
149 class InputList(list):
149 class InputList(list):
150 """Class to store user input.
150 """Class to store user input.
151
151
152 It's basically a list, but slices return a string instead of a list, thus
152 It's basically a list, but slices return a string instead of a list, thus
153 allowing things like (assuming 'In' is an instance):
153 allowing things like (assuming 'In' is an instance):
154
154
155 exec In[4:7]
155 exec In[4:7]
156
156
157 or
157 or
158
158
159 exec In[5:9] + In[14] + In[21:25]"""
159 exec In[5:9] + In[14] + In[21:25]"""
160
160
161 def __getslice__(self,i,j):
161 def __getslice__(self,i,j):
162 return ''.join(list.__getslice__(self,i,j))
162 return ''.join(list.__getslice__(self,i,j))
163
163
164 class SyntaxTB(ultraTB.ListTB):
164 class SyntaxTB(ultraTB.ListTB):
165 """Extension which holds some state: the last exception value"""
165 """Extension which holds some state: the last exception value"""
166
166
167 def __init__(self,color_scheme = 'NoColor'):
167 def __init__(self,color_scheme = 'NoColor'):
168 ultraTB.ListTB.__init__(self,color_scheme)
168 ultraTB.ListTB.__init__(self,color_scheme)
169 self.last_syntax_error = None
169 self.last_syntax_error = None
170
170
171 def __call__(self, etype, value, elist):
171 def __call__(self, etype, value, elist):
172 self.last_syntax_error = value
172 self.last_syntax_error = value
173 ultraTB.ListTB.__call__(self,etype,value,elist)
173 ultraTB.ListTB.__call__(self,etype,value,elist)
174
174
175 def clear_err_state(self):
175 def clear_err_state(self):
176 """Return the current error state and clear it"""
176 """Return the current error state and clear it"""
177 e = self.last_syntax_error
177 e = self.last_syntax_error
178 self.last_syntax_error = None
178 self.last_syntax_error = None
179 return e
179 return e
180
180
181 #****************************************************************************
181 #****************************************************************************
182 # Main IPython class
182 # Main IPython class
183
183
184 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
184 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
185 # until a full rewrite is made. I've cleaned all cross-class uses of
185 # until a full rewrite is made. I've cleaned all cross-class uses of
186 # attributes and methods, but too much user code out there relies on the
186 # attributes and methods, but too much user code out there relies on the
187 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
187 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
188 #
188 #
189 # But at least now, all the pieces have been separated and we could, in
189 # But at least now, all the pieces have been separated and we could, in
190 # principle, stop using the mixin. This will ease the transition to the
190 # principle, stop using the mixin. This will ease the transition to the
191 # chainsaw branch.
191 # chainsaw branch.
192
192
193 # For reference, the following is the list of 'self.foo' uses in the Magic
193 # For reference, the following is the list of 'self.foo' uses in the Magic
194 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
194 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
195 # class, to prevent clashes.
195 # class, to prevent clashes.
196
196
197 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
197 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
198 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
198 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
199 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
199 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
200 # 'self.value']
200 # 'self.value']
201
201
202 class InteractiveShell(object,Magic):
202 class InteractiveShell(object,Magic):
203 """An enhanced console for Python."""
203 """An enhanced console for Python."""
204
204
205 # class attribute to indicate whether the class supports threads or not.
205 # class attribute to indicate whether the class supports threads or not.
206 # Subclasses with thread support should override this as needed.
206 # Subclasses with thread support should override this as needed.
207 isthreaded = False
207 isthreaded = False
208
208
209 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
209 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
210 user_ns = None,user_global_ns=None,banner2='',
210 user_ns=None,user_global_ns=None,banner2='',
211 custom_exceptions=((),None),embedded=False):
211 custom_exceptions=((),None),embedded=False):
212
212
213 # log system
213 # log system
214 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
214 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
215
215
216 # Job manager (for jobs run as background threads)
216 # Job manager (for jobs run as background threads)
217 self.jobs = BackgroundJobManager()
217 self.jobs = BackgroundJobManager()
218
218
219 # Store the actual shell's name
219 # Store the actual shell's name
220 self.name = name
220 self.name = name
221 self.more = False
221 self.more = False
222
222
223 # We need to know whether the instance is meant for embedding, since
223 # We need to know whether the instance is meant for embedding, since
224 # global/local namespaces need to be handled differently in that case
224 # global/local namespaces need to be handled differently in that case
225 self.embedded = embedded
225 self.embedded = embedded
226 if embedded:
226 if embedded:
227 # Control variable so users can, from within the embedded instance,
227 # Control variable so users can, from within the embedded instance,
228 # permanently deactivate it.
228 # permanently deactivate it.
229 self.embedded_active = True
229 self.embedded_active = True
230
230
231 # command compiler
231 # command compiler
232 self.compile = codeop.CommandCompiler()
232 self.compile = codeop.CommandCompiler()
233
233
234 # User input buffer
234 # User input buffer
235 self.buffer = []
235 self.buffer = []
236
236
237 # Default name given in compilation of code
237 # Default name given in compilation of code
238 self.filename = '<ipython console>'
238 self.filename = '<ipython console>'
239
239
240 # Install our own quitter instead of the builtins. For python2.3-2.4,
240 # Install our own quitter instead of the builtins. For python2.3-2.4,
241 # this brings in behavior like 2.5, and for 2.5 it's identical.
241 # this brings in behavior like 2.5, and for 2.5 it's identical.
242 __builtin__.exit = Quitter(self,'exit')
242 __builtin__.exit = Quitter(self,'exit')
243 __builtin__.quit = Quitter(self,'quit')
243 __builtin__.quit = Quitter(self,'quit')
244
244
245 # Make an empty namespace, which extension writers can rely on both
245 # Make an empty namespace, which extension writers can rely on both
246 # existing and NEVER being used by ipython itself. This gives them a
246 # existing and NEVER being used by ipython itself. This gives them a
247 # convenient location for storing additional information and state
247 # convenient location for storing additional information and state
248 # their extensions may require, without fear of collisions with other
248 # their extensions may require, without fear of collisions with other
249 # ipython names that may develop later.
249 # ipython names that may develop later.
250 self.meta = Struct()
250 self.meta = Struct()
251
251
252 # Create the namespace where the user will operate. user_ns is
252 # Create the namespace where the user will operate. user_ns is
253 # normally the only one used, and it is passed to the exec calls as
253 # normally the only one used, and it is passed to the exec calls as
254 # the locals argument. But we do carry a user_global_ns namespace
254 # the locals argument. But we do carry a user_global_ns namespace
255 # given as the exec 'globals' argument, This is useful in embedding
255 # given as the exec 'globals' argument, This is useful in embedding
256 # situations where the ipython shell opens in a context where the
256 # situations where the ipython shell opens in a context where the
257 # distinction between locals and globals is meaningful.
257 # distinction between locals and globals is meaningful. For
258 # non-embedded contexts, it is just the same object as the user_ns dict.
258
259
259 # FIXME. For some strange reason, __builtins__ is showing up at user
260 # FIXME. For some strange reason, __builtins__ is showing up at user
260 # level as a dict instead of a module. This is a manual fix, but I
261 # level as a dict instead of a module. This is a manual fix, but I
261 # should really track down where the problem is coming from. Alex
262 # should really track down where the problem is coming from. Alex
262 # Schmolck reported this problem first.
263 # Schmolck reported this problem first.
263
264
264 # A useful post by Alex Martelli on this topic:
265 # A useful post by Alex Martelli on this topic:
265 # Re: inconsistent value from __builtins__
266 # Re: inconsistent value from __builtins__
266 # Von: Alex Martelli <aleaxit@yahoo.com>
267 # Von: Alex Martelli <aleaxit@yahoo.com>
267 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
268 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
268 # Gruppen: comp.lang.python
269 # Gruppen: comp.lang.python
269
270
270 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
271 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
271 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
272 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
272 # > <type 'dict'>
273 # > <type 'dict'>
273 # > >>> print type(__builtins__)
274 # > >>> print type(__builtins__)
274 # > <type 'module'>
275 # > <type 'module'>
275 # > Is this difference in return value intentional?
276 # > Is this difference in return value intentional?
276
277
277 # Well, it's documented that '__builtins__' can be either a dictionary
278 # Well, it's documented that '__builtins__' can be either a dictionary
278 # or a module, and it's been that way for a long time. Whether it's
279 # or a module, and it's been that way for a long time. Whether it's
279 # intentional (or sensible), I don't know. In any case, the idea is
280 # intentional (or sensible), I don't know. In any case, the idea is
280 # that if you need to access the built-in namespace directly, you
281 # that if you need to access the built-in namespace directly, you
281 # should start with "import __builtin__" (note, no 's') which will
282 # should start with "import __builtin__" (note, no 's') which will
282 # definitely give you a module. Yeah, it's somewhat confusing:-(.
283 # definitely give you a module. Yeah, it's somewhat confusing:-(.
283
284
284 # These routines return properly built dicts as needed by the rest of
285 # These routines return properly built dicts as needed by the rest of
285 # the code, and can also be used by extension writers to generate
286 # the code, and can also be used by extension writers to generate
286 # properly initialized namespaces.
287 # properly initialized namespaces.
287 user_ns = IPython.ipapi.make_user_ns(user_ns)
288 user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns,
288 user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns)
289 user_global_ns)
289
290
290 # Assign namespaces
291 # Assign namespaces
291 # This is the namespace where all normal user variables live
292 # This is the namespace where all normal user variables live
292 self.user_ns = user_ns
293 self.user_ns = user_ns
293 # Embedded instances require a separate namespace for globals.
294 # Normally this one is unused by non-embedded instances.
295 self.user_global_ns = user_global_ns
294 self.user_global_ns = user_global_ns
296 # A namespace to keep track of internal data structures to prevent
295 # A namespace to keep track of internal data structures to prevent
297 # them from cluttering user-visible stuff. Will be updated later
296 # them from cluttering user-visible stuff. Will be updated later
298 self.internal_ns = {}
297 self.internal_ns = {}
299
298
300 # Namespace of system aliases. Each entry in the alias
299 # Namespace of system aliases. Each entry in the alias
301 # table must be a 2-tuple of the form (N,name), where N is the number
300 # table must be a 2-tuple of the form (N,name), where N is the number
302 # of positional arguments of the alias.
301 # of positional arguments of the alias.
303 self.alias_table = {}
302 self.alias_table = {}
304
303
305 # A table holding all the namespaces IPython deals with, so that
304 # A table holding all the namespaces IPython deals with, so that
306 # introspection facilities can search easily.
305 # introspection facilities can search easily.
307 self.ns_table = {'user':user_ns,
306 self.ns_table = {'user':user_ns,
308 'user_global':user_global_ns,
307 'user_global':user_global_ns,
309 'alias':self.alias_table,
308 'alias':self.alias_table,
310 'internal':self.internal_ns,
309 'internal':self.internal_ns,
311 'builtin':__builtin__.__dict__
310 'builtin':__builtin__.__dict__
312 }
311 }
313 # The user namespace MUST have a pointer to the shell itself.
312 # The user namespace MUST have a pointer to the shell itself.
314 self.user_ns[name] = self
313 self.user_ns[name] = self
315
314
316 # We need to insert into sys.modules something that looks like a
315 # We need to insert into sys.modules something that looks like a
317 # module but which accesses the IPython namespace, for shelve and
316 # module but which accesses the IPython namespace, for shelve and
318 # pickle to work interactively. Normally they rely on getting
317 # pickle to work interactively. Normally they rely on getting
319 # everything out of __main__, but for embedding purposes each IPython
318 # everything out of __main__, but for embedding purposes each IPython
320 # instance has its own private namespace, so we can't go shoving
319 # instance has its own private namespace, so we can't go shoving
321 # everything into __main__.
320 # everything into __main__.
322
321
323 # note, however, that we should only do this for non-embedded
322 # note, however, that we should only do this for non-embedded
324 # ipythons, which really mimic the __main__.__dict__ with their own
323 # ipythons, which really mimic the __main__.__dict__ with their own
325 # namespace. Embedded instances, on the other hand, should not do
324 # namespace. Embedded instances, on the other hand, should not do
326 # this because they need to manage the user local/global namespaces
325 # this because they need to manage the user local/global namespaces
327 # only, but they live within a 'normal' __main__ (meaning, they
326 # only, but they live within a 'normal' __main__ (meaning, they
328 # shouldn't overtake the execution environment of the script they're
327 # shouldn't overtake the execution environment of the script they're
329 # embedded in).
328 # embedded in).
330
329
331 if not embedded:
330 if not embedded:
332 try:
331 try:
333 main_name = self.user_ns['__name__']
332 main_name = self.user_ns['__name__']
334 except KeyError:
333 except KeyError:
335 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
334 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
336 else:
335 else:
337 #print "pickle hack in place" # dbg
336 #print "pickle hack in place" # dbg
338 #print 'main_name:',main_name # dbg
337 #print 'main_name:',main_name # dbg
339 sys.modules[main_name] = FakeModule(self.user_ns)
338 sys.modules[main_name] = FakeModule(self.user_ns)
340
339
341 # Now that FakeModule produces a real module, we've run into a nasty
340 # Now that FakeModule produces a real module, we've run into a nasty
342 # problem: after script execution (via %run), the module where the user
341 # problem: after script execution (via %run), the module where the user
343 # code ran is deleted. Now that this object is a true module (needed
342 # code ran is deleted. Now that this object is a true module (needed
344 # so docetst and other tools work correctly), the Python module
343 # so docetst and other tools work correctly), the Python module
345 # teardown mechanism runs over it, and sets to None every variable
344 # teardown mechanism runs over it, and sets to None every variable
346 # present in that module. This means that later calls to functions
345 # present in that module. This means that later calls to functions
347 # defined in the script (which have become interactively visible after
346 # defined in the script (which have become interactively visible after
348 # script exit) fail, because they hold references to objects that have
347 # script exit) fail, because they hold references to objects that have
349 # become overwritten into None. The only solution I see right now is
348 # become overwritten into None. The only solution I see right now is
350 # to protect every FakeModule used by %run by holding an internal
349 # to protect every FakeModule used by %run by holding an internal
351 # reference to it. This private list will be used for that. The
350 # reference to it. This private list will be used for that. The
352 # %reset command will flush it as well.
351 # %reset command will flush it as well.
353 self._user_main_modules = []
352 self._user_main_modules = []
354
353
355 # List of input with multi-line handling.
354 # List of input with multi-line handling.
356 # Fill its zero entry, user counter starts at 1
355 # Fill its zero entry, user counter starts at 1
357 self.input_hist = InputList(['\n'])
356 self.input_hist = InputList(['\n'])
358 # This one will hold the 'raw' input history, without any
357 # This one will hold the 'raw' input history, without any
359 # pre-processing. This will allow users to retrieve the input just as
358 # pre-processing. This will allow users to retrieve the input just as
360 # it was exactly typed in by the user, with %hist -r.
359 # it was exactly typed in by the user, with %hist -r.
361 self.input_hist_raw = InputList(['\n'])
360 self.input_hist_raw = InputList(['\n'])
362
361
363 # list of visited directories
362 # list of visited directories
364 try:
363 try:
365 self.dir_hist = [os.getcwd()]
364 self.dir_hist = [os.getcwd()]
366 except OSError:
365 except OSError:
367 self.dir_hist = []
366 self.dir_hist = []
368
367
369 # dict of output history
368 # dict of output history
370 self.output_hist = {}
369 self.output_hist = {}
371
370
372 # Get system encoding at startup time. Certain terminals (like Emacs
371 # Get system encoding at startup time. Certain terminals (like Emacs
373 # under Win32 have it set to None, and we need to have a known valid
372 # under Win32 have it set to None, and we need to have a known valid
374 # encoding to use in the raw_input() method
373 # encoding to use in the raw_input() method
375 try:
374 try:
376 self.stdin_encoding = sys.stdin.encoding or 'ascii'
375 self.stdin_encoding = sys.stdin.encoding or 'ascii'
377 except AttributeError:
376 except AttributeError:
378 self.stdin_encoding = 'ascii'
377 self.stdin_encoding = 'ascii'
379
378
380 # dict of things NOT to alias (keywords, builtins and some magics)
379 # dict of things NOT to alias (keywords, builtins and some magics)
381 no_alias = {}
380 no_alias = {}
382 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
381 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
383 for key in keyword.kwlist + no_alias_magics:
382 for key in keyword.kwlist + no_alias_magics:
384 no_alias[key] = 1
383 no_alias[key] = 1
385 no_alias.update(__builtin__.__dict__)
384 no_alias.update(__builtin__.__dict__)
386 self.no_alias = no_alias
385 self.no_alias = no_alias
387
386
388 # make global variables for user access to these
387 # make global variables for user access to these
389 self.user_ns['_ih'] = self.input_hist
388 self.user_ns['_ih'] = self.input_hist
390 self.user_ns['_oh'] = self.output_hist
389 self.user_ns['_oh'] = self.output_hist
391 self.user_ns['_dh'] = self.dir_hist
390 self.user_ns['_dh'] = self.dir_hist
392
391
393 # user aliases to input and output histories
392 # user aliases to input and output histories
394 self.user_ns['In'] = self.input_hist
393 self.user_ns['In'] = self.input_hist
395 self.user_ns['Out'] = self.output_hist
394 self.user_ns['Out'] = self.output_hist
396
395
397 self.user_ns['_sh'] = IPython.shadowns
396 self.user_ns['_sh'] = IPython.shadowns
398 # Object variable to store code object waiting execution. This is
397 # Object variable to store code object waiting execution. This is
399 # used mainly by the multithreaded shells, but it can come in handy in
398 # used mainly by the multithreaded shells, but it can come in handy in
400 # other situations. No need to use a Queue here, since it's a single
399 # other situations. No need to use a Queue here, since it's a single
401 # item which gets cleared once run.
400 # item which gets cleared once run.
402 self.code_to_run = None
401 self.code_to_run = None
403
402
404 # escapes for automatic behavior on the command line
403 # escapes for automatic behavior on the command line
405 self.ESC_SHELL = '!'
404 self.ESC_SHELL = '!'
406 self.ESC_SH_CAP = '!!'
405 self.ESC_SH_CAP = '!!'
407 self.ESC_HELP = '?'
406 self.ESC_HELP = '?'
408 self.ESC_MAGIC = '%'
407 self.ESC_MAGIC = '%'
409 self.ESC_QUOTE = ','
408 self.ESC_QUOTE = ','
410 self.ESC_QUOTE2 = ';'
409 self.ESC_QUOTE2 = ';'
411 self.ESC_PAREN = '/'
410 self.ESC_PAREN = '/'
412
411
413 # And their associated handlers
412 # And their associated handlers
414 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
413 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
415 self.ESC_QUOTE : self.handle_auto,
414 self.ESC_QUOTE : self.handle_auto,
416 self.ESC_QUOTE2 : self.handle_auto,
415 self.ESC_QUOTE2 : self.handle_auto,
417 self.ESC_MAGIC : self.handle_magic,
416 self.ESC_MAGIC : self.handle_magic,
418 self.ESC_HELP : self.handle_help,
417 self.ESC_HELP : self.handle_help,
419 self.ESC_SHELL : self.handle_shell_escape,
418 self.ESC_SHELL : self.handle_shell_escape,
420 self.ESC_SH_CAP : self.handle_shell_escape,
419 self.ESC_SH_CAP : self.handle_shell_escape,
421 }
420 }
422
421
423 # class initializations
422 # class initializations
424 Magic.__init__(self,self)
423 Magic.__init__(self,self)
425
424
426 # Python source parser/formatter for syntax highlighting
425 # Python source parser/formatter for syntax highlighting
427 pyformat = PyColorize.Parser().format
426 pyformat = PyColorize.Parser().format
428 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
427 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
429
428
430 # hooks holds pointers used for user-side customizations
429 # hooks holds pointers used for user-side customizations
431 self.hooks = Struct()
430 self.hooks = Struct()
432
431
433 self.strdispatchers = {}
432 self.strdispatchers = {}
434
433
435 # Set all default hooks, defined in the IPython.hooks module.
434 # Set all default hooks, defined in the IPython.hooks module.
436 hooks = IPython.hooks
435 hooks = IPython.hooks
437 for hook_name in hooks.__all__:
436 for hook_name in hooks.__all__:
438 # default hooks have priority 100, i.e. low; user hooks should have
437 # default hooks have priority 100, i.e. low; user hooks should have
439 # 0-100 priority
438 # 0-100 priority
440 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
439 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
441 #print "bound hook",hook_name
440 #print "bound hook",hook_name
442
441
443 # Flag to mark unconditional exit
442 # Flag to mark unconditional exit
444 self.exit_now = False
443 self.exit_now = False
445
444
446 self.usage_min = """\
445 self.usage_min = """\
447 An enhanced console for Python.
446 An enhanced console for Python.
448 Some of its features are:
447 Some of its features are:
449 - Readline support if the readline library is present.
448 - Readline support if the readline library is present.
450 - Tab completion in the local namespace.
449 - Tab completion in the local namespace.
451 - Logging of input, see command-line options.
450 - Logging of input, see command-line options.
452 - System shell escape via ! , eg !ls.
451 - System shell escape via ! , eg !ls.
453 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
452 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
454 - Keeps track of locally defined variables via %who, %whos.
453 - Keeps track of locally defined variables via %who, %whos.
455 - Show object information with a ? eg ?x or x? (use ?? for more info).
454 - Show object information with a ? eg ?x or x? (use ?? for more info).
456 """
455 """
457 if usage: self.usage = usage
456 if usage: self.usage = usage
458 else: self.usage = self.usage_min
457 else: self.usage = self.usage_min
459
458
460 # Storage
459 # Storage
461 self.rc = rc # This will hold all configuration information
460 self.rc = rc # This will hold all configuration information
462 self.pager = 'less'
461 self.pager = 'less'
463 # temporary files used for various purposes. Deleted at exit.
462 # temporary files used for various purposes. Deleted at exit.
464 self.tempfiles = []
463 self.tempfiles = []
465
464
466 # Keep track of readline usage (later set by init_readline)
465 # Keep track of readline usage (later set by init_readline)
467 self.has_readline = False
466 self.has_readline = False
468
467
469 # template for logfile headers. It gets resolved at runtime by the
468 # template for logfile headers. It gets resolved at runtime by the
470 # logstart method.
469 # logstart method.
471 self.loghead_tpl = \
470 self.loghead_tpl = \
472 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
471 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
473 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
472 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
474 #log# opts = %s
473 #log# opts = %s
475 #log# args = %s
474 #log# args = %s
476 #log# It is safe to make manual edits below here.
475 #log# It is safe to make manual edits below here.
477 #log#-----------------------------------------------------------------------
476 #log#-----------------------------------------------------------------------
478 """
477 """
479 # for pushd/popd management
478 # for pushd/popd management
480 try:
479 try:
481 self.home_dir = get_home_dir()
480 self.home_dir = get_home_dir()
482 except HomeDirError,msg:
481 except HomeDirError,msg:
483 fatal(msg)
482 fatal(msg)
484
483
485 self.dir_stack = []
484 self.dir_stack = []
486
485
487 # Functions to call the underlying shell.
486 # Functions to call the underlying shell.
488
487
489 # The first is similar to os.system, but it doesn't return a value,
488 # The first is similar to os.system, but it doesn't return a value,
490 # and it allows interpolation of variables in the user's namespace.
489 # and it allows interpolation of variables in the user's namespace.
491 self.system = lambda cmd: \
490 self.system = lambda cmd: \
492 self.hooks.shell_hook(self.var_expand(cmd,depth=2))
491 self.hooks.shell_hook(self.var_expand(cmd,depth=2))
493
492
494 # These are for getoutput and getoutputerror:
493 # These are for getoutput and getoutputerror:
495 self.getoutput = lambda cmd: \
494 self.getoutput = lambda cmd: \
496 getoutput(self.var_expand(cmd,depth=2),
495 getoutput(self.var_expand(cmd,depth=2),
497 header=self.rc.system_header,
496 header=self.rc.system_header,
498 verbose=self.rc.system_verbose)
497 verbose=self.rc.system_verbose)
499
498
500 self.getoutputerror = lambda cmd: \
499 self.getoutputerror = lambda cmd: \
501 getoutputerror(self.var_expand(cmd,depth=2),
500 getoutputerror(self.var_expand(cmd,depth=2),
502 header=self.rc.system_header,
501 header=self.rc.system_header,
503 verbose=self.rc.system_verbose)
502 verbose=self.rc.system_verbose)
504
503
505
504
506 # keep track of where we started running (mainly for crash post-mortem)
505 # keep track of where we started running (mainly for crash post-mortem)
507 self.starting_dir = os.getcwd()
506 self.starting_dir = os.getcwd()
508
507
509 # Various switches which can be set
508 # Various switches which can be set
510 self.CACHELENGTH = 5000 # this is cheap, it's just text
509 self.CACHELENGTH = 5000 # this is cheap, it's just text
511 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
510 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
512 self.banner2 = banner2
511 self.banner2 = banner2
513
512
514 # TraceBack handlers:
513 # TraceBack handlers:
515
514
516 # Syntax error handler.
515 # Syntax error handler.
517 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
516 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
518
517
519 # The interactive one is initialized with an offset, meaning we always
518 # The interactive one is initialized with an offset, meaning we always
520 # want to remove the topmost item in the traceback, which is our own
519 # want to remove the topmost item in the traceback, which is our own
521 # internal code. Valid modes: ['Plain','Context','Verbose']
520 # internal code. Valid modes: ['Plain','Context','Verbose']
522 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
521 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
523 color_scheme='NoColor',
522 color_scheme='NoColor',
524 tb_offset = 1)
523 tb_offset = 1)
525
524
526 # IPython itself shouldn't crash. This will produce a detailed
525 # IPython itself shouldn't crash. This will produce a detailed
527 # post-mortem if it does. But we only install the crash handler for
526 # post-mortem if it does. But we only install the crash handler for
528 # non-threaded shells, the threaded ones use a normal verbose reporter
527 # non-threaded shells, the threaded ones use a normal verbose reporter
529 # and lose the crash handler. This is because exceptions in the main
528 # and lose the crash handler. This is because exceptions in the main
530 # thread (such as in GUI code) propagate directly to sys.excepthook,
529 # thread (such as in GUI code) propagate directly to sys.excepthook,
531 # and there's no point in printing crash dumps for every user exception.
530 # and there's no point in printing crash dumps for every user exception.
532 if self.isthreaded:
531 if self.isthreaded:
533 ipCrashHandler = ultraTB.FormattedTB()
532 ipCrashHandler = ultraTB.FormattedTB()
534 else:
533 else:
535 from IPython import CrashHandler
534 from IPython import CrashHandler
536 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
535 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
537 self.set_crash_handler(ipCrashHandler)
536 self.set_crash_handler(ipCrashHandler)
538
537
539 # and add any custom exception handlers the user may have specified
538 # and add any custom exception handlers the user may have specified
540 self.set_custom_exc(*custom_exceptions)
539 self.set_custom_exc(*custom_exceptions)
541
540
542 # indentation management
541 # indentation management
543 self.autoindent = False
542 self.autoindent = False
544 self.indent_current_nsp = 0
543 self.indent_current_nsp = 0
545
544
546 # Make some aliases automatically
545 # Make some aliases automatically
547 # Prepare list of shell aliases to auto-define
546 # Prepare list of shell aliases to auto-define
548 if os.name == 'posix':
547 if os.name == 'posix':
549 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
548 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
550 'mv mv -i','rm rm -i','cp cp -i',
549 'mv mv -i','rm rm -i','cp cp -i',
551 'cat cat','less less','clear clear',
550 'cat cat','less less','clear clear',
552 # a better ls
551 # a better ls
553 'ls ls -F',
552 'ls ls -F',
554 # long ls
553 # long ls
555 'll ls -lF')
554 'll ls -lF')
556 # Extra ls aliases with color, which need special treatment on BSD
555 # Extra ls aliases with color, which need special treatment on BSD
557 # variants
556 # variants
558 ls_extra = ( # color ls
557 ls_extra = ( # color ls
559 'lc ls -F -o --color',
558 'lc ls -F -o --color',
560 # ls normal files only
559 # ls normal files only
561 'lf ls -F -o --color %l | grep ^-',
560 'lf ls -F -o --color %l | grep ^-',
562 # ls symbolic links
561 # ls symbolic links
563 'lk ls -F -o --color %l | grep ^l',
562 'lk ls -F -o --color %l | grep ^l',
564 # directories or links to directories,
563 # directories or links to directories,
565 'ldir ls -F -o --color %l | grep /$',
564 'ldir ls -F -o --color %l | grep /$',
566 # things which are executable
565 # things which are executable
567 'lx ls -F -o --color %l | grep ^-..x',
566 'lx ls -F -o --color %l | grep ^-..x',
568 )
567 )
569 # The BSDs don't ship GNU ls, so they don't understand the
568 # The BSDs don't ship GNU ls, so they don't understand the
570 # --color switch out of the box
569 # --color switch out of the box
571 if 'bsd' in sys.platform:
570 if 'bsd' in sys.platform:
572 ls_extra = ( # ls normal files only
571 ls_extra = ( # ls normal files only
573 'lf ls -lF | grep ^-',
572 'lf ls -lF | grep ^-',
574 # ls symbolic links
573 # ls symbolic links
575 'lk ls -lF | grep ^l',
574 'lk ls -lF | grep ^l',
576 # directories or links to directories,
575 # directories or links to directories,
577 'ldir ls -lF | grep /$',
576 'ldir ls -lF | grep /$',
578 # things which are executable
577 # things which are executable
579 'lx ls -lF | grep ^-..x',
578 'lx ls -lF | grep ^-..x',
580 )
579 )
581 auto_alias = auto_alias + ls_extra
580 auto_alias = auto_alias + ls_extra
582 elif os.name in ['nt','dos']:
581 elif os.name in ['nt','dos']:
583 auto_alias = ('ls dir /on',
582 auto_alias = ('ls dir /on',
584 'ddir dir /ad /on', 'ldir dir /ad /on',
583 'ddir dir /ad /on', 'ldir dir /ad /on',
585 'mkdir mkdir','rmdir rmdir','echo echo',
584 'mkdir mkdir','rmdir rmdir','echo echo',
586 'ren ren','cls cls','copy copy')
585 'ren ren','cls cls','copy copy')
587 else:
586 else:
588 auto_alias = ()
587 auto_alias = ()
589 self.auto_alias = [s.split(None,1) for s in auto_alias]
588 self.auto_alias = [s.split(None,1) for s in auto_alias]
590
589
591
590
592 # Produce a public API instance
591 # Produce a public API instance
593 self.api = IPython.ipapi.IPApi(self)
592 self.api = IPython.ipapi.IPApi(self)
594
593
595 # Call the actual (public) initializer
594 # Call the actual (public) initializer
596 self.init_auto_alias()
595 self.init_auto_alias()
597
596
598 # track which builtins we add, so we can clean up later
597 # track which builtins we add, so we can clean up later
599 self.builtins_added = {}
598 self.builtins_added = {}
600 # This method will add the necessary builtins for operation, but
599 # This method will add the necessary builtins for operation, but
601 # tracking what it did via the builtins_added dict.
600 # tracking what it did via the builtins_added dict.
602
601
603 #TODO: remove this, redundant
602 #TODO: remove this, redundant
604 self.add_builtins()
603 self.add_builtins()
605
604
606
605
607
606
608
607
609 # end __init__
608 # end __init__
610
609
611 def var_expand(self,cmd,depth=0):
610 def var_expand(self,cmd,depth=0):
612 """Expand python variables in a string.
611 """Expand python variables in a string.
613
612
614 The depth argument indicates how many frames above the caller should
613 The depth argument indicates how many frames above the caller should
615 be walked to look for the local namespace where to expand variables.
614 be walked to look for the local namespace where to expand variables.
616
615
617 The global namespace for expansion is always the user's interactive
616 The global namespace for expansion is always the user's interactive
618 namespace.
617 namespace.
619 """
618 """
620
619
621 return str(ItplNS(cmd,
620 return str(ItplNS(cmd,
622 self.user_ns, # globals
621 self.user_ns, # globals
623 # Skip our own frame in searching for locals:
622 # Skip our own frame in searching for locals:
624 sys._getframe(depth+1).f_locals # locals
623 sys._getframe(depth+1).f_locals # locals
625 ))
624 ))
626
625
627 def pre_config_initialization(self):
626 def pre_config_initialization(self):
628 """Pre-configuration init method
627 """Pre-configuration init method
629
628
630 This is called before the configuration files are processed to
629 This is called before the configuration files are processed to
631 prepare the services the config files might need.
630 prepare the services the config files might need.
632
631
633 self.rc already has reasonable default values at this point.
632 self.rc already has reasonable default values at this point.
634 """
633 """
635 rc = self.rc
634 rc = self.rc
636 try:
635 try:
637 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
636 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
638 except exceptions.UnicodeDecodeError:
637 except exceptions.UnicodeDecodeError:
639 print "Your ipythondir can't be decoded to unicode!"
638 print "Your ipythondir can't be decoded to unicode!"
640 print "Please set HOME environment variable to something that"
639 print "Please set HOME environment variable to something that"
641 print r"only has ASCII characters, e.g. c:\home"
640 print r"only has ASCII characters, e.g. c:\home"
642 print "Now it is",rc.ipythondir
641 print "Now it is",rc.ipythondir
643 sys.exit()
642 sys.exit()
644 self.shadowhist = IPython.history.ShadowHist(self.db)
643 self.shadowhist = IPython.history.ShadowHist(self.db)
645
644
646
645
647 def post_config_initialization(self):
646 def post_config_initialization(self):
648 """Post configuration init method
647 """Post configuration init method
649
648
650 This is called after the configuration files have been processed to
649 This is called after the configuration files have been processed to
651 'finalize' the initialization."""
650 'finalize' the initialization."""
652
651
653 rc = self.rc
652 rc = self.rc
654
653
655 # Object inspector
654 # Object inspector
656 self.inspector = OInspect.Inspector(OInspect.InspectColors,
655 self.inspector = OInspect.Inspector(OInspect.InspectColors,
657 PyColorize.ANSICodeColors,
656 PyColorize.ANSICodeColors,
658 'NoColor',
657 'NoColor',
659 rc.object_info_string_level)
658 rc.object_info_string_level)
660
659
661 self.rl_next_input = None
660 self.rl_next_input = None
662 self.rl_do_indent = False
661 self.rl_do_indent = False
663 # Load readline proper
662 # Load readline proper
664 if rc.readline:
663 if rc.readline:
665 self.init_readline()
664 self.init_readline()
666
665
667
666
668 # local shortcut, this is used a LOT
667 # local shortcut, this is used a LOT
669 self.log = self.logger.log
668 self.log = self.logger.log
670
669
671 # Initialize cache, set in/out prompts and printing system
670 # Initialize cache, set in/out prompts and printing system
672 self.outputcache = CachedOutput(self,
671 self.outputcache = CachedOutput(self,
673 rc.cache_size,
672 rc.cache_size,
674 rc.pprint,
673 rc.pprint,
675 input_sep = rc.separate_in,
674 input_sep = rc.separate_in,
676 output_sep = rc.separate_out,
675 output_sep = rc.separate_out,
677 output_sep2 = rc.separate_out2,
676 output_sep2 = rc.separate_out2,
678 ps1 = rc.prompt_in1,
677 ps1 = rc.prompt_in1,
679 ps2 = rc.prompt_in2,
678 ps2 = rc.prompt_in2,
680 ps_out = rc.prompt_out,
679 ps_out = rc.prompt_out,
681 pad_left = rc.prompts_pad_left)
680 pad_left = rc.prompts_pad_left)
682
681
683 # user may have over-ridden the default print hook:
682 # user may have over-ridden the default print hook:
684 try:
683 try:
685 self.outputcache.__class__.display = self.hooks.display
684 self.outputcache.__class__.display = self.hooks.display
686 except AttributeError:
685 except AttributeError:
687 pass
686 pass
688
687
689 # I don't like assigning globally to sys, because it means when
688 # I don't like assigning globally to sys, because it means when
690 # embedding instances, each embedded instance overrides the previous
689 # embedding instances, each embedded instance overrides the previous
691 # choice. But sys.displayhook seems to be called internally by exec,
690 # choice. But sys.displayhook seems to be called internally by exec,
692 # so I don't see a way around it. We first save the original and then
691 # so I don't see a way around it. We first save the original and then
693 # overwrite it.
692 # overwrite it.
694 self.sys_displayhook = sys.displayhook
693 self.sys_displayhook = sys.displayhook
695 sys.displayhook = self.outputcache
694 sys.displayhook = self.outputcache
696
695
697 # Do a proper resetting of doctest, including the necessary displayhook
696 # Do a proper resetting of doctest, including the necessary displayhook
698 # monkeypatching
697 # monkeypatching
699 try:
698 try:
700 doctest_reload()
699 doctest_reload()
701 except ImportError:
700 except ImportError:
702 warn("doctest module does not exist.")
701 warn("doctest module does not exist.")
703
702
704 # Set user colors (don't do it in the constructor above so that it
703 # Set user colors (don't do it in the constructor above so that it
705 # doesn't crash if colors option is invalid)
704 # doesn't crash if colors option is invalid)
706 self.magic_colors(rc.colors)
705 self.magic_colors(rc.colors)
707
706
708 # Set calling of pdb on exceptions
707 # Set calling of pdb on exceptions
709 self.call_pdb = rc.pdb
708 self.call_pdb = rc.pdb
710
709
711 # Load user aliases
710 # Load user aliases
712 for alias in rc.alias:
711 for alias in rc.alias:
713 self.magic_alias(alias)
712 self.magic_alias(alias)
714
713
715 self.hooks.late_startup_hook()
714 self.hooks.late_startup_hook()
716
715
717 for cmd in self.rc.autoexec:
716 for cmd in self.rc.autoexec:
718 #print "autoexec>",cmd #dbg
717 #print "autoexec>",cmd #dbg
719 self.api.runlines(cmd)
718 self.api.runlines(cmd)
720
719
721 batchrun = False
720 batchrun = False
722 for batchfile in [path(arg) for arg in self.rc.args
721 for batchfile in [path(arg) for arg in self.rc.args
723 if arg.lower().endswith('.ipy')]:
722 if arg.lower().endswith('.ipy')]:
724 if not batchfile.isfile():
723 if not batchfile.isfile():
725 print "No such batch file:", batchfile
724 print "No such batch file:", batchfile
726 continue
725 continue
727 self.api.runlines(batchfile.text())
726 self.api.runlines(batchfile.text())
728 batchrun = True
727 batchrun = True
729 # without -i option, exit after running the batch file
728 # without -i option, exit after running the batch file
730 if batchrun and not self.rc.interact:
729 if batchrun and not self.rc.interact:
731 self.exit_now = True
730 self.exit_now = True
732
731
733 def add_builtins(self):
732 def add_builtins(self):
734 """Store ipython references into the builtin namespace.
733 """Store ipython references into the builtin namespace.
735
734
736 Some parts of ipython operate via builtins injected here, which hold a
735 Some parts of ipython operate via builtins injected here, which hold a
737 reference to IPython itself."""
736 reference to IPython itself."""
738
737
739 # TODO: deprecate all of these, they are unsafe
738 # TODO: deprecate all of these, they are unsafe
740 builtins_new = dict(__IPYTHON__ = self,
739 builtins_new = dict(__IPYTHON__ = self,
741 ip_set_hook = self.set_hook,
740 ip_set_hook = self.set_hook,
742 jobs = self.jobs,
741 jobs = self.jobs,
743 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
742 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
744 ipalias = wrap_deprecated(self.ipalias),
743 ipalias = wrap_deprecated(self.ipalias),
745 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
744 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
746 #_ip = self.api
745 #_ip = self.api
747 )
746 )
748 for biname,bival in builtins_new.items():
747 for biname,bival in builtins_new.items():
749 try:
748 try:
750 # store the orignal value so we can restore it
749 # store the orignal value so we can restore it
751 self.builtins_added[biname] = __builtin__.__dict__[biname]
750 self.builtins_added[biname] = __builtin__.__dict__[biname]
752 except KeyError:
751 except KeyError:
753 # or mark that it wasn't defined, and we'll just delete it at
752 # or mark that it wasn't defined, and we'll just delete it at
754 # cleanup
753 # cleanup
755 self.builtins_added[biname] = Undefined
754 self.builtins_added[biname] = Undefined
756 __builtin__.__dict__[biname] = bival
755 __builtin__.__dict__[biname] = bival
757
756
758 # Keep in the builtins a flag for when IPython is active. We set it
757 # Keep in the builtins a flag for when IPython is active. We set it
759 # with setdefault so that multiple nested IPythons don't clobber one
758 # with setdefault so that multiple nested IPythons don't clobber one
760 # another. Each will increase its value by one upon being activated,
759 # another. Each will increase its value by one upon being activated,
761 # which also gives us a way to determine the nesting level.
760 # which also gives us a way to determine the nesting level.
762 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
761 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
763
762
764 def clean_builtins(self):
763 def clean_builtins(self):
765 """Remove any builtins which might have been added by add_builtins, or
764 """Remove any builtins which might have been added by add_builtins, or
766 restore overwritten ones to their previous values."""
765 restore overwritten ones to their previous values."""
767 for biname,bival in self.builtins_added.items():
766 for biname,bival in self.builtins_added.items():
768 if bival is Undefined:
767 if bival is Undefined:
769 del __builtin__.__dict__[biname]
768 del __builtin__.__dict__[biname]
770 else:
769 else:
771 __builtin__.__dict__[biname] = bival
770 __builtin__.__dict__[biname] = bival
772 self.builtins_added.clear()
771 self.builtins_added.clear()
773
772
774 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
773 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
775 """set_hook(name,hook) -> sets an internal IPython hook.
774 """set_hook(name,hook) -> sets an internal IPython hook.
776
775
777 IPython exposes some of its internal API as user-modifiable hooks. By
776 IPython exposes some of its internal API as user-modifiable hooks. By
778 adding your function to one of these hooks, you can modify IPython's
777 adding your function to one of these hooks, you can modify IPython's
779 behavior to call at runtime your own routines."""
778 behavior to call at runtime your own routines."""
780
779
781 # At some point in the future, this should validate the hook before it
780 # At some point in the future, this should validate the hook before it
782 # accepts it. Probably at least check that the hook takes the number
781 # accepts it. Probably at least check that the hook takes the number
783 # of args it's supposed to.
782 # of args it's supposed to.
784
783
785 f = new.instancemethod(hook,self,self.__class__)
784 f = new.instancemethod(hook,self,self.__class__)
786
785
787 # check if the hook is for strdispatcher first
786 # check if the hook is for strdispatcher first
788 if str_key is not None:
787 if str_key is not None:
789 sdp = self.strdispatchers.get(name, StrDispatch())
788 sdp = self.strdispatchers.get(name, StrDispatch())
790 sdp.add_s(str_key, f, priority )
789 sdp.add_s(str_key, f, priority )
791 self.strdispatchers[name] = sdp
790 self.strdispatchers[name] = sdp
792 return
791 return
793 if re_key is not None:
792 if re_key is not None:
794 sdp = self.strdispatchers.get(name, StrDispatch())
793 sdp = self.strdispatchers.get(name, StrDispatch())
795 sdp.add_re(re.compile(re_key), f, priority )
794 sdp.add_re(re.compile(re_key), f, priority )
796 self.strdispatchers[name] = sdp
795 self.strdispatchers[name] = sdp
797 return
796 return
798
797
799 dp = getattr(self.hooks, name, None)
798 dp = getattr(self.hooks, name, None)
800 if name not in IPython.hooks.__all__:
799 if name not in IPython.hooks.__all__:
801 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
800 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
802 if not dp:
801 if not dp:
803 dp = IPython.hooks.CommandChainDispatcher()
802 dp = IPython.hooks.CommandChainDispatcher()
804
803
805 try:
804 try:
806 dp.add(f,priority)
805 dp.add(f,priority)
807 except AttributeError:
806 except AttributeError:
808 # it was not commandchain, plain old func - replace
807 # it was not commandchain, plain old func - replace
809 dp = f
808 dp = f
810
809
811 setattr(self.hooks,name, dp)
810 setattr(self.hooks,name, dp)
812
811
813
812
814 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
813 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
815
814
816 def set_crash_handler(self,crashHandler):
815 def set_crash_handler(self,crashHandler):
817 """Set the IPython crash handler.
816 """Set the IPython crash handler.
818
817
819 This must be a callable with a signature suitable for use as
818 This must be a callable with a signature suitable for use as
820 sys.excepthook."""
819 sys.excepthook."""
821
820
822 # Install the given crash handler as the Python exception hook
821 # Install the given crash handler as the Python exception hook
823 sys.excepthook = crashHandler
822 sys.excepthook = crashHandler
824
823
825 # The instance will store a pointer to this, so that runtime code
824 # The instance will store a pointer to this, so that runtime code
826 # (such as magics) can access it. This is because during the
825 # (such as magics) can access it. This is because during the
827 # read-eval loop, it gets temporarily overwritten (to deal with GUI
826 # read-eval loop, it gets temporarily overwritten (to deal with GUI
828 # frameworks).
827 # frameworks).
829 self.sys_excepthook = sys.excepthook
828 self.sys_excepthook = sys.excepthook
830
829
831
830
832 def set_custom_exc(self,exc_tuple,handler):
831 def set_custom_exc(self,exc_tuple,handler):
833 """set_custom_exc(exc_tuple,handler)
832 """set_custom_exc(exc_tuple,handler)
834
833
835 Set a custom exception handler, which will be called if any of the
834 Set a custom exception handler, which will be called if any of the
836 exceptions in exc_tuple occur in the mainloop (specifically, in the
835 exceptions in exc_tuple occur in the mainloop (specifically, in the
837 runcode() method.
836 runcode() method.
838
837
839 Inputs:
838 Inputs:
840
839
841 - exc_tuple: a *tuple* of valid exceptions to call the defined
840 - exc_tuple: a *tuple* of valid exceptions to call the defined
842 handler for. It is very important that you use a tuple, and NOT A
841 handler for. It is very important that you use a tuple, and NOT A
843 LIST here, because of the way Python's except statement works. If
842 LIST here, because of the way Python's except statement works. If
844 you only want to trap a single exception, use a singleton tuple:
843 you only want to trap a single exception, use a singleton tuple:
845
844
846 exc_tuple == (MyCustomException,)
845 exc_tuple == (MyCustomException,)
847
846
848 - handler: this must be defined as a function with the following
847 - handler: this must be defined as a function with the following
849 basic interface: def my_handler(self,etype,value,tb).
848 basic interface: def my_handler(self,etype,value,tb).
850
849
851 This will be made into an instance method (via new.instancemethod)
850 This will be made into an instance method (via new.instancemethod)
852 of IPython itself, and it will be called if any of the exceptions
851 of IPython itself, and it will be called if any of the exceptions
853 listed in the exc_tuple are caught. If the handler is None, an
852 listed in the exc_tuple are caught. If the handler is None, an
854 internal basic one is used, which just prints basic info.
853 internal basic one is used, which just prints basic info.
855
854
856 WARNING: by putting in your own exception handler into IPython's main
855 WARNING: by putting in your own exception handler into IPython's main
857 execution loop, you run a very good chance of nasty crashes. This
856 execution loop, you run a very good chance of nasty crashes. This
858 facility should only be used if you really know what you are doing."""
857 facility should only be used if you really know what you are doing."""
859
858
860 assert type(exc_tuple)==type(()) , \
859 assert type(exc_tuple)==type(()) , \
861 "The custom exceptions must be given AS A TUPLE."
860 "The custom exceptions must be given AS A TUPLE."
862
861
863 def dummy_handler(self,etype,value,tb):
862 def dummy_handler(self,etype,value,tb):
864 print '*** Simple custom exception handler ***'
863 print '*** Simple custom exception handler ***'
865 print 'Exception type :',etype
864 print 'Exception type :',etype
866 print 'Exception value:',value
865 print 'Exception value:',value
867 print 'Traceback :',tb
866 print 'Traceback :',tb
868 print 'Source code :','\n'.join(self.buffer)
867 print 'Source code :','\n'.join(self.buffer)
869
868
870 if handler is None: handler = dummy_handler
869 if handler is None: handler = dummy_handler
871
870
872 self.CustomTB = new.instancemethod(handler,self,self.__class__)
871 self.CustomTB = new.instancemethod(handler,self,self.__class__)
873 self.custom_exceptions = exc_tuple
872 self.custom_exceptions = exc_tuple
874
873
875 def set_custom_completer(self,completer,pos=0):
874 def set_custom_completer(self,completer,pos=0):
876 """set_custom_completer(completer,pos=0)
875 """set_custom_completer(completer,pos=0)
877
876
878 Adds a new custom completer function.
877 Adds a new custom completer function.
879
878
880 The position argument (defaults to 0) is the index in the completers
879 The position argument (defaults to 0) is the index in the completers
881 list where you want the completer to be inserted."""
880 list where you want the completer to be inserted."""
882
881
883 newcomp = new.instancemethod(completer,self.Completer,
882 newcomp = new.instancemethod(completer,self.Completer,
884 self.Completer.__class__)
883 self.Completer.__class__)
885 self.Completer.matchers.insert(pos,newcomp)
884 self.Completer.matchers.insert(pos,newcomp)
886
885
887 def set_completer(self):
886 def set_completer(self):
888 """reset readline's completer to be our own."""
887 """reset readline's completer to be our own."""
889 self.readline.set_completer(self.Completer.complete)
888 self.readline.set_completer(self.Completer.complete)
890
889
891 def _get_call_pdb(self):
890 def _get_call_pdb(self):
892 return self._call_pdb
891 return self._call_pdb
893
892
894 def _set_call_pdb(self,val):
893 def _set_call_pdb(self,val):
895
894
896 if val not in (0,1,False,True):
895 if val not in (0,1,False,True):
897 raise ValueError,'new call_pdb value must be boolean'
896 raise ValueError,'new call_pdb value must be boolean'
898
897
899 # store value in instance
898 # store value in instance
900 self._call_pdb = val
899 self._call_pdb = val
901
900
902 # notify the actual exception handlers
901 # notify the actual exception handlers
903 self.InteractiveTB.call_pdb = val
902 self.InteractiveTB.call_pdb = val
904 if self.isthreaded:
903 if self.isthreaded:
905 try:
904 try:
906 self.sys_excepthook.call_pdb = val
905 self.sys_excepthook.call_pdb = val
907 except:
906 except:
908 warn('Failed to activate pdb for threaded exception handler')
907 warn('Failed to activate pdb for threaded exception handler')
909
908
910 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
909 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
911 'Control auto-activation of pdb at exceptions')
910 'Control auto-activation of pdb at exceptions')
912
911
913
912
914 # These special functions get installed in the builtin namespace, to
913 # These special functions get installed in the builtin namespace, to
915 # provide programmatic (pure python) access to magics, aliases and system
914 # provide programmatic (pure python) access to magics, aliases and system
916 # calls. This is important for logging, user scripting, and more.
915 # calls. This is important for logging, user scripting, and more.
917
916
918 # We are basically exposing, via normal python functions, the three
917 # We are basically exposing, via normal python functions, the three
919 # mechanisms in which ipython offers special call modes (magics for
918 # mechanisms in which ipython offers special call modes (magics for
920 # internal control, aliases for direct system access via pre-selected
919 # internal control, aliases for direct system access via pre-selected
921 # names, and !cmd for calling arbitrary system commands).
920 # names, and !cmd for calling arbitrary system commands).
922
921
923 def ipmagic(self,arg_s):
922 def ipmagic(self,arg_s):
924 """Call a magic function by name.
923 """Call a magic function by name.
925
924
926 Input: a string containing the name of the magic function to call and any
925 Input: a string containing the name of the magic function to call and any
927 additional arguments to be passed to the magic.
926 additional arguments to be passed to the magic.
928
927
929 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
928 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
930 prompt:
929 prompt:
931
930
932 In[1]: %name -opt foo bar
931 In[1]: %name -opt foo bar
933
932
934 To call a magic without arguments, simply use ipmagic('name').
933 To call a magic without arguments, simply use ipmagic('name').
935
934
936 This provides a proper Python function to call IPython's magics in any
935 This provides a proper Python function to call IPython's magics in any
937 valid Python code you can type at the interpreter, including loops and
936 valid Python code you can type at the interpreter, including loops and
938 compound statements. It is added by IPython to the Python builtin
937 compound statements. It is added by IPython to the Python builtin
939 namespace upon initialization."""
938 namespace upon initialization."""
940
939
941 args = arg_s.split(' ',1)
940 args = arg_s.split(' ',1)
942 magic_name = args[0]
941 magic_name = args[0]
943 magic_name = magic_name.lstrip(self.ESC_MAGIC)
942 magic_name = magic_name.lstrip(self.ESC_MAGIC)
944
943
945 try:
944 try:
946 magic_args = args[1]
945 magic_args = args[1]
947 except IndexError:
946 except IndexError:
948 magic_args = ''
947 magic_args = ''
949 fn = getattr(self,'magic_'+magic_name,None)
948 fn = getattr(self,'magic_'+magic_name,None)
950 if fn is None:
949 if fn is None:
951 error("Magic function `%s` not found." % magic_name)
950 error("Magic function `%s` not found." % magic_name)
952 else:
951 else:
953 magic_args = self.var_expand(magic_args,1)
952 magic_args = self.var_expand(magic_args,1)
954 return fn(magic_args)
953 return fn(magic_args)
955
954
956 def ipalias(self,arg_s):
955 def ipalias(self,arg_s):
957 """Call an alias by name.
956 """Call an alias by name.
958
957
959 Input: a string containing the name of the alias to call and any
958 Input: a string containing the name of the alias to call and any
960 additional arguments to be passed to the magic.
959 additional arguments to be passed to the magic.
961
960
962 ipalias('name -opt foo bar') is equivalent to typing at the ipython
961 ipalias('name -opt foo bar') is equivalent to typing at the ipython
963 prompt:
962 prompt:
964
963
965 In[1]: name -opt foo bar
964 In[1]: name -opt foo bar
966
965
967 To call an alias without arguments, simply use ipalias('name').
966 To call an alias without arguments, simply use ipalias('name').
968
967
969 This provides a proper Python function to call IPython's aliases in any
968 This provides a proper Python function to call IPython's aliases in any
970 valid Python code you can type at the interpreter, including loops and
969 valid Python code you can type at the interpreter, including loops and
971 compound statements. It is added by IPython to the Python builtin
970 compound statements. It is added by IPython to the Python builtin
972 namespace upon initialization."""
971 namespace upon initialization."""
973
972
974 args = arg_s.split(' ',1)
973 args = arg_s.split(' ',1)
975 alias_name = args[0]
974 alias_name = args[0]
976 try:
975 try:
977 alias_args = args[1]
976 alias_args = args[1]
978 except IndexError:
977 except IndexError:
979 alias_args = ''
978 alias_args = ''
980 if alias_name in self.alias_table:
979 if alias_name in self.alias_table:
981 self.call_alias(alias_name,alias_args)
980 self.call_alias(alias_name,alias_args)
982 else:
981 else:
983 error("Alias `%s` not found." % alias_name)
982 error("Alias `%s` not found." % alias_name)
984
983
985 def ipsystem(self,arg_s):
984 def ipsystem(self,arg_s):
986 """Make a system call, using IPython."""
985 """Make a system call, using IPython."""
987
986
988 self.system(arg_s)
987 self.system(arg_s)
989
988
990 def complete(self,text):
989 def complete(self,text):
991 """Return a sorted list of all possible completions on text.
990 """Return a sorted list of all possible completions on text.
992
991
993 Inputs:
992 Inputs:
994
993
995 - text: a string of text to be completed on.
994 - text: a string of text to be completed on.
996
995
997 This is a wrapper around the completion mechanism, similar to what
996 This is a wrapper around the completion mechanism, similar to what
998 readline does at the command line when the TAB key is hit. By
997 readline does at the command line when the TAB key is hit. By
999 exposing it as a method, it can be used by other non-readline
998 exposing it as a method, it can be used by other non-readline
1000 environments (such as GUIs) for text completion.
999 environments (such as GUIs) for text completion.
1001
1000
1002 Simple usage example:
1001 Simple usage example:
1003
1002
1004 In [7]: x = 'hello'
1003 In [7]: x = 'hello'
1005
1004
1006 In [8]: x
1005 In [8]: x
1007 Out[8]: 'hello'
1006 Out[8]: 'hello'
1008
1007
1009 In [9]: print x
1008 In [9]: print x
1010 hello
1009 hello
1011
1010
1012 In [10]: _ip.IP.complete('x.l')
1011 In [10]: _ip.IP.complete('x.l')
1013 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] # randomX
1012 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] # randomX
1014 """
1013 """
1015
1014
1016 complete = self.Completer.complete
1015 complete = self.Completer.complete
1017 state = 0
1016 state = 0
1018 # use a dict so we get unique keys, since ipyhton's multiple
1017 # use a dict so we get unique keys, since ipyhton's multiple
1019 # completers can return duplicates. When we make 2.4 a requirement,
1018 # completers can return duplicates. When we make 2.4 a requirement,
1020 # start using sets instead, which are faster.
1019 # start using sets instead, which are faster.
1021 comps = {}
1020 comps = {}
1022 while True:
1021 while True:
1023 newcomp = complete(text,state,line_buffer=text)
1022 newcomp = complete(text,state,line_buffer=text)
1024 if newcomp is None:
1023 if newcomp is None:
1025 break
1024 break
1026 comps[newcomp] = 1
1025 comps[newcomp] = 1
1027 state += 1
1026 state += 1
1028 outcomps = comps.keys()
1027 outcomps = comps.keys()
1029 outcomps.sort()
1028 outcomps.sort()
1030 #print "T:",text,"OC:",outcomps # dbg
1029 #print "T:",text,"OC:",outcomps # dbg
1031 #print "vars:",self.user_ns.keys()
1030 #print "vars:",self.user_ns.keys()
1032 return outcomps
1031 return outcomps
1033
1032
1034 def set_completer_frame(self, frame=None):
1033 def set_completer_frame(self, frame=None):
1035 if frame:
1034 if frame:
1036 self.Completer.namespace = frame.f_locals
1035 self.Completer.namespace = frame.f_locals
1037 self.Completer.global_namespace = frame.f_globals
1036 self.Completer.global_namespace = frame.f_globals
1038 else:
1037 else:
1039 self.Completer.namespace = self.user_ns
1038 self.Completer.namespace = self.user_ns
1040 self.Completer.global_namespace = self.user_global_ns
1039 self.Completer.global_namespace = self.user_global_ns
1041
1040
1042 def init_auto_alias(self):
1041 def init_auto_alias(self):
1043 """Define some aliases automatically.
1042 """Define some aliases automatically.
1044
1043
1045 These are ALL parameter-less aliases"""
1044 These are ALL parameter-less aliases"""
1046
1045
1047 for alias,cmd in self.auto_alias:
1046 for alias,cmd in self.auto_alias:
1048 self.getapi().defalias(alias,cmd)
1047 self.getapi().defalias(alias,cmd)
1049
1048
1050
1049
1051 def alias_table_validate(self,verbose=0):
1050 def alias_table_validate(self,verbose=0):
1052 """Update information about the alias table.
1051 """Update information about the alias table.
1053
1052
1054 In particular, make sure no Python keywords/builtins are in it."""
1053 In particular, make sure no Python keywords/builtins are in it."""
1055
1054
1056 no_alias = self.no_alias
1055 no_alias = self.no_alias
1057 for k in self.alias_table.keys():
1056 for k in self.alias_table.keys():
1058 if k in no_alias:
1057 if k in no_alias:
1059 del self.alias_table[k]
1058 del self.alias_table[k]
1060 if verbose:
1059 if verbose:
1061 print ("Deleting alias <%s>, it's a Python "
1060 print ("Deleting alias <%s>, it's a Python "
1062 "keyword or builtin." % k)
1061 "keyword or builtin." % k)
1063
1062
1064 def set_autoindent(self,value=None):
1063 def set_autoindent(self,value=None):
1065 """Set the autoindent flag, checking for readline support.
1064 """Set the autoindent flag, checking for readline support.
1066
1065
1067 If called with no arguments, it acts as a toggle."""
1066 If called with no arguments, it acts as a toggle."""
1068
1067
1069 if not self.has_readline:
1068 if not self.has_readline:
1070 if os.name == 'posix':
1069 if os.name == 'posix':
1071 warn("The auto-indent feature requires the readline library")
1070 warn("The auto-indent feature requires the readline library")
1072 self.autoindent = 0
1071 self.autoindent = 0
1073 return
1072 return
1074 if value is None:
1073 if value is None:
1075 self.autoindent = not self.autoindent
1074 self.autoindent = not self.autoindent
1076 else:
1075 else:
1077 self.autoindent = value
1076 self.autoindent = value
1078
1077
1079 def rc_set_toggle(self,rc_field,value=None):
1078 def rc_set_toggle(self,rc_field,value=None):
1080 """Set or toggle a field in IPython's rc config. structure.
1079 """Set or toggle a field in IPython's rc config. structure.
1081
1080
1082 If called with no arguments, it acts as a toggle.
1081 If called with no arguments, it acts as a toggle.
1083
1082
1084 If called with a non-existent field, the resulting AttributeError
1083 If called with a non-existent field, the resulting AttributeError
1085 exception will propagate out."""
1084 exception will propagate out."""
1086
1085
1087 rc_val = getattr(self.rc,rc_field)
1086 rc_val = getattr(self.rc,rc_field)
1088 if value is None:
1087 if value is None:
1089 value = not rc_val
1088 value = not rc_val
1090 setattr(self.rc,rc_field,value)
1089 setattr(self.rc,rc_field,value)
1091
1090
1092 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1091 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1093 """Install the user configuration directory.
1092 """Install the user configuration directory.
1094
1093
1095 Can be called when running for the first time or to upgrade the user's
1094 Can be called when running for the first time or to upgrade the user's
1096 .ipython/ directory with the mode parameter. Valid modes are 'install'
1095 .ipython/ directory with the mode parameter. Valid modes are 'install'
1097 and 'upgrade'."""
1096 and 'upgrade'."""
1098
1097
1099 def wait():
1098 def wait():
1100 try:
1099 try:
1101 raw_input("Please press <RETURN> to start IPython.")
1100 raw_input("Please press <RETURN> to start IPython.")
1102 except EOFError:
1101 except EOFError:
1103 print >> Term.cout
1102 print >> Term.cout
1104 print '*'*70
1103 print '*'*70
1105
1104
1106 cwd = os.getcwd() # remember where we started
1105 cwd = os.getcwd() # remember where we started
1107 glb = glob.glob
1106 glb = glob.glob
1108 print '*'*70
1107 print '*'*70
1109 if mode == 'install':
1108 if mode == 'install':
1110 print \
1109 print \
1111 """Welcome to IPython. I will try to create a personal configuration directory
1110 """Welcome to IPython. I will try to create a personal configuration directory
1112 where you can customize many aspects of IPython's functionality in:\n"""
1111 where you can customize many aspects of IPython's functionality in:\n"""
1113 else:
1112 else:
1114 print 'I am going to upgrade your configuration in:'
1113 print 'I am going to upgrade your configuration in:'
1115
1114
1116 print ipythondir
1115 print ipythondir
1117
1116
1118 rcdirend = os.path.join('IPython','UserConfig')
1117 rcdirend = os.path.join('IPython','UserConfig')
1119 cfg = lambda d: os.path.join(d,rcdirend)
1118 cfg = lambda d: os.path.join(d,rcdirend)
1120 try:
1119 try:
1121 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1120 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1122 print "Initializing from configuration",rcdir
1121 print "Initializing from configuration",rcdir
1123 except IndexError:
1122 except IndexError:
1124 warning = """
1123 warning = """
1125 Installation error. IPython's directory was not found.
1124 Installation error. IPython's directory was not found.
1126
1125
1127 Check the following:
1126 Check the following:
1128
1127
1129 The ipython/IPython directory should be in a directory belonging to your
1128 The ipython/IPython directory should be in a directory belonging to your
1130 PYTHONPATH environment variable (that is, it should be in a directory
1129 PYTHONPATH environment variable (that is, it should be in a directory
1131 belonging to sys.path). You can copy it explicitly there or just link to it.
1130 belonging to sys.path). You can copy it explicitly there or just link to it.
1132
1131
1133 IPython will create a minimal default configuration for you.
1132 IPython will create a minimal default configuration for you.
1134
1133
1135 """
1134 """
1136 warn(warning)
1135 warn(warning)
1137 wait()
1136 wait()
1138
1137
1139 if sys.platform =='win32':
1138 if sys.platform =='win32':
1140 inif = 'ipythonrc.ini'
1139 inif = 'ipythonrc.ini'
1141 else:
1140 else:
1142 inif = 'ipythonrc'
1141 inif = 'ipythonrc'
1143 minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', inif : '# intentionally left blank' }
1142 minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', inif : '# intentionally left blank' }
1144 os.makedirs(ipythondir, mode = 0777)
1143 os.makedirs(ipythondir, mode = 0777)
1145 for f, cont in minimal_setup.items():
1144 for f, cont in minimal_setup.items():
1146 open(ipythondir + '/' + f,'w').write(cont)
1145 open(ipythondir + '/' + f,'w').write(cont)
1147
1146
1148 return
1147 return
1149
1148
1150 if mode == 'install':
1149 if mode == 'install':
1151 try:
1150 try:
1152 shutil.copytree(rcdir,ipythondir)
1151 shutil.copytree(rcdir,ipythondir)
1153 os.chdir(ipythondir)
1152 os.chdir(ipythondir)
1154 rc_files = glb("ipythonrc*")
1153 rc_files = glb("ipythonrc*")
1155 for rc_file in rc_files:
1154 for rc_file in rc_files:
1156 os.rename(rc_file,rc_file+rc_suffix)
1155 os.rename(rc_file,rc_file+rc_suffix)
1157 except:
1156 except:
1158 warning = """
1157 warning = """
1159
1158
1160 There was a problem with the installation:
1159 There was a problem with the installation:
1161 %s
1160 %s
1162 Try to correct it or contact the developers if you think it's a bug.
1161 Try to correct it or contact the developers if you think it's a bug.
1163 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1162 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1164 warn(warning)
1163 warn(warning)
1165 wait()
1164 wait()
1166 return
1165 return
1167
1166
1168 elif mode == 'upgrade':
1167 elif mode == 'upgrade':
1169 try:
1168 try:
1170 os.chdir(ipythondir)
1169 os.chdir(ipythondir)
1171 except:
1170 except:
1172 print """
1171 print """
1173 Can not upgrade: changing to directory %s failed. Details:
1172 Can not upgrade: changing to directory %s failed. Details:
1174 %s
1173 %s
1175 """ % (ipythondir,sys.exc_info()[1])
1174 """ % (ipythondir,sys.exc_info()[1])
1176 wait()
1175 wait()
1177 return
1176 return
1178 else:
1177 else:
1179 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1178 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1180 for new_full_path in sources:
1179 for new_full_path in sources:
1181 new_filename = os.path.basename(new_full_path)
1180 new_filename = os.path.basename(new_full_path)
1182 if new_filename.startswith('ipythonrc'):
1181 if new_filename.startswith('ipythonrc'):
1183 new_filename = new_filename + rc_suffix
1182 new_filename = new_filename + rc_suffix
1184 # The config directory should only contain files, skip any
1183 # The config directory should only contain files, skip any
1185 # directories which may be there (like CVS)
1184 # directories which may be there (like CVS)
1186 if os.path.isdir(new_full_path):
1185 if os.path.isdir(new_full_path):
1187 continue
1186 continue
1188 if os.path.exists(new_filename):
1187 if os.path.exists(new_filename):
1189 old_file = new_filename+'.old'
1188 old_file = new_filename+'.old'
1190 if os.path.exists(old_file):
1189 if os.path.exists(old_file):
1191 os.remove(old_file)
1190 os.remove(old_file)
1192 os.rename(new_filename,old_file)
1191 os.rename(new_filename,old_file)
1193 shutil.copy(new_full_path,new_filename)
1192 shutil.copy(new_full_path,new_filename)
1194 else:
1193 else:
1195 raise ValueError,'unrecognized mode for install:',`mode`
1194 raise ValueError,'unrecognized mode for install:',`mode`
1196
1195
1197 # Fix line-endings to those native to each platform in the config
1196 # Fix line-endings to those native to each platform in the config
1198 # directory.
1197 # directory.
1199 try:
1198 try:
1200 os.chdir(ipythondir)
1199 os.chdir(ipythondir)
1201 except:
1200 except:
1202 print """
1201 print """
1203 Problem: changing to directory %s failed.
1202 Problem: changing to directory %s failed.
1204 Details:
1203 Details:
1205 %s
1204 %s
1206
1205
1207 Some configuration files may have incorrect line endings. This should not
1206 Some configuration files may have incorrect line endings. This should not
1208 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1207 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1209 wait()
1208 wait()
1210 else:
1209 else:
1211 for fname in glb('ipythonrc*'):
1210 for fname in glb('ipythonrc*'):
1212 try:
1211 try:
1213 native_line_ends(fname,backup=0)
1212 native_line_ends(fname,backup=0)
1214 except IOError:
1213 except IOError:
1215 pass
1214 pass
1216
1215
1217 if mode == 'install':
1216 if mode == 'install':
1218 print """
1217 print """
1219 Successful installation!
1218 Successful installation!
1220
1219
1221 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1220 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1222 IPython manual (there are both HTML and PDF versions supplied with the
1221 IPython manual (there are both HTML and PDF versions supplied with the
1223 distribution) to make sure that your system environment is properly configured
1222 distribution) to make sure that your system environment is properly configured
1224 to take advantage of IPython's features.
1223 to take advantage of IPython's features.
1225
1224
1226 Important note: the configuration system has changed! The old system is
1225 Important note: the configuration system has changed! The old system is
1227 still in place, but its setting may be partly overridden by the settings in
1226 still in place, but its setting may be partly overridden by the settings in
1228 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1227 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1229 if some of the new settings bother you.
1228 if some of the new settings bother you.
1230
1229
1231 """
1230 """
1232 else:
1231 else:
1233 print """
1232 print """
1234 Successful upgrade!
1233 Successful upgrade!
1235
1234
1236 All files in your directory:
1235 All files in your directory:
1237 %(ipythondir)s
1236 %(ipythondir)s
1238 which would have been overwritten by the upgrade were backed up with a .old
1237 which would have been overwritten by the upgrade were backed up with a .old
1239 extension. If you had made particular customizations in those files you may
1238 extension. If you had made particular customizations in those files you may
1240 want to merge them back into the new files.""" % locals()
1239 want to merge them back into the new files.""" % locals()
1241 wait()
1240 wait()
1242 os.chdir(cwd)
1241 os.chdir(cwd)
1243 # end user_setup()
1242 # end user_setup()
1244
1243
1245 def atexit_operations(self):
1244 def atexit_operations(self):
1246 """This will be executed at the time of exit.
1245 """This will be executed at the time of exit.
1247
1246
1248 Saving of persistent data should be performed here. """
1247 Saving of persistent data should be performed here. """
1249
1248
1250 #print '*** IPython exit cleanup ***' # dbg
1249 #print '*** IPython exit cleanup ***' # dbg
1251 # input history
1250 # input history
1252 self.savehist()
1251 self.savehist()
1253
1252
1254 # Cleanup all tempfiles left around
1253 # Cleanup all tempfiles left around
1255 for tfile in self.tempfiles:
1254 for tfile in self.tempfiles:
1256 try:
1255 try:
1257 os.unlink(tfile)
1256 os.unlink(tfile)
1258 except OSError:
1257 except OSError:
1259 pass
1258 pass
1260
1259
1261 self.hooks.shutdown_hook()
1260 self.hooks.shutdown_hook()
1262
1261
1263 def savehist(self):
1262 def savehist(self):
1264 """Save input history to a file (via readline library)."""
1263 """Save input history to a file (via readline library)."""
1265
1264
1266 if not self.has_readline:
1265 if not self.has_readline:
1267 return
1266 return
1268
1267
1269 try:
1268 try:
1270 self.readline.write_history_file(self.histfile)
1269 self.readline.write_history_file(self.histfile)
1271 except:
1270 except:
1272 print 'Unable to save IPython command history to file: ' + \
1271 print 'Unable to save IPython command history to file: ' + \
1273 `self.histfile`
1272 `self.histfile`
1274
1273
1275 def reloadhist(self):
1274 def reloadhist(self):
1276 """Reload the input history from disk file."""
1275 """Reload the input history from disk file."""
1277
1276
1278 if self.has_readline:
1277 if self.has_readline:
1279 try:
1278 try:
1280 self.readline.clear_history()
1279 self.readline.clear_history()
1281 self.readline.read_history_file(self.shell.histfile)
1280 self.readline.read_history_file(self.shell.histfile)
1282 except AttributeError:
1281 except AttributeError:
1283 pass
1282 pass
1284
1283
1285
1284
1286 def history_saving_wrapper(self, func):
1285 def history_saving_wrapper(self, func):
1287 """ Wrap func for readline history saving
1286 """ Wrap func for readline history saving
1288
1287
1289 Convert func into callable that saves & restores
1288 Convert func into callable that saves & restores
1290 history around the call """
1289 history around the call """
1291
1290
1292 if not self.has_readline:
1291 if not self.has_readline:
1293 return func
1292 return func
1294
1293
1295 def wrapper():
1294 def wrapper():
1296 self.savehist()
1295 self.savehist()
1297 try:
1296 try:
1298 func()
1297 func()
1299 finally:
1298 finally:
1300 readline.read_history_file(self.histfile)
1299 readline.read_history_file(self.histfile)
1301 return wrapper
1300 return wrapper
1302
1301
1303
1302
1304 def pre_readline(self):
1303 def pre_readline(self):
1305 """readline hook to be used at the start of each line.
1304 """readline hook to be used at the start of each line.
1306
1305
1307 Currently it handles auto-indent only."""
1306 Currently it handles auto-indent only."""
1308
1307
1309 #debugx('self.indent_current_nsp','pre_readline:')
1308 #debugx('self.indent_current_nsp','pre_readline:')
1310
1309
1311 if self.rl_do_indent:
1310 if self.rl_do_indent:
1312 self.readline.insert_text(self.indent_current_str())
1311 self.readline.insert_text(self.indent_current_str())
1313 if self.rl_next_input is not None:
1312 if self.rl_next_input is not None:
1314 self.readline.insert_text(self.rl_next_input)
1313 self.readline.insert_text(self.rl_next_input)
1315 self.rl_next_input = None
1314 self.rl_next_input = None
1316
1315
1317 def init_readline(self):
1316 def init_readline(self):
1318 """Command history completion/saving/reloading."""
1317 """Command history completion/saving/reloading."""
1319
1318
1320
1319
1321 import IPython.rlineimpl as readline
1320 import IPython.rlineimpl as readline
1322
1321
1323 if not readline.have_readline:
1322 if not readline.have_readline:
1324 self.has_readline = 0
1323 self.has_readline = 0
1325 self.readline = None
1324 self.readline = None
1326 # no point in bugging windows users with this every time:
1325 # no point in bugging windows users with this every time:
1327 warn('Readline services not available on this platform.')
1326 warn('Readline services not available on this platform.')
1328 else:
1327 else:
1329 sys.modules['readline'] = readline
1328 sys.modules['readline'] = readline
1330 import atexit
1329 import atexit
1331 from IPython.completer import IPCompleter
1330 from IPython.completer import IPCompleter
1332 self.Completer = IPCompleter(self,
1331 self.Completer = IPCompleter(self,
1333 self.user_ns,
1332 self.user_ns,
1334 self.user_global_ns,
1333 self.user_global_ns,
1335 self.rc.readline_omit__names,
1334 self.rc.readline_omit__names,
1336 self.alias_table)
1335 self.alias_table)
1337 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1336 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1338 self.strdispatchers['complete_command'] = sdisp
1337 self.strdispatchers['complete_command'] = sdisp
1339 self.Completer.custom_completers = sdisp
1338 self.Completer.custom_completers = sdisp
1340 # Platform-specific configuration
1339 # Platform-specific configuration
1341 if os.name == 'nt':
1340 if os.name == 'nt':
1342 self.readline_startup_hook = readline.set_pre_input_hook
1341 self.readline_startup_hook = readline.set_pre_input_hook
1343 else:
1342 else:
1344 self.readline_startup_hook = readline.set_startup_hook
1343 self.readline_startup_hook = readline.set_startup_hook
1345
1344
1346 # Load user's initrc file (readline config)
1345 # Load user's initrc file (readline config)
1347 # Or if libedit is used, load editrc.
1346 # Or if libedit is used, load editrc.
1348 inputrc_name = os.environ.get('INPUTRC')
1347 inputrc_name = os.environ.get('INPUTRC')
1349 if inputrc_name is None:
1348 if inputrc_name is None:
1350 home_dir = get_home_dir()
1349 home_dir = get_home_dir()
1351 if home_dir is not None:
1350 if home_dir is not None:
1352 inputrc_name = '.inputrc'
1351 inputrc_name = '.inputrc'
1353 if readline.uses_libedit:
1352 if readline.uses_libedit:
1354 inputrc_name = '.editrc'
1353 inputrc_name = '.editrc'
1355 inputrc_name = os.path.join(home_dir, inputrc_name)
1354 inputrc_name = os.path.join(home_dir, inputrc_name)
1356 if os.path.isfile(inputrc_name):
1355 if os.path.isfile(inputrc_name):
1357 try:
1356 try:
1358 readline.read_init_file(inputrc_name)
1357 readline.read_init_file(inputrc_name)
1359 except:
1358 except:
1360 warn('Problems reading readline initialization file <%s>'
1359 warn('Problems reading readline initialization file <%s>'
1361 % inputrc_name)
1360 % inputrc_name)
1362
1361
1363 self.has_readline = 1
1362 self.has_readline = 1
1364 self.readline = readline
1363 self.readline = readline
1365 # save this in sys so embedded copies can restore it properly
1364 # save this in sys so embedded copies can restore it properly
1366 sys.ipcompleter = self.Completer.complete
1365 sys.ipcompleter = self.Completer.complete
1367 self.set_completer()
1366 self.set_completer()
1368
1367
1369 # Configure readline according to user's prefs
1368 # Configure readline according to user's prefs
1370 # This is only done if GNU readline is being used. If libedit
1369 # This is only done if GNU readline is being used. If libedit
1371 # is being used (as on Leopard) the readline config is
1370 # is being used (as on Leopard) the readline config is
1372 # not run as the syntax for libedit is different.
1371 # not run as the syntax for libedit is different.
1373 if not readline.uses_libedit:
1372 if not readline.uses_libedit:
1374 for rlcommand in self.rc.readline_parse_and_bind:
1373 for rlcommand in self.rc.readline_parse_and_bind:
1375 readline.parse_and_bind(rlcommand)
1374 readline.parse_and_bind(rlcommand)
1376
1375
1377 # remove some chars from the delimiters list
1376 # remove some chars from the delimiters list
1378 delims = readline.get_completer_delims()
1377 delims = readline.get_completer_delims()
1379 delims = delims.translate(string._idmap,
1378 delims = delims.translate(string._idmap,
1380 self.rc.readline_remove_delims)
1379 self.rc.readline_remove_delims)
1381 readline.set_completer_delims(delims)
1380 readline.set_completer_delims(delims)
1382 # otherwise we end up with a monster history after a while:
1381 # otherwise we end up with a monster history after a while:
1383 readline.set_history_length(1000)
1382 readline.set_history_length(1000)
1384 try:
1383 try:
1385 #print '*** Reading readline history' # dbg
1384 #print '*** Reading readline history' # dbg
1386 readline.read_history_file(self.histfile)
1385 readline.read_history_file(self.histfile)
1387 except IOError:
1386 except IOError:
1388 pass # It doesn't exist yet.
1387 pass # It doesn't exist yet.
1389
1388
1390 atexit.register(self.atexit_operations)
1389 atexit.register(self.atexit_operations)
1391 del atexit
1390 del atexit
1392
1391
1393 # Configure auto-indent for all platforms
1392 # Configure auto-indent for all platforms
1394 self.set_autoindent(self.rc.autoindent)
1393 self.set_autoindent(self.rc.autoindent)
1395
1394
1396 def ask_yes_no(self,prompt,default=True):
1395 def ask_yes_no(self,prompt,default=True):
1397 if self.rc.quiet:
1396 if self.rc.quiet:
1398 return True
1397 return True
1399 return ask_yes_no(prompt,default)
1398 return ask_yes_no(prompt,default)
1400
1399
1401 def _should_recompile(self,e):
1400 def _should_recompile(self,e):
1402 """Utility routine for edit_syntax_error"""
1401 """Utility routine for edit_syntax_error"""
1403
1402
1404 if e.filename in ('<ipython console>','<input>','<string>',
1403 if e.filename in ('<ipython console>','<input>','<string>',
1405 '<console>','<BackgroundJob compilation>',
1404 '<console>','<BackgroundJob compilation>',
1406 None):
1405 None):
1407
1406
1408 return False
1407 return False
1409 try:
1408 try:
1410 if (self.rc.autoedit_syntax and
1409 if (self.rc.autoedit_syntax and
1411 not self.ask_yes_no('Return to editor to correct syntax error? '
1410 not self.ask_yes_no('Return to editor to correct syntax error? '
1412 '[Y/n] ','y')):
1411 '[Y/n] ','y')):
1413 return False
1412 return False
1414 except EOFError:
1413 except EOFError:
1415 return False
1414 return False
1416
1415
1417 def int0(x):
1416 def int0(x):
1418 try:
1417 try:
1419 return int(x)
1418 return int(x)
1420 except TypeError:
1419 except TypeError:
1421 return 0
1420 return 0
1422 # always pass integer line and offset values to editor hook
1421 # always pass integer line and offset values to editor hook
1423 self.hooks.fix_error_editor(e.filename,
1422 self.hooks.fix_error_editor(e.filename,
1424 int0(e.lineno),int0(e.offset),e.msg)
1423 int0(e.lineno),int0(e.offset),e.msg)
1425 return True
1424 return True
1426
1425
1427 def edit_syntax_error(self):
1426 def edit_syntax_error(self):
1428 """The bottom half of the syntax error handler called in the main loop.
1427 """The bottom half of the syntax error handler called in the main loop.
1429
1428
1430 Loop until syntax error is fixed or user cancels.
1429 Loop until syntax error is fixed or user cancels.
1431 """
1430 """
1432
1431
1433 while self.SyntaxTB.last_syntax_error:
1432 while self.SyntaxTB.last_syntax_error:
1434 # copy and clear last_syntax_error
1433 # copy and clear last_syntax_error
1435 err = self.SyntaxTB.clear_err_state()
1434 err = self.SyntaxTB.clear_err_state()
1436 if not self._should_recompile(err):
1435 if not self._should_recompile(err):
1437 return
1436 return
1438 try:
1437 try:
1439 # may set last_syntax_error again if a SyntaxError is raised
1438 # may set last_syntax_error again if a SyntaxError is raised
1440 self.safe_execfile(err.filename,self.user_ns)
1439 self.safe_execfile(err.filename,self.user_ns)
1441 except:
1440 except:
1442 self.showtraceback()
1441 self.showtraceback()
1443 else:
1442 else:
1444 try:
1443 try:
1445 f = file(err.filename)
1444 f = file(err.filename)
1446 try:
1445 try:
1447 sys.displayhook(f.read())
1446 sys.displayhook(f.read())
1448 finally:
1447 finally:
1449 f.close()
1448 f.close()
1450 except:
1449 except:
1451 self.showtraceback()
1450 self.showtraceback()
1452
1451
1453 def showsyntaxerror(self, filename=None):
1452 def showsyntaxerror(self, filename=None):
1454 """Display the syntax error that just occurred.
1453 """Display the syntax error that just occurred.
1455
1454
1456 This doesn't display a stack trace because there isn't one.
1455 This doesn't display a stack trace because there isn't one.
1457
1456
1458 If a filename is given, it is stuffed in the exception instead
1457 If a filename is given, it is stuffed in the exception instead
1459 of what was there before (because Python's parser always uses
1458 of what was there before (because Python's parser always uses
1460 "<string>" when reading from a string).
1459 "<string>" when reading from a string).
1461 """
1460 """
1462 etype, value, last_traceback = sys.exc_info()
1461 etype, value, last_traceback = sys.exc_info()
1463
1462
1464 # See note about these variables in showtraceback() below
1463 # See note about these variables in showtraceback() below
1465 sys.last_type = etype
1464 sys.last_type = etype
1466 sys.last_value = value
1465 sys.last_value = value
1467 sys.last_traceback = last_traceback
1466 sys.last_traceback = last_traceback
1468
1467
1469 if filename and etype is SyntaxError:
1468 if filename and etype is SyntaxError:
1470 # Work hard to stuff the correct filename in the exception
1469 # Work hard to stuff the correct filename in the exception
1471 try:
1470 try:
1472 msg, (dummy_filename, lineno, offset, line) = value
1471 msg, (dummy_filename, lineno, offset, line) = value
1473 except:
1472 except:
1474 # Not the format we expect; leave it alone
1473 # Not the format we expect; leave it alone
1475 pass
1474 pass
1476 else:
1475 else:
1477 # Stuff in the right filename
1476 # Stuff in the right filename
1478 try:
1477 try:
1479 # Assume SyntaxError is a class exception
1478 # Assume SyntaxError is a class exception
1480 value = SyntaxError(msg, (filename, lineno, offset, line))
1479 value = SyntaxError(msg, (filename, lineno, offset, line))
1481 except:
1480 except:
1482 # If that failed, assume SyntaxError is a string
1481 # If that failed, assume SyntaxError is a string
1483 value = msg, (filename, lineno, offset, line)
1482 value = msg, (filename, lineno, offset, line)
1484 self.SyntaxTB(etype,value,[])
1483 self.SyntaxTB(etype,value,[])
1485
1484
1486 def debugger(self,force=False):
1485 def debugger(self,force=False):
1487 """Call the pydb/pdb debugger.
1486 """Call the pydb/pdb debugger.
1488
1487
1489 Keywords:
1488 Keywords:
1490
1489
1491 - force(False): by default, this routine checks the instance call_pdb
1490 - force(False): by default, this routine checks the instance call_pdb
1492 flag and does not actually invoke the debugger if the flag is false.
1491 flag and does not actually invoke the debugger if the flag is false.
1493 The 'force' option forces the debugger to activate even if the flag
1492 The 'force' option forces the debugger to activate even if the flag
1494 is false.
1493 is false.
1495 """
1494 """
1496
1495
1497 if not (force or self.call_pdb):
1496 if not (force or self.call_pdb):
1498 return
1497 return
1499
1498
1500 if not hasattr(sys,'last_traceback'):
1499 if not hasattr(sys,'last_traceback'):
1501 error('No traceback has been produced, nothing to debug.')
1500 error('No traceback has been produced, nothing to debug.')
1502 return
1501 return
1503
1502
1504 # use pydb if available
1503 # use pydb if available
1505 if Debugger.has_pydb:
1504 if Debugger.has_pydb:
1506 from pydb import pm
1505 from pydb import pm
1507 else:
1506 else:
1508 # fallback to our internal debugger
1507 # fallback to our internal debugger
1509 pm = lambda : self.InteractiveTB.debugger(force=True)
1508 pm = lambda : self.InteractiveTB.debugger(force=True)
1510 self.history_saving_wrapper(pm)()
1509 self.history_saving_wrapper(pm)()
1511
1510
1512 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1511 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1513 """Display the exception that just occurred.
1512 """Display the exception that just occurred.
1514
1513
1515 If nothing is known about the exception, this is the method which
1514 If nothing is known about the exception, this is the method which
1516 should be used throughout the code for presenting user tracebacks,
1515 should be used throughout the code for presenting user tracebacks,
1517 rather than directly invoking the InteractiveTB object.
1516 rather than directly invoking the InteractiveTB object.
1518
1517
1519 A specific showsyntaxerror() also exists, but this method can take
1518 A specific showsyntaxerror() also exists, but this method can take
1520 care of calling it if needed, so unless you are explicitly catching a
1519 care of calling it if needed, so unless you are explicitly catching a
1521 SyntaxError exception, don't try to analyze the stack manually and
1520 SyntaxError exception, don't try to analyze the stack manually and
1522 simply call this method."""
1521 simply call this method."""
1523
1522
1524
1523
1525 # Though this won't be called by syntax errors in the input line,
1524 # Though this won't be called by syntax errors in the input line,
1526 # there may be SyntaxError cases whith imported code.
1525 # there may be SyntaxError cases whith imported code.
1527
1526
1528 try:
1527 try:
1529 if exc_tuple is None:
1528 if exc_tuple is None:
1530 etype, value, tb = sys.exc_info()
1529 etype, value, tb = sys.exc_info()
1531 else:
1530 else:
1532 etype, value, tb = exc_tuple
1531 etype, value, tb = exc_tuple
1533
1532
1534 if etype is SyntaxError:
1533 if etype is SyntaxError:
1535 self.showsyntaxerror(filename)
1534 self.showsyntaxerror(filename)
1536 elif etype is IPython.ipapi.UsageError:
1535 elif etype is IPython.ipapi.UsageError:
1537 print "UsageError:", value
1536 print "UsageError:", value
1538 else:
1537 else:
1539 # WARNING: these variables are somewhat deprecated and not
1538 # WARNING: these variables are somewhat deprecated and not
1540 # necessarily safe to use in a threaded environment, but tools
1539 # necessarily safe to use in a threaded environment, but tools
1541 # like pdb depend on their existence, so let's set them. If we
1540 # like pdb depend on their existence, so let's set them. If we
1542 # find problems in the field, we'll need to revisit their use.
1541 # find problems in the field, we'll need to revisit their use.
1543 sys.last_type = etype
1542 sys.last_type = etype
1544 sys.last_value = value
1543 sys.last_value = value
1545 sys.last_traceback = tb
1544 sys.last_traceback = tb
1546
1545
1547 if etype in self.custom_exceptions:
1546 if etype in self.custom_exceptions:
1548 self.CustomTB(etype,value,tb)
1547 self.CustomTB(etype,value,tb)
1549 else:
1548 else:
1550 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1549 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1551 if self.InteractiveTB.call_pdb and self.has_readline:
1550 if self.InteractiveTB.call_pdb and self.has_readline:
1552 # pdb mucks up readline, fix it back
1551 # pdb mucks up readline, fix it back
1553 self.set_completer()
1552 self.set_completer()
1554 except KeyboardInterrupt:
1553 except KeyboardInterrupt:
1555 self.write("\nKeyboardInterrupt\n")
1554 self.write("\nKeyboardInterrupt\n")
1556
1555
1557
1556
1558
1557
1559 def mainloop(self,banner=None):
1558 def mainloop(self,banner=None):
1560 """Creates the local namespace and starts the mainloop.
1559 """Creates the local namespace and starts the mainloop.
1561
1560
1562 If an optional banner argument is given, it will override the
1561 If an optional banner argument is given, it will override the
1563 internally created default banner."""
1562 internally created default banner."""
1564
1563
1565 if self.rc.c: # Emulate Python's -c option
1564 if self.rc.c: # Emulate Python's -c option
1566 self.exec_init_cmd()
1565 self.exec_init_cmd()
1567 if banner is None:
1566 if banner is None:
1568 if not self.rc.banner:
1567 if not self.rc.banner:
1569 banner = ''
1568 banner = ''
1570 # banner is string? Use it directly!
1569 # banner is string? Use it directly!
1571 elif isinstance(self.rc.banner,basestring):
1570 elif isinstance(self.rc.banner,basestring):
1572 banner = self.rc.banner
1571 banner = self.rc.banner
1573 else:
1572 else:
1574 banner = self.BANNER+self.banner2
1573 banner = self.BANNER+self.banner2
1575
1574
1576 while 1:
1575 while 1:
1577 try:
1576 try:
1578 self.interact(banner)
1577 self.interact(banner)
1579 #self.interact_with_readline()
1578 #self.interact_with_readline()
1580 # XXX for testing of a readline-decoupled repl loop, call interact_with_readline above
1579 # XXX for testing of a readline-decoupled repl loop, call interact_with_readline above
1581
1580
1582 break
1581 break
1583 except KeyboardInterrupt:
1582 except KeyboardInterrupt:
1584 # this should not be necessary, but KeyboardInterrupt
1583 # this should not be necessary, but KeyboardInterrupt
1585 # handling seems rather unpredictable...
1584 # handling seems rather unpredictable...
1586 self.write("\nKeyboardInterrupt in interact()\n")
1585 self.write("\nKeyboardInterrupt in interact()\n")
1587
1586
1588 def exec_init_cmd(self):
1587 def exec_init_cmd(self):
1589 """Execute a command given at the command line.
1588 """Execute a command given at the command line.
1590
1589
1591 This emulates Python's -c option."""
1590 This emulates Python's -c option."""
1592
1591
1593 #sys.argv = ['-c']
1592 #sys.argv = ['-c']
1594 self.push(self.prefilter(self.rc.c, False))
1593 self.push(self.prefilter(self.rc.c, False))
1595 if not self.rc.interact:
1594 if not self.rc.interact:
1596 self.exit_now = True
1595 self.exit_now = True
1597
1596
1598 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1597 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1599 """Embeds IPython into a running python program.
1598 """Embeds IPython into a running python program.
1600
1599
1601 Input:
1600 Input:
1602
1601
1603 - header: An optional header message can be specified.
1602 - header: An optional header message can be specified.
1604
1603
1605 - local_ns, global_ns: working namespaces. If given as None, the
1604 - local_ns, global_ns: working namespaces. If given as None, the
1606 IPython-initialized one is updated with __main__.__dict__, so that
1605 IPython-initialized one is updated with __main__.__dict__, so that
1607 program variables become visible but user-specific configuration
1606 program variables become visible but user-specific configuration
1608 remains possible.
1607 remains possible.
1609
1608
1610 - stack_depth: specifies how many levels in the stack to go to
1609 - stack_depth: specifies how many levels in the stack to go to
1611 looking for namespaces (when local_ns and global_ns are None). This
1610 looking for namespaces (when local_ns and global_ns are None). This
1612 allows an intermediate caller to make sure that this function gets
1611 allows an intermediate caller to make sure that this function gets
1613 the namespace from the intended level in the stack. By default (0)
1612 the namespace from the intended level in the stack. By default (0)
1614 it will get its locals and globals from the immediate caller.
1613 it will get its locals and globals from the immediate caller.
1615
1614
1616 Warning: it's possible to use this in a program which is being run by
1615 Warning: it's possible to use this in a program which is being run by
1617 IPython itself (via %run), but some funny things will happen (a few
1616 IPython itself (via %run), but some funny things will happen (a few
1618 globals get overwritten). In the future this will be cleaned up, as
1617 globals get overwritten). In the future this will be cleaned up, as
1619 there is no fundamental reason why it can't work perfectly."""
1618 there is no fundamental reason why it can't work perfectly."""
1620
1619
1621 # Get locals and globals from caller
1620 # Get locals and globals from caller
1622 if local_ns is None or global_ns is None:
1621 if local_ns is None or global_ns is None:
1623 call_frame = sys._getframe(stack_depth).f_back
1622 call_frame = sys._getframe(stack_depth).f_back
1624
1623
1625 if local_ns is None:
1624 if local_ns is None:
1626 local_ns = call_frame.f_locals
1625 local_ns = call_frame.f_locals
1627 if global_ns is None:
1626 if global_ns is None:
1628 global_ns = call_frame.f_globals
1627 global_ns = call_frame.f_globals
1629
1628
1630 # Update namespaces and fire up interpreter
1629 # Update namespaces and fire up interpreter
1631
1630
1632 # The global one is easy, we can just throw it in
1631 # The global one is easy, we can just throw it in
1633 self.user_global_ns = global_ns
1632 self.user_global_ns = global_ns
1634
1633
1635 # but the user/local one is tricky: ipython needs it to store internal
1634 # but the user/local one is tricky: ipython needs it to store internal
1636 # data, but we also need the locals. We'll copy locals in the user
1635 # data, but we also need the locals. We'll copy locals in the user
1637 # one, but will track what got copied so we can delete them at exit.
1636 # one, but will track what got copied so we can delete them at exit.
1638 # This is so that a later embedded call doesn't see locals from a
1637 # This is so that a later embedded call doesn't see locals from a
1639 # previous call (which most likely existed in a separate scope).
1638 # previous call (which most likely existed in a separate scope).
1640 local_varnames = local_ns.keys()
1639 local_varnames = local_ns.keys()
1641 self.user_ns.update(local_ns)
1640 self.user_ns.update(local_ns)
1642 #self.user_ns['local_ns'] = local_ns # dbg
1641 #self.user_ns['local_ns'] = local_ns # dbg
1643
1642
1644 # Patch for global embedding to make sure that things don't overwrite
1643 # Patch for global embedding to make sure that things don't overwrite
1645 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1644 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1646 # FIXME. Test this a bit more carefully (the if.. is new)
1645 # FIXME. Test this a bit more carefully (the if.. is new)
1647 if local_ns is None and global_ns is None:
1646 if local_ns is None and global_ns is None:
1648 self.user_global_ns.update(__main__.__dict__)
1647 self.user_global_ns.update(__main__.__dict__)
1649
1648
1650 # make sure the tab-completer has the correct frame information, so it
1649 # make sure the tab-completer has the correct frame information, so it
1651 # actually completes using the frame's locals/globals
1650 # actually completes using the frame's locals/globals
1652 self.set_completer_frame()
1651 self.set_completer_frame()
1653
1652
1654 # before activating the interactive mode, we need to make sure that
1653 # before activating the interactive mode, we need to make sure that
1655 # all names in the builtin namespace needed by ipython point to
1654 # all names in the builtin namespace needed by ipython point to
1656 # ourselves, and not to other instances.
1655 # ourselves, and not to other instances.
1657 self.add_builtins()
1656 self.add_builtins()
1658
1657
1659 self.interact(header)
1658 self.interact(header)
1660
1659
1661 # now, purge out the user namespace from anything we might have added
1660 # now, purge out the user namespace from anything we might have added
1662 # from the caller's local namespace
1661 # from the caller's local namespace
1663 delvar = self.user_ns.pop
1662 delvar = self.user_ns.pop
1664 for var in local_varnames:
1663 for var in local_varnames:
1665 delvar(var,None)
1664 delvar(var,None)
1666 # and clean builtins we may have overridden
1665 # and clean builtins we may have overridden
1667 self.clean_builtins()
1666 self.clean_builtins()
1668
1667
1669 def interact_prompt(self):
1668 def interact_prompt(self):
1670 """ Print the prompt (in read-eval-print loop)
1669 """ Print the prompt (in read-eval-print loop)
1671
1670
1672 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1671 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1673 used in standard IPython flow.
1672 used in standard IPython flow.
1674 """
1673 """
1675 if self.more:
1674 if self.more:
1676 try:
1675 try:
1677 prompt = self.hooks.generate_prompt(True)
1676 prompt = self.hooks.generate_prompt(True)
1678 except:
1677 except:
1679 self.showtraceback()
1678 self.showtraceback()
1680 if self.autoindent:
1679 if self.autoindent:
1681 self.rl_do_indent = True
1680 self.rl_do_indent = True
1682
1681
1683 else:
1682 else:
1684 try:
1683 try:
1685 prompt = self.hooks.generate_prompt(False)
1684 prompt = self.hooks.generate_prompt(False)
1686 except:
1685 except:
1687 self.showtraceback()
1686 self.showtraceback()
1688 self.write(prompt)
1687 self.write(prompt)
1689
1688
1690 def interact_handle_input(self,line):
1689 def interact_handle_input(self,line):
1691 """ Handle the input line (in read-eval-print loop)
1690 """ Handle the input line (in read-eval-print loop)
1692
1691
1693 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1692 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1694 used in standard IPython flow.
1693 used in standard IPython flow.
1695 """
1694 """
1696 if line.lstrip() == line:
1695 if line.lstrip() == line:
1697 self.shadowhist.add(line.strip())
1696 self.shadowhist.add(line.strip())
1698 lineout = self.prefilter(line,self.more)
1697 lineout = self.prefilter(line,self.more)
1699
1698
1700 if line.strip():
1699 if line.strip():
1701 if self.more:
1700 if self.more:
1702 self.input_hist_raw[-1] += '%s\n' % line
1701 self.input_hist_raw[-1] += '%s\n' % line
1703 else:
1702 else:
1704 self.input_hist_raw.append('%s\n' % line)
1703 self.input_hist_raw.append('%s\n' % line)
1705
1704
1706
1705
1707 self.more = self.push(lineout)
1706 self.more = self.push(lineout)
1708 if (self.SyntaxTB.last_syntax_error and
1707 if (self.SyntaxTB.last_syntax_error and
1709 self.rc.autoedit_syntax):
1708 self.rc.autoedit_syntax):
1710 self.edit_syntax_error()
1709 self.edit_syntax_error()
1711
1710
1712 def interact_with_readline(self):
1711 def interact_with_readline(self):
1713 """ Demo of using interact_handle_input, interact_prompt
1712 """ Demo of using interact_handle_input, interact_prompt
1714
1713
1715 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1714 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1716 it should work like this.
1715 it should work like this.
1717 """
1716 """
1718 self.readline_startup_hook(self.pre_readline)
1717 self.readline_startup_hook(self.pre_readline)
1719 while not self.exit_now:
1718 while not self.exit_now:
1720 self.interact_prompt()
1719 self.interact_prompt()
1721 if self.more:
1720 if self.more:
1722 self.rl_do_indent = True
1721 self.rl_do_indent = True
1723 else:
1722 else:
1724 self.rl_do_indent = False
1723 self.rl_do_indent = False
1725 line = raw_input_original().decode(self.stdin_encoding)
1724 line = raw_input_original().decode(self.stdin_encoding)
1726 self.interact_handle_input(line)
1725 self.interact_handle_input(line)
1727
1726
1728
1727
1729 def interact(self, banner=None):
1728 def interact(self, banner=None):
1730 """Closely emulate the interactive Python console.
1729 """Closely emulate the interactive Python console.
1731
1730
1732 The optional banner argument specify the banner to print
1731 The optional banner argument specify the banner to print
1733 before the first interaction; by default it prints a banner
1732 before the first interaction; by default it prints a banner
1734 similar to the one printed by the real Python interpreter,
1733 similar to the one printed by the real Python interpreter,
1735 followed by the current class name in parentheses (so as not
1734 followed by the current class name in parentheses (so as not
1736 to confuse this with the real interpreter -- since it's so
1735 to confuse this with the real interpreter -- since it's so
1737 close!).
1736 close!).
1738
1737
1739 """
1738 """
1740
1739
1741 if self.exit_now:
1740 if self.exit_now:
1742 # batch run -> do not interact
1741 # batch run -> do not interact
1743 return
1742 return
1744 cprt = 'Type "copyright", "credits" or "license" for more information.'
1743 cprt = 'Type "copyright", "credits" or "license" for more information.'
1745 if banner is None:
1744 if banner is None:
1746 self.write("Python %s on %s\n%s\n(%s)\n" %
1745 self.write("Python %s on %s\n%s\n(%s)\n" %
1747 (sys.version, sys.platform, cprt,
1746 (sys.version, sys.platform, cprt,
1748 self.__class__.__name__))
1747 self.__class__.__name__))
1749 else:
1748 else:
1750 self.write(banner)
1749 self.write(banner)
1751
1750
1752 more = 0
1751 more = 0
1753
1752
1754 # Mark activity in the builtins
1753 # Mark activity in the builtins
1755 __builtin__.__dict__['__IPYTHON__active'] += 1
1754 __builtin__.__dict__['__IPYTHON__active'] += 1
1756
1755
1757 if self.has_readline:
1756 if self.has_readline:
1758 self.readline_startup_hook(self.pre_readline)
1757 self.readline_startup_hook(self.pre_readline)
1759 # exit_now is set by a call to %Exit or %Quit
1758 # exit_now is set by a call to %Exit or %Quit
1760
1759
1761 while not self.exit_now:
1760 while not self.exit_now:
1762 self.hooks.pre_prompt_hook()
1761 self.hooks.pre_prompt_hook()
1763 if more:
1762 if more:
1764 try:
1763 try:
1765 prompt = self.hooks.generate_prompt(True)
1764 prompt = self.hooks.generate_prompt(True)
1766 except:
1765 except:
1767 self.showtraceback()
1766 self.showtraceback()
1768 if self.autoindent:
1767 if self.autoindent:
1769 self.rl_do_indent = True
1768 self.rl_do_indent = True
1770
1769
1771 else:
1770 else:
1772 try:
1771 try:
1773 prompt = self.hooks.generate_prompt(False)
1772 prompt = self.hooks.generate_prompt(False)
1774 except:
1773 except:
1775 self.showtraceback()
1774 self.showtraceback()
1776 try:
1775 try:
1777 line = self.raw_input(prompt,more)
1776 line = self.raw_input(prompt,more)
1778 if self.exit_now:
1777 if self.exit_now:
1779 # quick exit on sys.std[in|out] close
1778 # quick exit on sys.std[in|out] close
1780 break
1779 break
1781 if self.autoindent:
1780 if self.autoindent:
1782 self.rl_do_indent = False
1781 self.rl_do_indent = False
1783
1782
1784 except KeyboardInterrupt:
1783 except KeyboardInterrupt:
1785 #double-guard against keyboardinterrupts during kbdint handling
1784 #double-guard against keyboardinterrupts during kbdint handling
1786 try:
1785 try:
1787 self.write('\nKeyboardInterrupt\n')
1786 self.write('\nKeyboardInterrupt\n')
1788 self.resetbuffer()
1787 self.resetbuffer()
1789 # keep cache in sync with the prompt counter:
1788 # keep cache in sync with the prompt counter:
1790 self.outputcache.prompt_count -= 1
1789 self.outputcache.prompt_count -= 1
1791
1790
1792 if self.autoindent:
1791 if self.autoindent:
1793 self.indent_current_nsp = 0
1792 self.indent_current_nsp = 0
1794 more = 0
1793 more = 0
1795 except KeyboardInterrupt:
1794 except KeyboardInterrupt:
1796 pass
1795 pass
1797 except EOFError:
1796 except EOFError:
1798 if self.autoindent:
1797 if self.autoindent:
1799 self.rl_do_indent = False
1798 self.rl_do_indent = False
1800 self.readline_startup_hook(None)
1799 self.readline_startup_hook(None)
1801 self.write('\n')
1800 self.write('\n')
1802 self.exit()
1801 self.exit()
1803 except bdb.BdbQuit:
1802 except bdb.BdbQuit:
1804 warn('The Python debugger has exited with a BdbQuit exception.\n'
1803 warn('The Python debugger has exited with a BdbQuit exception.\n'
1805 'Because of how pdb handles the stack, it is impossible\n'
1804 'Because of how pdb handles the stack, it is impossible\n'
1806 'for IPython to properly format this particular exception.\n'
1805 'for IPython to properly format this particular exception.\n'
1807 'IPython will resume normal operation.')
1806 'IPython will resume normal operation.')
1808 except:
1807 except:
1809 # exceptions here are VERY RARE, but they can be triggered
1808 # exceptions here are VERY RARE, but they can be triggered
1810 # asynchronously by signal handlers, for example.
1809 # asynchronously by signal handlers, for example.
1811 self.showtraceback()
1810 self.showtraceback()
1812 else:
1811 else:
1813 more = self.push(line)
1812 more = self.push(line)
1814 if (self.SyntaxTB.last_syntax_error and
1813 if (self.SyntaxTB.last_syntax_error and
1815 self.rc.autoedit_syntax):
1814 self.rc.autoedit_syntax):
1816 self.edit_syntax_error()
1815 self.edit_syntax_error()
1817
1816
1818 # We are off again...
1817 # We are off again...
1819 __builtin__.__dict__['__IPYTHON__active'] -= 1
1818 __builtin__.__dict__['__IPYTHON__active'] -= 1
1820
1819
1821 def excepthook(self, etype, value, tb):
1820 def excepthook(self, etype, value, tb):
1822 """One more defense for GUI apps that call sys.excepthook.
1821 """One more defense for GUI apps that call sys.excepthook.
1823
1822
1824 GUI frameworks like wxPython trap exceptions and call
1823 GUI frameworks like wxPython trap exceptions and call
1825 sys.excepthook themselves. I guess this is a feature that
1824 sys.excepthook themselves. I guess this is a feature that
1826 enables them to keep running after exceptions that would
1825 enables them to keep running after exceptions that would
1827 otherwise kill their mainloop. This is a bother for IPython
1826 otherwise kill their mainloop. This is a bother for IPython
1828 which excepts to catch all of the program exceptions with a try:
1827 which excepts to catch all of the program exceptions with a try:
1829 except: statement.
1828 except: statement.
1830
1829
1831 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1830 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1832 any app directly invokes sys.excepthook, it will look to the user like
1831 any app directly invokes sys.excepthook, it will look to the user like
1833 IPython crashed. In order to work around this, we can disable the
1832 IPython crashed. In order to work around this, we can disable the
1834 CrashHandler and replace it with this excepthook instead, which prints a
1833 CrashHandler and replace it with this excepthook instead, which prints a
1835 regular traceback using our InteractiveTB. In this fashion, apps which
1834 regular traceback using our InteractiveTB. In this fashion, apps which
1836 call sys.excepthook will generate a regular-looking exception from
1835 call sys.excepthook will generate a regular-looking exception from
1837 IPython, and the CrashHandler will only be triggered by real IPython
1836 IPython, and the CrashHandler will only be triggered by real IPython
1838 crashes.
1837 crashes.
1839
1838
1840 This hook should be used sparingly, only in places which are not likely
1839 This hook should be used sparingly, only in places which are not likely
1841 to be true IPython errors.
1840 to be true IPython errors.
1842 """
1841 """
1843 self.showtraceback((etype,value,tb),tb_offset=0)
1842 self.showtraceback((etype,value,tb),tb_offset=0)
1844
1843
1845 def expand_aliases(self,fn,rest):
1844 def expand_aliases(self,fn,rest):
1846 """ Expand multiple levels of aliases:
1845 """ Expand multiple levels of aliases:
1847
1846
1848 if:
1847 if:
1849
1848
1850 alias foo bar /tmp
1849 alias foo bar /tmp
1851 alias baz foo
1850 alias baz foo
1852
1851
1853 then:
1852 then:
1854
1853
1855 baz huhhahhei -> bar /tmp huhhahhei
1854 baz huhhahhei -> bar /tmp huhhahhei
1856
1855
1857 """
1856 """
1858 line = fn + " " + rest
1857 line = fn + " " + rest
1859
1858
1860 done = Set()
1859 done = Set()
1861 while 1:
1860 while 1:
1862 pre,fn,rest = prefilter.splitUserInput(line,
1861 pre,fn,rest = prefilter.splitUserInput(line,
1863 prefilter.shell_line_split)
1862 prefilter.shell_line_split)
1864 if fn in self.alias_table:
1863 if fn in self.alias_table:
1865 if fn in done:
1864 if fn in done:
1866 warn("Cyclic alias definition, repeated '%s'" % fn)
1865 warn("Cyclic alias definition, repeated '%s'" % fn)
1867 return ""
1866 return ""
1868 done.add(fn)
1867 done.add(fn)
1869
1868
1870 l2 = self.transform_alias(fn,rest)
1869 l2 = self.transform_alias(fn,rest)
1871 # dir -> dir
1870 # dir -> dir
1872 # print "alias",line, "->",l2 #dbg
1871 # print "alias",line, "->",l2 #dbg
1873 if l2 == line:
1872 if l2 == line:
1874 break
1873 break
1875 # ls -> ls -F should not recurse forever
1874 # ls -> ls -F should not recurse forever
1876 if l2.split(None,1)[0] == line.split(None,1)[0]:
1875 if l2.split(None,1)[0] == line.split(None,1)[0]:
1877 line = l2
1876 line = l2
1878 break
1877 break
1879
1878
1880 line=l2
1879 line=l2
1881
1880
1882
1881
1883 # print "al expand to",line #dbg
1882 # print "al expand to",line #dbg
1884 else:
1883 else:
1885 break
1884 break
1886
1885
1887 return line
1886 return line
1888
1887
1889 def transform_alias(self, alias,rest=''):
1888 def transform_alias(self, alias,rest=''):
1890 """ Transform alias to system command string.
1889 """ Transform alias to system command string.
1891 """
1890 """
1892 trg = self.alias_table[alias]
1891 trg = self.alias_table[alias]
1893
1892
1894 nargs,cmd = trg
1893 nargs,cmd = trg
1895 # print trg #dbg
1894 # print trg #dbg
1896 if ' ' in cmd and os.path.isfile(cmd):
1895 if ' ' in cmd and os.path.isfile(cmd):
1897 cmd = '"%s"' % cmd
1896 cmd = '"%s"' % cmd
1898
1897
1899 # Expand the %l special to be the user's input line
1898 # Expand the %l special to be the user's input line
1900 if cmd.find('%l') >= 0:
1899 if cmd.find('%l') >= 0:
1901 cmd = cmd.replace('%l',rest)
1900 cmd = cmd.replace('%l',rest)
1902 rest = ''
1901 rest = ''
1903 if nargs==0:
1902 if nargs==0:
1904 # Simple, argument-less aliases
1903 # Simple, argument-less aliases
1905 cmd = '%s %s' % (cmd,rest)
1904 cmd = '%s %s' % (cmd,rest)
1906 else:
1905 else:
1907 # Handle aliases with positional arguments
1906 # Handle aliases with positional arguments
1908 args = rest.split(None,nargs)
1907 args = rest.split(None,nargs)
1909 if len(args)< nargs:
1908 if len(args)< nargs:
1910 error('Alias <%s> requires %s arguments, %s given.' %
1909 error('Alias <%s> requires %s arguments, %s given.' %
1911 (alias,nargs,len(args)))
1910 (alias,nargs,len(args)))
1912 return None
1911 return None
1913 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1912 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1914 # Now call the macro, evaluating in the user's namespace
1913 # Now call the macro, evaluating in the user's namespace
1915 #print 'new command: <%r>' % cmd # dbg
1914 #print 'new command: <%r>' % cmd # dbg
1916 return cmd
1915 return cmd
1917
1916
1918 def call_alias(self,alias,rest=''):
1917 def call_alias(self,alias,rest=''):
1919 """Call an alias given its name and the rest of the line.
1918 """Call an alias given its name and the rest of the line.
1920
1919
1921 This is only used to provide backwards compatibility for users of
1920 This is only used to provide backwards compatibility for users of
1922 ipalias(), use of which is not recommended for anymore."""
1921 ipalias(), use of which is not recommended for anymore."""
1923
1922
1924 # Now call the macro, evaluating in the user's namespace
1923 # Now call the macro, evaluating in the user's namespace
1925 cmd = self.transform_alias(alias, rest)
1924 cmd = self.transform_alias(alias, rest)
1926 try:
1925 try:
1927 self.system(cmd)
1926 self.system(cmd)
1928 except:
1927 except:
1929 self.showtraceback()
1928 self.showtraceback()
1930
1929
1931 def indent_current_str(self):
1930 def indent_current_str(self):
1932 """return the current level of indentation as a string"""
1931 """return the current level of indentation as a string"""
1933 return self.indent_current_nsp * ' '
1932 return self.indent_current_nsp * ' '
1934
1933
1935 def autoindent_update(self,line):
1934 def autoindent_update(self,line):
1936 """Keep track of the indent level."""
1935 """Keep track of the indent level."""
1937
1936
1938 #debugx('line')
1937 #debugx('line')
1939 #debugx('self.indent_current_nsp')
1938 #debugx('self.indent_current_nsp')
1940 if self.autoindent:
1939 if self.autoindent:
1941 if line:
1940 if line:
1942 inisp = num_ini_spaces(line)
1941 inisp = num_ini_spaces(line)
1943 if inisp < self.indent_current_nsp:
1942 if inisp < self.indent_current_nsp:
1944 self.indent_current_nsp = inisp
1943 self.indent_current_nsp = inisp
1945
1944
1946 if line[-1] == ':':
1945 if line[-1] == ':':
1947 self.indent_current_nsp += 4
1946 self.indent_current_nsp += 4
1948 elif dedent_re.match(line):
1947 elif dedent_re.match(line):
1949 self.indent_current_nsp -= 4
1948 self.indent_current_nsp -= 4
1950 else:
1949 else:
1951 self.indent_current_nsp = 0
1950 self.indent_current_nsp = 0
1952
1951
1953 def runlines(self,lines):
1952 def runlines(self,lines):
1954 """Run a string of one or more lines of source.
1953 """Run a string of one or more lines of source.
1955
1954
1956 This method is capable of running a string containing multiple source
1955 This method is capable of running a string containing multiple source
1957 lines, as if they had been entered at the IPython prompt. Since it
1956 lines, as if they had been entered at the IPython prompt. Since it
1958 exposes IPython's processing machinery, the given strings can contain
1957 exposes IPython's processing machinery, the given strings can contain
1959 magic calls (%magic), special shell access (!cmd), etc."""
1958 magic calls (%magic), special shell access (!cmd), etc."""
1960
1959
1961 # We must start with a clean buffer, in case this is run from an
1960 # We must start with a clean buffer, in case this is run from an
1962 # interactive IPython session (via a magic, for example).
1961 # interactive IPython session (via a magic, for example).
1963 self.resetbuffer()
1962 self.resetbuffer()
1964 lines = lines.split('\n')
1963 lines = lines.split('\n')
1965 more = 0
1964 more = 0
1966
1965
1967 for line in lines:
1966 for line in lines:
1968 # skip blank lines so we don't mess up the prompt counter, but do
1967 # skip blank lines so we don't mess up the prompt counter, but do
1969 # NOT skip even a blank line if we are in a code block (more is
1968 # NOT skip even a blank line if we are in a code block (more is
1970 # true)
1969 # true)
1971
1970
1972
1971
1973 if line or more:
1972 if line or more:
1974 # push to raw history, so hist line numbers stay in sync
1973 # push to raw history, so hist line numbers stay in sync
1975 self.input_hist_raw.append("# " + line + "\n")
1974 self.input_hist_raw.append("# " + line + "\n")
1976 more = self.push(self.prefilter(line,more))
1975 more = self.push(self.prefilter(line,more))
1977 # IPython's runsource returns None if there was an error
1976 # IPython's runsource returns None if there was an error
1978 # compiling the code. This allows us to stop processing right
1977 # compiling the code. This allows us to stop processing right
1979 # away, so the user gets the error message at the right place.
1978 # away, so the user gets the error message at the right place.
1980 if more is None:
1979 if more is None:
1981 break
1980 break
1982 else:
1981 else:
1983 self.input_hist_raw.append("\n")
1982 self.input_hist_raw.append("\n")
1984 # final newline in case the input didn't have it, so that the code
1983 # final newline in case the input didn't have it, so that the code
1985 # actually does get executed
1984 # actually does get executed
1986 if more:
1985 if more:
1987 self.push('\n')
1986 self.push('\n')
1988
1987
1989 def runsource(self, source, filename='<input>', symbol='single'):
1988 def runsource(self, source, filename='<input>', symbol='single'):
1990 """Compile and run some source in the interpreter.
1989 """Compile and run some source in the interpreter.
1991
1990
1992 Arguments are as for compile_command().
1991 Arguments are as for compile_command().
1993
1992
1994 One several things can happen:
1993 One several things can happen:
1995
1994
1996 1) The input is incorrect; compile_command() raised an
1995 1) The input is incorrect; compile_command() raised an
1997 exception (SyntaxError or OverflowError). A syntax traceback
1996 exception (SyntaxError or OverflowError). A syntax traceback
1998 will be printed by calling the showsyntaxerror() method.
1997 will be printed by calling the showsyntaxerror() method.
1999
1998
2000 2) The input is incomplete, and more input is required;
1999 2) The input is incomplete, and more input is required;
2001 compile_command() returned None. Nothing happens.
2000 compile_command() returned None. Nothing happens.
2002
2001
2003 3) The input is complete; compile_command() returned a code
2002 3) The input is complete; compile_command() returned a code
2004 object. The code is executed by calling self.runcode() (which
2003 object. The code is executed by calling self.runcode() (which
2005 also handles run-time exceptions, except for SystemExit).
2004 also handles run-time exceptions, except for SystemExit).
2006
2005
2007 The return value is:
2006 The return value is:
2008
2007
2009 - True in case 2
2008 - True in case 2
2010
2009
2011 - False in the other cases, unless an exception is raised, where
2010 - False in the other cases, unless an exception is raised, where
2012 None is returned instead. This can be used by external callers to
2011 None is returned instead. This can be used by external callers to
2013 know whether to continue feeding input or not.
2012 know whether to continue feeding input or not.
2014
2013
2015 The return value can be used to decide whether to use sys.ps1 or
2014 The return value can be used to decide whether to use sys.ps1 or
2016 sys.ps2 to prompt the next line."""
2015 sys.ps2 to prompt the next line."""
2017
2016
2018 # if the source code has leading blanks, add 'if 1:\n' to it
2017 # if the source code has leading blanks, add 'if 1:\n' to it
2019 # this allows execution of indented pasted code. It is tempting
2018 # this allows execution of indented pasted code. It is tempting
2020 # to add '\n' at the end of source to run commands like ' a=1'
2019 # to add '\n' at the end of source to run commands like ' a=1'
2021 # directly, but this fails for more complicated scenarios
2020 # directly, but this fails for more complicated scenarios
2022 source=source.encode(self.stdin_encoding)
2021 source=source.encode(self.stdin_encoding)
2023 if source[:1] in [' ', '\t']:
2022 if source[:1] in [' ', '\t']:
2024 source = 'if 1:\n%s' % source
2023 source = 'if 1:\n%s' % source
2025
2024
2026 try:
2025 try:
2027 code = self.compile(source,filename,symbol)
2026 code = self.compile(source,filename,symbol)
2028 except (OverflowError, SyntaxError, ValueError, TypeError):
2027 except (OverflowError, SyntaxError, ValueError, TypeError):
2029 # Case 1
2028 # Case 1
2030 self.showsyntaxerror(filename)
2029 self.showsyntaxerror(filename)
2031 return None
2030 return None
2032
2031
2033 if code is None:
2032 if code is None:
2034 # Case 2
2033 # Case 2
2035 return True
2034 return True
2036
2035
2037 # Case 3
2036 # Case 3
2038 # We store the code object so that threaded shells and
2037 # We store the code object so that threaded shells and
2039 # custom exception handlers can access all this info if needed.
2038 # custom exception handlers can access all this info if needed.
2040 # The source corresponding to this can be obtained from the
2039 # The source corresponding to this can be obtained from the
2041 # buffer attribute as '\n'.join(self.buffer).
2040 # buffer attribute as '\n'.join(self.buffer).
2042 self.code_to_run = code
2041 self.code_to_run = code
2043 # now actually execute the code object
2042 # now actually execute the code object
2044 if self.runcode(code) == 0:
2043 if self.runcode(code) == 0:
2045 return False
2044 return False
2046 else:
2045 else:
2047 return None
2046 return None
2048
2047
2049 def runcode(self,code_obj):
2048 def runcode(self,code_obj):
2050 """Execute a code object.
2049 """Execute a code object.
2051
2050
2052 When an exception occurs, self.showtraceback() is called to display a
2051 When an exception occurs, self.showtraceback() is called to display a
2053 traceback.
2052 traceback.
2054
2053
2055 Return value: a flag indicating whether the code to be run completed
2054 Return value: a flag indicating whether the code to be run completed
2056 successfully:
2055 successfully:
2057
2056
2058 - 0: successful execution.
2057 - 0: successful execution.
2059 - 1: an error occurred.
2058 - 1: an error occurred.
2060 """
2059 """
2061
2060
2062 # Set our own excepthook in case the user code tries to call it
2061 # Set our own excepthook in case the user code tries to call it
2063 # directly, so that the IPython crash handler doesn't get triggered
2062 # directly, so that the IPython crash handler doesn't get triggered
2064 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2063 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2065
2064
2066 # we save the original sys.excepthook in the instance, in case config
2065 # we save the original sys.excepthook in the instance, in case config
2067 # code (such as magics) needs access to it.
2066 # code (such as magics) needs access to it.
2068 self.sys_excepthook = old_excepthook
2067 self.sys_excepthook = old_excepthook
2069 outflag = 1 # happens in more places, so it's easier as default
2068 outflag = 1 # happens in more places, so it's easier as default
2070 try:
2069 try:
2071 try:
2070 try:
2072 self.hooks.pre_runcode_hook()
2071 self.hooks.pre_runcode_hook()
2073 # Embedded instances require separate global/local namespaces
2072 exec code_obj in self.user_global_ns, self.user_ns
2074 # so they can see both the surrounding (local) namespace and
2075 # the module-level globals when called inside another function.
2076 if self.embedded:
2077 exec code_obj in self.user_global_ns, self.user_ns
2078 # Normal (non-embedded) instances should only have a single
2079 # namespace for user code execution, otherwise functions won't
2080 # see interactive top-level globals.
2081 else:
2082 exec code_obj in self.user_ns
2083 finally:
2073 finally:
2084 # Reset our crash handler in place
2074 # Reset our crash handler in place
2085 sys.excepthook = old_excepthook
2075 sys.excepthook = old_excepthook
2086 except SystemExit:
2076 except SystemExit:
2087 self.resetbuffer()
2077 self.resetbuffer()
2088 self.showtraceback()
2078 self.showtraceback()
2089 warn("Type %exit or %quit to exit IPython "
2079 warn("Type %exit or %quit to exit IPython "
2090 "(%Exit or %Quit do so unconditionally).",level=1)
2080 "(%Exit or %Quit do so unconditionally).",level=1)
2091 except self.custom_exceptions:
2081 except self.custom_exceptions:
2092 etype,value,tb = sys.exc_info()
2082 etype,value,tb = sys.exc_info()
2093 self.CustomTB(etype,value,tb)
2083 self.CustomTB(etype,value,tb)
2094 except:
2084 except:
2095 self.showtraceback()
2085 self.showtraceback()
2096 else:
2086 else:
2097 outflag = 0
2087 outflag = 0
2098 if softspace(sys.stdout, 0):
2088 if softspace(sys.stdout, 0):
2099 print
2089 print
2100 # Flush out code object which has been run (and source)
2090 # Flush out code object which has been run (and source)
2101 self.code_to_run = None
2091 self.code_to_run = None
2102 return outflag
2092 return outflag
2103
2093
2104 def push(self, line):
2094 def push(self, line):
2105 """Push a line to the interpreter.
2095 """Push a line to the interpreter.
2106
2096
2107 The line should not have a trailing newline; it may have
2097 The line should not have a trailing newline; it may have
2108 internal newlines. The line is appended to a buffer and the
2098 internal newlines. The line is appended to a buffer and the
2109 interpreter's runsource() method is called with the
2099 interpreter's runsource() method is called with the
2110 concatenated contents of the buffer as source. If this
2100 concatenated contents of the buffer as source. If this
2111 indicates that the command was executed or invalid, the buffer
2101 indicates that the command was executed or invalid, the buffer
2112 is reset; otherwise, the command is incomplete, and the buffer
2102 is reset; otherwise, the command is incomplete, and the buffer
2113 is left as it was after the line was appended. The return
2103 is left as it was after the line was appended. The return
2114 value is 1 if more input is required, 0 if the line was dealt
2104 value is 1 if more input is required, 0 if the line was dealt
2115 with in some way (this is the same as runsource()).
2105 with in some way (this is the same as runsource()).
2116 """
2106 """
2117
2107
2118 # autoindent management should be done here, and not in the
2108 # autoindent management should be done here, and not in the
2119 # interactive loop, since that one is only seen by keyboard input. We
2109 # interactive loop, since that one is only seen by keyboard input. We
2120 # need this done correctly even for code run via runlines (which uses
2110 # need this done correctly even for code run via runlines (which uses
2121 # push).
2111 # push).
2122
2112
2123 #print 'push line: <%s>' % line # dbg
2113 #print 'push line: <%s>' % line # dbg
2124 for subline in line.splitlines():
2114 for subline in line.splitlines():
2125 self.autoindent_update(subline)
2115 self.autoindent_update(subline)
2126 self.buffer.append(line)
2116 self.buffer.append(line)
2127 more = self.runsource('\n'.join(self.buffer), self.filename)
2117 more = self.runsource('\n'.join(self.buffer), self.filename)
2128 if not more:
2118 if not more:
2129 self.resetbuffer()
2119 self.resetbuffer()
2130 return more
2120 return more
2131
2121
2132 def split_user_input(self, line):
2122 def split_user_input(self, line):
2133 # This is really a hold-over to support ipapi and some extensions
2123 # This is really a hold-over to support ipapi and some extensions
2134 return prefilter.splitUserInput(line)
2124 return prefilter.splitUserInput(line)
2135
2125
2136 def resetbuffer(self):
2126 def resetbuffer(self):
2137 """Reset the input buffer."""
2127 """Reset the input buffer."""
2138 self.buffer[:] = []
2128 self.buffer[:] = []
2139
2129
2140 def raw_input(self,prompt='',continue_prompt=False):
2130 def raw_input(self,prompt='',continue_prompt=False):
2141 """Write a prompt and read a line.
2131 """Write a prompt and read a line.
2142
2132
2143 The returned line does not include the trailing newline.
2133 The returned line does not include the trailing newline.
2144 When the user enters the EOF key sequence, EOFError is raised.
2134 When the user enters the EOF key sequence, EOFError is raised.
2145
2135
2146 Optional inputs:
2136 Optional inputs:
2147
2137
2148 - prompt(''): a string to be printed to prompt the user.
2138 - prompt(''): a string to be printed to prompt the user.
2149
2139
2150 - continue_prompt(False): whether this line is the first one or a
2140 - continue_prompt(False): whether this line is the first one or a
2151 continuation in a sequence of inputs.
2141 continuation in a sequence of inputs.
2152 """
2142 """
2153
2143
2154 # Code run by the user may have modified the readline completer state.
2144 # Code run by the user may have modified the readline completer state.
2155 # We must ensure that our completer is back in place.
2145 # We must ensure that our completer is back in place.
2156 if self.has_readline:
2146 if self.has_readline:
2157 self.set_completer()
2147 self.set_completer()
2158
2148
2159 try:
2149 try:
2160 line = raw_input_original(prompt).decode(self.stdin_encoding)
2150 line = raw_input_original(prompt).decode(self.stdin_encoding)
2161 except ValueError:
2151 except ValueError:
2162 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2152 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2163 " or sys.stdout.close()!\nExiting IPython!")
2153 " or sys.stdout.close()!\nExiting IPython!")
2164 self.exit_now = True
2154 self.exit_now = True
2165 return ""
2155 return ""
2166
2156
2167 # Try to be reasonably smart about not re-indenting pasted input more
2157 # Try to be reasonably smart about not re-indenting pasted input more
2168 # than necessary. We do this by trimming out the auto-indent initial
2158 # than necessary. We do this by trimming out the auto-indent initial
2169 # spaces, if the user's actual input started itself with whitespace.
2159 # spaces, if the user's actual input started itself with whitespace.
2170 #debugx('self.buffer[-1]')
2160 #debugx('self.buffer[-1]')
2171
2161
2172 if self.autoindent:
2162 if self.autoindent:
2173 if num_ini_spaces(line) > self.indent_current_nsp:
2163 if num_ini_spaces(line) > self.indent_current_nsp:
2174 line = line[self.indent_current_nsp:]
2164 line = line[self.indent_current_nsp:]
2175 self.indent_current_nsp = 0
2165 self.indent_current_nsp = 0
2176
2166
2177 # store the unfiltered input before the user has any chance to modify
2167 # store the unfiltered input before the user has any chance to modify
2178 # it.
2168 # it.
2179 if line.strip():
2169 if line.strip():
2180 if continue_prompt:
2170 if continue_prompt:
2181 self.input_hist_raw[-1] += '%s\n' % line
2171 self.input_hist_raw[-1] += '%s\n' % line
2182 if self.has_readline: # and some config option is set?
2172 if self.has_readline: # and some config option is set?
2183 try:
2173 try:
2184 histlen = self.readline.get_current_history_length()
2174 histlen = self.readline.get_current_history_length()
2185 if histlen > 1:
2175 if histlen > 1:
2186 newhist = self.input_hist_raw[-1].rstrip()
2176 newhist = self.input_hist_raw[-1].rstrip()
2187 self.readline.remove_history_item(histlen-1)
2177 self.readline.remove_history_item(histlen-1)
2188 self.readline.replace_history_item(histlen-2,
2178 self.readline.replace_history_item(histlen-2,
2189 newhist.encode(self.stdin_encoding))
2179 newhist.encode(self.stdin_encoding))
2190 except AttributeError:
2180 except AttributeError:
2191 pass # re{move,place}_history_item are new in 2.4.
2181 pass # re{move,place}_history_item are new in 2.4.
2192 else:
2182 else:
2193 self.input_hist_raw.append('%s\n' % line)
2183 self.input_hist_raw.append('%s\n' % line)
2194 # only entries starting at first column go to shadow history
2184 # only entries starting at first column go to shadow history
2195 if line.lstrip() == line:
2185 if line.lstrip() == line:
2196 self.shadowhist.add(line.strip())
2186 self.shadowhist.add(line.strip())
2197 elif not continue_prompt:
2187 elif not continue_prompt:
2198 self.input_hist_raw.append('\n')
2188 self.input_hist_raw.append('\n')
2199 try:
2189 try:
2200 lineout = self.prefilter(line,continue_prompt)
2190 lineout = self.prefilter(line,continue_prompt)
2201 except:
2191 except:
2202 # blanket except, in case a user-defined prefilter crashes, so it
2192 # blanket except, in case a user-defined prefilter crashes, so it
2203 # can't take all of ipython with it.
2193 # can't take all of ipython with it.
2204 self.showtraceback()
2194 self.showtraceback()
2205 return ''
2195 return ''
2206 else:
2196 else:
2207 return lineout
2197 return lineout
2208
2198
2209 def _prefilter(self, line, continue_prompt):
2199 def _prefilter(self, line, continue_prompt):
2210 """Calls different preprocessors, depending on the form of line."""
2200 """Calls different preprocessors, depending on the form of line."""
2211
2201
2212 # All handlers *must* return a value, even if it's blank ('').
2202 # All handlers *must* return a value, even if it's blank ('').
2213
2203
2214 # Lines are NOT logged here. Handlers should process the line as
2204 # Lines are NOT logged here. Handlers should process the line as
2215 # needed, update the cache AND log it (so that the input cache array
2205 # needed, update the cache AND log it (so that the input cache array
2216 # stays synced).
2206 # stays synced).
2217
2207
2218 #.....................................................................
2208 #.....................................................................
2219 # Code begins
2209 # Code begins
2220
2210
2221 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2211 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2222
2212
2223 # save the line away in case we crash, so the post-mortem handler can
2213 # save the line away in case we crash, so the post-mortem handler can
2224 # record it
2214 # record it
2225 self._last_input_line = line
2215 self._last_input_line = line
2226
2216
2227 #print '***line: <%s>' % line # dbg
2217 #print '***line: <%s>' % line # dbg
2228
2218
2229 if not line:
2219 if not line:
2230 # Return immediately on purely empty lines, so that if the user
2220 # Return immediately on purely empty lines, so that if the user
2231 # previously typed some whitespace that started a continuation
2221 # previously typed some whitespace that started a continuation
2232 # prompt, he can break out of that loop with just an empty line.
2222 # prompt, he can break out of that loop with just an empty line.
2233 # This is how the default python prompt works.
2223 # This is how the default python prompt works.
2234
2224
2235 # Only return if the accumulated input buffer was just whitespace!
2225 # Only return if the accumulated input buffer was just whitespace!
2236 if ''.join(self.buffer).isspace():
2226 if ''.join(self.buffer).isspace():
2237 self.buffer[:] = []
2227 self.buffer[:] = []
2238 return ''
2228 return ''
2239
2229
2240 line_info = prefilter.LineInfo(line, continue_prompt)
2230 line_info = prefilter.LineInfo(line, continue_prompt)
2241
2231
2242 # the input history needs to track even empty lines
2232 # the input history needs to track even empty lines
2243 stripped = line.strip()
2233 stripped = line.strip()
2244
2234
2245 if not stripped:
2235 if not stripped:
2246 if not continue_prompt:
2236 if not continue_prompt:
2247 self.outputcache.prompt_count -= 1
2237 self.outputcache.prompt_count -= 1
2248 return self.handle_normal(line_info)
2238 return self.handle_normal(line_info)
2249
2239
2250 # print '***cont',continue_prompt # dbg
2240 # print '***cont',continue_prompt # dbg
2251 # special handlers are only allowed for single line statements
2241 # special handlers are only allowed for single line statements
2252 if continue_prompt and not self.rc.multi_line_specials:
2242 if continue_prompt and not self.rc.multi_line_specials:
2253 return self.handle_normal(line_info)
2243 return self.handle_normal(line_info)
2254
2244
2255
2245
2256 # See whether any pre-existing handler can take care of it
2246 # See whether any pre-existing handler can take care of it
2257 rewritten = self.hooks.input_prefilter(stripped)
2247 rewritten = self.hooks.input_prefilter(stripped)
2258 if rewritten != stripped: # ok, some prefilter did something
2248 if rewritten != stripped: # ok, some prefilter did something
2259 rewritten = line_info.pre + rewritten # add indentation
2249 rewritten = line_info.pre + rewritten # add indentation
2260 return self.handle_normal(prefilter.LineInfo(rewritten,
2250 return self.handle_normal(prefilter.LineInfo(rewritten,
2261 continue_prompt))
2251 continue_prompt))
2262
2252
2263 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2253 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2264
2254
2265 return prefilter.prefilter(line_info, self)
2255 return prefilter.prefilter(line_info, self)
2266
2256
2267
2257
2268 def _prefilter_dumb(self, line, continue_prompt):
2258 def _prefilter_dumb(self, line, continue_prompt):
2269 """simple prefilter function, for debugging"""
2259 """simple prefilter function, for debugging"""
2270 return self.handle_normal(line,continue_prompt)
2260 return self.handle_normal(line,continue_prompt)
2271
2261
2272
2262
2273 def multiline_prefilter(self, line, continue_prompt):
2263 def multiline_prefilter(self, line, continue_prompt):
2274 """ Run _prefilter for each line of input
2264 """ Run _prefilter for each line of input
2275
2265
2276 Covers cases where there are multiple lines in the user entry,
2266 Covers cases where there are multiple lines in the user entry,
2277 which is the case when the user goes back to a multiline history
2267 which is the case when the user goes back to a multiline history
2278 entry and presses enter.
2268 entry and presses enter.
2279
2269
2280 """
2270 """
2281 out = []
2271 out = []
2282 for l in line.rstrip('\n').split('\n'):
2272 for l in line.rstrip('\n').split('\n'):
2283 out.append(self._prefilter(l, continue_prompt))
2273 out.append(self._prefilter(l, continue_prompt))
2284 return '\n'.join(out)
2274 return '\n'.join(out)
2285
2275
2286 # Set the default prefilter() function (this can be user-overridden)
2276 # Set the default prefilter() function (this can be user-overridden)
2287 prefilter = multiline_prefilter
2277 prefilter = multiline_prefilter
2288
2278
2289 def handle_normal(self,line_info):
2279 def handle_normal(self,line_info):
2290 """Handle normal input lines. Use as a template for handlers."""
2280 """Handle normal input lines. Use as a template for handlers."""
2291
2281
2292 # With autoindent on, we need some way to exit the input loop, and I
2282 # With autoindent on, we need some way to exit the input loop, and I
2293 # don't want to force the user to have to backspace all the way to
2283 # don't want to force the user to have to backspace all the way to
2294 # clear the line. The rule will be in this case, that either two
2284 # clear the line. The rule will be in this case, that either two
2295 # lines of pure whitespace in a row, or a line of pure whitespace but
2285 # lines of pure whitespace in a row, or a line of pure whitespace but
2296 # of a size different to the indent level, will exit the input loop.
2286 # of a size different to the indent level, will exit the input loop.
2297 line = line_info.line
2287 line = line_info.line
2298 continue_prompt = line_info.continue_prompt
2288 continue_prompt = line_info.continue_prompt
2299
2289
2300 if (continue_prompt and self.autoindent and line.isspace() and
2290 if (continue_prompt and self.autoindent and line.isspace() and
2301 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2291 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2302 (self.buffer[-1]).isspace() )):
2292 (self.buffer[-1]).isspace() )):
2303 line = ''
2293 line = ''
2304
2294
2305 self.log(line,line,continue_prompt)
2295 self.log(line,line,continue_prompt)
2306 return line
2296 return line
2307
2297
2308 def handle_alias(self,line_info):
2298 def handle_alias(self,line_info):
2309 """Handle alias input lines. """
2299 """Handle alias input lines. """
2310 tgt = self.alias_table[line_info.iFun]
2300 tgt = self.alias_table[line_info.iFun]
2311 # print "=>",tgt #dbg
2301 # print "=>",tgt #dbg
2312 if callable(tgt):
2302 if callable(tgt):
2313 if '$' in line_info.line:
2303 if '$' in line_info.line:
2314 call_meth = '(_ip, _ip.itpl(%s))'
2304 call_meth = '(_ip, _ip.itpl(%s))'
2315 else:
2305 else:
2316 call_meth = '(_ip,%s)'
2306 call_meth = '(_ip,%s)'
2317 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2307 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2318 line_info.iFun,
2308 line_info.iFun,
2319 make_quoted_expr(line_info.line))
2309 make_quoted_expr(line_info.line))
2320 else:
2310 else:
2321 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2311 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2322
2312
2323 # pre is needed, because it carries the leading whitespace. Otherwise
2313 # pre is needed, because it carries the leading whitespace. Otherwise
2324 # aliases won't work in indented sections.
2314 # aliases won't work in indented sections.
2325 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2315 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2326 make_quoted_expr( transformed ))
2316 make_quoted_expr( transformed ))
2327
2317
2328 self.log(line_info.line,line_out,line_info.continue_prompt)
2318 self.log(line_info.line,line_out,line_info.continue_prompt)
2329 #print 'line out:',line_out # dbg
2319 #print 'line out:',line_out # dbg
2330 return line_out
2320 return line_out
2331
2321
2332 def handle_shell_escape(self, line_info):
2322 def handle_shell_escape(self, line_info):
2333 """Execute the line in a shell, empty return value"""
2323 """Execute the line in a shell, empty return value"""
2334 #print 'line in :', `line` # dbg
2324 #print 'line in :', `line` # dbg
2335 line = line_info.line
2325 line = line_info.line
2336 if line.lstrip().startswith('!!'):
2326 if line.lstrip().startswith('!!'):
2337 # rewrite LineInfo's line, iFun and theRest to properly hold the
2327 # rewrite LineInfo's line, iFun and theRest to properly hold the
2338 # call to %sx and the actual command to be executed, so
2328 # call to %sx and the actual command to be executed, so
2339 # handle_magic can work correctly. Note that this works even if
2329 # handle_magic can work correctly. Note that this works even if
2340 # the line is indented, so it handles multi_line_specials
2330 # the line is indented, so it handles multi_line_specials
2341 # properly.
2331 # properly.
2342 new_rest = line.lstrip()[2:]
2332 new_rest = line.lstrip()[2:]
2343 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2333 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2344 line_info.iFun = 'sx'
2334 line_info.iFun = 'sx'
2345 line_info.theRest = new_rest
2335 line_info.theRest = new_rest
2346 return self.handle_magic(line_info)
2336 return self.handle_magic(line_info)
2347 else:
2337 else:
2348 cmd = line.lstrip().lstrip('!')
2338 cmd = line.lstrip().lstrip('!')
2349 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2339 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2350 make_quoted_expr(cmd))
2340 make_quoted_expr(cmd))
2351 # update cache/log and return
2341 # update cache/log and return
2352 self.log(line,line_out,line_info.continue_prompt)
2342 self.log(line,line_out,line_info.continue_prompt)
2353 return line_out
2343 return line_out
2354
2344
2355 def handle_magic(self, line_info):
2345 def handle_magic(self, line_info):
2356 """Execute magic functions."""
2346 """Execute magic functions."""
2357 iFun = line_info.iFun
2347 iFun = line_info.iFun
2358 theRest = line_info.theRest
2348 theRest = line_info.theRest
2359 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2349 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2360 make_quoted_expr(iFun + " " + theRest))
2350 make_quoted_expr(iFun + " " + theRest))
2361 self.log(line_info.line,cmd,line_info.continue_prompt)
2351 self.log(line_info.line,cmd,line_info.continue_prompt)
2362 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2352 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2363 return cmd
2353 return cmd
2364
2354
2365 def handle_auto(self, line_info):
2355 def handle_auto(self, line_info):
2366 """Hande lines which can be auto-executed, quoting if requested."""
2356 """Hande lines which can be auto-executed, quoting if requested."""
2367
2357
2368 line = line_info.line
2358 line = line_info.line
2369 iFun = line_info.iFun
2359 iFun = line_info.iFun
2370 theRest = line_info.theRest
2360 theRest = line_info.theRest
2371 pre = line_info.pre
2361 pre = line_info.pre
2372 continue_prompt = line_info.continue_prompt
2362 continue_prompt = line_info.continue_prompt
2373 obj = line_info.ofind(self)['obj']
2363 obj = line_info.ofind(self)['obj']
2374
2364
2375 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2365 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2376
2366
2377 # This should only be active for single-line input!
2367 # This should only be active for single-line input!
2378 if continue_prompt:
2368 if continue_prompt:
2379 self.log(line,line,continue_prompt)
2369 self.log(line,line,continue_prompt)
2380 return line
2370 return line
2381
2371
2382 force_auto = isinstance(obj, IPython.ipapi.IPyAutocall)
2372 force_auto = isinstance(obj, IPython.ipapi.IPyAutocall)
2383 auto_rewrite = True
2373 auto_rewrite = True
2384
2374
2385 if pre == self.ESC_QUOTE:
2375 if pre == self.ESC_QUOTE:
2386 # Auto-quote splitting on whitespace
2376 # Auto-quote splitting on whitespace
2387 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2377 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2388 elif pre == self.ESC_QUOTE2:
2378 elif pre == self.ESC_QUOTE2:
2389 # Auto-quote whole string
2379 # Auto-quote whole string
2390 newcmd = '%s("%s")' % (iFun,theRest)
2380 newcmd = '%s("%s")' % (iFun,theRest)
2391 elif pre == self.ESC_PAREN:
2381 elif pre == self.ESC_PAREN:
2392 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2382 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2393 else:
2383 else:
2394 # Auto-paren.
2384 # Auto-paren.
2395 # We only apply it to argument-less calls if the autocall
2385 # We only apply it to argument-less calls if the autocall
2396 # parameter is set to 2. We only need to check that autocall is <
2386 # parameter is set to 2. We only need to check that autocall is <
2397 # 2, since this function isn't called unless it's at least 1.
2387 # 2, since this function isn't called unless it's at least 1.
2398 if not theRest and (self.rc.autocall < 2) and not force_auto:
2388 if not theRest and (self.rc.autocall < 2) and not force_auto:
2399 newcmd = '%s %s' % (iFun,theRest)
2389 newcmd = '%s %s' % (iFun,theRest)
2400 auto_rewrite = False
2390 auto_rewrite = False
2401 else:
2391 else:
2402 if not force_auto and theRest.startswith('['):
2392 if not force_auto and theRest.startswith('['):
2403 if hasattr(obj,'__getitem__'):
2393 if hasattr(obj,'__getitem__'):
2404 # Don't autocall in this case: item access for an object
2394 # Don't autocall in this case: item access for an object
2405 # which is BOTH callable and implements __getitem__.
2395 # which is BOTH callable and implements __getitem__.
2406 newcmd = '%s %s' % (iFun,theRest)
2396 newcmd = '%s %s' % (iFun,theRest)
2407 auto_rewrite = False
2397 auto_rewrite = False
2408 else:
2398 else:
2409 # if the object doesn't support [] access, go ahead and
2399 # if the object doesn't support [] access, go ahead and
2410 # autocall
2400 # autocall
2411 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2401 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2412 elif theRest.endswith(';'):
2402 elif theRest.endswith(';'):
2413 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2403 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2414 else:
2404 else:
2415 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2405 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2416
2406
2417 if auto_rewrite:
2407 if auto_rewrite:
2418 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2408 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2419
2409
2420 try:
2410 try:
2421 # plain ascii works better w/ pyreadline, on some machines, so
2411 # plain ascii works better w/ pyreadline, on some machines, so
2422 # we use it and only print uncolored rewrite if we have unicode
2412 # we use it and only print uncolored rewrite if we have unicode
2423 rw = str(rw)
2413 rw = str(rw)
2424 print >>Term.cout, rw
2414 print >>Term.cout, rw
2425 except UnicodeEncodeError:
2415 except UnicodeEncodeError:
2426 print "-------------->" + newcmd
2416 print "-------------->" + newcmd
2427
2417
2428 # log what is now valid Python, not the actual user input (without the
2418 # log what is now valid Python, not the actual user input (without the
2429 # final newline)
2419 # final newline)
2430 self.log(line,newcmd,continue_prompt)
2420 self.log(line,newcmd,continue_prompt)
2431 return newcmd
2421 return newcmd
2432
2422
2433 def handle_help(self, line_info):
2423 def handle_help(self, line_info):
2434 """Try to get some help for the object.
2424 """Try to get some help for the object.
2435
2425
2436 obj? or ?obj -> basic information.
2426 obj? or ?obj -> basic information.
2437 obj?? or ??obj -> more details.
2427 obj?? or ??obj -> more details.
2438 """
2428 """
2439
2429
2440 line = line_info.line
2430 line = line_info.line
2441 # We need to make sure that we don't process lines which would be
2431 # We need to make sure that we don't process lines which would be
2442 # otherwise valid python, such as "x=1 # what?"
2432 # otherwise valid python, such as "x=1 # what?"
2443 try:
2433 try:
2444 codeop.compile_command(line)
2434 codeop.compile_command(line)
2445 except SyntaxError:
2435 except SyntaxError:
2446 # We should only handle as help stuff which is NOT valid syntax
2436 # We should only handle as help stuff which is NOT valid syntax
2447 if line[0]==self.ESC_HELP:
2437 if line[0]==self.ESC_HELP:
2448 line = line[1:]
2438 line = line[1:]
2449 elif line[-1]==self.ESC_HELP:
2439 elif line[-1]==self.ESC_HELP:
2450 line = line[:-1]
2440 line = line[:-1]
2451 self.log(line,'#?'+line,line_info.continue_prompt)
2441 self.log(line,'#?'+line,line_info.continue_prompt)
2452 if line:
2442 if line:
2453 #print 'line:<%r>' % line # dbg
2443 #print 'line:<%r>' % line # dbg
2454 self.magic_pinfo(line)
2444 self.magic_pinfo(line)
2455 else:
2445 else:
2456 page(self.usage,screen_lines=self.rc.screen_length)
2446 page(self.usage,screen_lines=self.rc.screen_length)
2457 return '' # Empty string is needed here!
2447 return '' # Empty string is needed here!
2458 except:
2448 except:
2459 # Pass any other exceptions through to the normal handler
2449 # Pass any other exceptions through to the normal handler
2460 return self.handle_normal(line_info)
2450 return self.handle_normal(line_info)
2461 else:
2451 else:
2462 # If the code compiles ok, we should handle it normally
2452 # If the code compiles ok, we should handle it normally
2463 return self.handle_normal(line_info)
2453 return self.handle_normal(line_info)
2464
2454
2465 def getapi(self):
2455 def getapi(self):
2466 """ Get an IPApi object for this shell instance
2456 """ Get an IPApi object for this shell instance
2467
2457
2468 Getting an IPApi object is always preferable to accessing the shell
2458 Getting an IPApi object is always preferable to accessing the shell
2469 directly, but this holds true especially for extensions.
2459 directly, but this holds true especially for extensions.
2470
2460
2471 It should always be possible to implement an extension with IPApi
2461 It should always be possible to implement an extension with IPApi
2472 alone. If not, contact maintainer to request an addition.
2462 alone. If not, contact maintainer to request an addition.
2473
2463
2474 """
2464 """
2475 return self.api
2465 return self.api
2476
2466
2477 def handle_emacs(self, line_info):
2467 def handle_emacs(self, line_info):
2478 """Handle input lines marked by python-mode."""
2468 """Handle input lines marked by python-mode."""
2479
2469
2480 # Currently, nothing is done. Later more functionality can be added
2470 # Currently, nothing is done. Later more functionality can be added
2481 # here if needed.
2471 # here if needed.
2482
2472
2483 # The input cache shouldn't be updated
2473 # The input cache shouldn't be updated
2484 return line_info.line
2474 return line_info.line
2485
2475
2486
2476
2487 def mktempfile(self,data=None):
2477 def mktempfile(self,data=None):
2488 """Make a new tempfile and return its filename.
2478 """Make a new tempfile and return its filename.
2489
2479
2490 This makes a call to tempfile.mktemp, but it registers the created
2480 This makes a call to tempfile.mktemp, but it registers the created
2491 filename internally so ipython cleans it up at exit time.
2481 filename internally so ipython cleans it up at exit time.
2492
2482
2493 Optional inputs:
2483 Optional inputs:
2494
2484
2495 - data(None): if data is given, it gets written out to the temp file
2485 - data(None): if data is given, it gets written out to the temp file
2496 immediately, and the file is closed again."""
2486 immediately, and the file is closed again."""
2497
2487
2498 filename = tempfile.mktemp('.py','ipython_edit_')
2488 filename = tempfile.mktemp('.py','ipython_edit_')
2499 self.tempfiles.append(filename)
2489 self.tempfiles.append(filename)
2500
2490
2501 if data:
2491 if data:
2502 tmp_file = open(filename,'w')
2492 tmp_file = open(filename,'w')
2503 tmp_file.write(data)
2493 tmp_file.write(data)
2504 tmp_file.close()
2494 tmp_file.close()
2505 return filename
2495 return filename
2506
2496
2507 def write(self,data):
2497 def write(self,data):
2508 """Write a string to the default output"""
2498 """Write a string to the default output"""
2509 Term.cout.write(data)
2499 Term.cout.write(data)
2510
2500
2511 def write_err(self,data):
2501 def write_err(self,data):
2512 """Write a string to the default error output"""
2502 """Write a string to the default error output"""
2513 Term.cerr.write(data)
2503 Term.cerr.write(data)
2514
2504
2515 def exit(self):
2505 def exit(self):
2516 """Handle interactive exit.
2506 """Handle interactive exit.
2517
2507
2518 This method sets the exit_now attribute."""
2508 This method sets the exit_now attribute."""
2519
2509
2520 if self.rc.confirm_exit:
2510 if self.rc.confirm_exit:
2521 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2511 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2522 self.exit_now = True
2512 self.exit_now = True
2523 else:
2513 else:
2524 self.exit_now = True
2514 self.exit_now = True
2525
2515
2526 def safe_execfile(self,fname,*where,**kw):
2516 def safe_execfile(self,fname,*where,**kw):
2527 """A safe version of the builtin execfile().
2517 """A safe version of the builtin execfile().
2528
2518
2529 This version will never throw an exception, and knows how to handle
2519 This version will never throw an exception, and knows how to handle
2530 ipython logs as well.
2520 ipython logs as well.
2531
2521
2532 :Parameters:
2522 :Parameters:
2533 fname : string
2523 fname : string
2534 Name of the file to be executed.
2524 Name of the file to be executed.
2535
2525
2536 where : tuple
2526 where : tuple
2537 One or two namespaces, passed to execfile() as (globals,locals).
2527 One or two namespaces, passed to execfile() as (globals,locals).
2538 If only one is given, it is passed as both.
2528 If only one is given, it is passed as both.
2539
2529
2540 :Keywords:
2530 :Keywords:
2541 islog : boolean (False)
2531 islog : boolean (False)
2542
2532
2543 quiet : boolean (True)
2533 quiet : boolean (True)
2544
2534
2545 exit_ignore : boolean (False)
2535 exit_ignore : boolean (False)
2546 """
2536 """
2547
2537
2548 def syspath_cleanup():
2538 def syspath_cleanup():
2549 """Internal cleanup routine for sys.path."""
2539 """Internal cleanup routine for sys.path."""
2550 if add_dname:
2540 if add_dname:
2551 try:
2541 try:
2552 sys.path.remove(dname)
2542 sys.path.remove(dname)
2553 except ValueError:
2543 except ValueError:
2554 # For some reason the user has already removed it, ignore.
2544 # For some reason the user has already removed it, ignore.
2555 pass
2545 pass
2556
2546
2557 fname = os.path.expanduser(fname)
2547 fname = os.path.expanduser(fname)
2558
2548
2559 # Find things also in current directory. This is needed to mimic the
2549 # Find things also in current directory. This is needed to mimic the
2560 # behavior of running a script from the system command line, where
2550 # behavior of running a script from the system command line, where
2561 # Python inserts the script's directory into sys.path
2551 # Python inserts the script's directory into sys.path
2562 dname = os.path.dirname(os.path.abspath(fname))
2552 dname = os.path.dirname(os.path.abspath(fname))
2563 add_dname = False
2553 add_dname = False
2564 if dname not in sys.path:
2554 if dname not in sys.path:
2565 sys.path.insert(0,dname)
2555 sys.path.insert(0,dname)
2566 add_dname = True
2556 add_dname = True
2567
2557
2568 try:
2558 try:
2569 xfile = open(fname)
2559 xfile = open(fname)
2570 except:
2560 except:
2571 print >> Term.cerr, \
2561 print >> Term.cerr, \
2572 'Could not open file <%s> for safe execution.' % fname
2562 'Could not open file <%s> for safe execution.' % fname
2573 syspath_cleanup()
2563 syspath_cleanup()
2574 return None
2564 return None
2575
2565
2576 kw.setdefault('islog',0)
2566 kw.setdefault('islog',0)
2577 kw.setdefault('quiet',1)
2567 kw.setdefault('quiet',1)
2578 kw.setdefault('exit_ignore',0)
2568 kw.setdefault('exit_ignore',0)
2579
2569
2580 first = xfile.readline()
2570 first = xfile.readline()
2581 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2571 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2582 xfile.close()
2572 xfile.close()
2583 # line by line execution
2573 # line by line execution
2584 if first.startswith(loghead) or kw['islog']:
2574 if first.startswith(loghead) or kw['islog']:
2585 print 'Loading log file <%s> one line at a time...' % fname
2575 print 'Loading log file <%s> one line at a time...' % fname
2586 if kw['quiet']:
2576 if kw['quiet']:
2587 stdout_save = sys.stdout
2577 stdout_save = sys.stdout
2588 sys.stdout = StringIO.StringIO()
2578 sys.stdout = StringIO.StringIO()
2589 try:
2579 try:
2590 globs,locs = where[0:2]
2580 globs,locs = where[0:2]
2591 except:
2581 except:
2592 try:
2582 try:
2593 globs = locs = where[0]
2583 globs = locs = where[0]
2594 except:
2584 except:
2595 globs = locs = globals()
2585 globs = locs = globals()
2596 badblocks = []
2586 badblocks = []
2597
2587
2598 # we also need to identify indented blocks of code when replaying
2588 # we also need to identify indented blocks of code when replaying
2599 # logs and put them together before passing them to an exec
2589 # logs and put them together before passing them to an exec
2600 # statement. This takes a bit of regexp and look-ahead work in the
2590 # statement. This takes a bit of regexp and look-ahead work in the
2601 # file. It's easiest if we swallow the whole thing in memory
2591 # file. It's easiest if we swallow the whole thing in memory
2602 # first, and manually walk through the lines list moving the
2592 # first, and manually walk through the lines list moving the
2603 # counter ourselves.
2593 # counter ourselves.
2604 indent_re = re.compile('\s+\S')
2594 indent_re = re.compile('\s+\S')
2605 xfile = open(fname)
2595 xfile = open(fname)
2606 filelines = xfile.readlines()
2596 filelines = xfile.readlines()
2607 xfile.close()
2597 xfile.close()
2608 nlines = len(filelines)
2598 nlines = len(filelines)
2609 lnum = 0
2599 lnum = 0
2610 while lnum < nlines:
2600 while lnum < nlines:
2611 line = filelines[lnum]
2601 line = filelines[lnum]
2612 lnum += 1
2602 lnum += 1
2613 # don't re-insert logger status info into cache
2603 # don't re-insert logger status info into cache
2614 if line.startswith('#log#'):
2604 if line.startswith('#log#'):
2615 continue
2605 continue
2616 else:
2606 else:
2617 # build a block of code (maybe a single line) for execution
2607 # build a block of code (maybe a single line) for execution
2618 block = line
2608 block = line
2619 try:
2609 try:
2620 next = filelines[lnum] # lnum has already incremented
2610 next = filelines[lnum] # lnum has already incremented
2621 except:
2611 except:
2622 next = None
2612 next = None
2623 while next and indent_re.match(next):
2613 while next and indent_re.match(next):
2624 block += next
2614 block += next
2625 lnum += 1
2615 lnum += 1
2626 try:
2616 try:
2627 next = filelines[lnum]
2617 next = filelines[lnum]
2628 except:
2618 except:
2629 next = None
2619 next = None
2630 # now execute the block of one or more lines
2620 # now execute the block of one or more lines
2631 try:
2621 try:
2632 exec block in globs,locs
2622 exec block in globs,locs
2633 except SystemExit:
2623 except SystemExit:
2634 pass
2624 pass
2635 except:
2625 except:
2636 badblocks.append(block.rstrip())
2626 badblocks.append(block.rstrip())
2637 if kw['quiet']: # restore stdout
2627 if kw['quiet']: # restore stdout
2638 sys.stdout.close()
2628 sys.stdout.close()
2639 sys.stdout = stdout_save
2629 sys.stdout = stdout_save
2640 print 'Finished replaying log file <%s>' % fname
2630 print 'Finished replaying log file <%s>' % fname
2641 if badblocks:
2631 if badblocks:
2642 print >> sys.stderr, ('\nThe following lines/blocks in file '
2632 print >> sys.stderr, ('\nThe following lines/blocks in file '
2643 '<%s> reported errors:' % fname)
2633 '<%s> reported errors:' % fname)
2644
2634
2645 for badline in badblocks:
2635 for badline in badblocks:
2646 print >> sys.stderr, badline
2636 print >> sys.stderr, badline
2647 else: # regular file execution
2637 else: # regular file execution
2648 try:
2638 try:
2649 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2639 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2650 # Work around a bug in Python for Windows. The bug was
2640 # Work around a bug in Python for Windows. The bug was
2651 # fixed in in Python 2.5 r54159 and 54158, but that's still
2641 # fixed in in Python 2.5 r54159 and 54158, but that's still
2652 # SVN Python as of March/07. For details, see:
2642 # SVN Python as of March/07. For details, see:
2653 # http://projects.scipy.org/ipython/ipython/ticket/123
2643 # http://projects.scipy.org/ipython/ipython/ticket/123
2654 try:
2644 try:
2655 globs,locs = where[0:2]
2645 globs,locs = where[0:2]
2656 except:
2646 except:
2657 try:
2647 try:
2658 globs = locs = where[0]
2648 globs = locs = where[0]
2659 except:
2649 except:
2660 globs = locs = globals()
2650 globs = locs = globals()
2661 exec file(fname) in globs,locs
2651 exec file(fname) in globs,locs
2662 else:
2652 else:
2663 execfile(fname,*where)
2653 execfile(fname,*where)
2664 except SyntaxError:
2654 except SyntaxError:
2665 self.showsyntaxerror()
2655 self.showsyntaxerror()
2666 warn('Failure executing file: <%s>' % fname)
2656 warn('Failure executing file: <%s>' % fname)
2667 except SystemExit,status:
2657 except SystemExit,status:
2668 # Code that correctly sets the exit status flag to success (0)
2658 # Code that correctly sets the exit status flag to success (0)
2669 # shouldn't be bothered with a traceback. Note that a plain
2659 # shouldn't be bothered with a traceback. Note that a plain
2670 # sys.exit() does NOT set the message to 0 (it's empty) so that
2660 # sys.exit() does NOT set the message to 0 (it's empty) so that
2671 # will still get a traceback. Note that the structure of the
2661 # will still get a traceback. Note that the structure of the
2672 # SystemExit exception changed between Python 2.4 and 2.5, so
2662 # SystemExit exception changed between Python 2.4 and 2.5, so
2673 # the checks must be done in a version-dependent way.
2663 # the checks must be done in a version-dependent way.
2674 show = False
2664 show = False
2675
2665
2676 if sys.version_info[:2] > (2,5):
2666 if sys.version_info[:2] > (2,5):
2677 if status.message!=0 and not kw['exit_ignore']:
2667 if status.message!=0 and not kw['exit_ignore']:
2678 show = True
2668 show = True
2679 else:
2669 else:
2680 if status.code and not kw['exit_ignore']:
2670 if status.code and not kw['exit_ignore']:
2681 show = True
2671 show = True
2682 if show:
2672 if show:
2683 self.showtraceback()
2673 self.showtraceback()
2684 warn('Failure executing file: <%s>' % fname)
2674 warn('Failure executing file: <%s>' % fname)
2685 except:
2675 except:
2686 self.showtraceback()
2676 self.showtraceback()
2687 warn('Failure executing file: <%s>' % fname)
2677 warn('Failure executing file: <%s>' % fname)
2688
2678
2689 syspath_cleanup()
2679 syspath_cleanup()
2690
2680
2691 #************************* end of file <iplib.py> *****************************
2681 #************************* end of file <iplib.py> *****************************
General Comments 0
You need to be logged in to leave comments. Login now