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