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