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