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