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