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