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