##// END OF EJS Templates
clean leftover debug info
fperez -
Show More
@@ -1,2060 +1,2060 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 IPython -- An enhanced Interactive Python
3 IPython -- An enhanced Interactive Python
4
4
5 Requires Python 2.1 or newer.
5 Requires Python 2.1 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 982 2005-12-30 23:57:07Z fperez $
9 $Id: iplib.py 983 2005-12-31 00:04:25Z fperez $
10 """
10 """
11
11
12 #*****************************************************************************
12 #*****************************************************************************
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu>
14 # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu>
15 #
15 #
16 # Distributed under the terms of the BSD License. The full license is in
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
17 # the file COPYING, distributed as part of this software.
18 #
18 #
19 # Note: this code originally subclassed code.InteractiveConsole from the
19 # Note: this code originally subclassed code.InteractiveConsole from the
20 # Python standard library. Over time, all of that class has been copied
20 # Python standard library. Over time, all of that class has been copied
21 # verbatim here for modifications which could not be accomplished by
21 # verbatim here for modifications which could not be accomplished by
22 # subclassing. At this point, there are no dependencies at all on the code
22 # 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)
23 # 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
24 # allows for this, but it's always nice to acknowledge credit where credit is
25 # due.
25 # due.
26 #*****************************************************************************
26 #*****************************************************************************
27
27
28 #****************************************************************************
28 #****************************************************************************
29 # Modules and globals
29 # Modules and globals
30
30
31 from __future__ import generators # for 2.2 backwards-compatibility
31 from __future__ import generators # for 2.2 backwards-compatibility
32
32
33 from IPython import Release
33 from IPython import Release
34 __author__ = '%s <%s>\n%s <%s>' % \
34 __author__ = '%s <%s>\n%s <%s>' % \
35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
36 __license__ = Release.license
36 __license__ = Release.license
37 __version__ = Release.version
37 __version__ = Release.version
38
38
39 # Python standard modules
39 # Python standard modules
40 import __main__
40 import __main__
41 import __builtin__
41 import __builtin__
42 import StringIO
42 import StringIO
43 import bdb
43 import bdb
44 import cPickle as pickle
44 import cPickle as pickle
45 import codeop
45 import codeop
46 import exceptions
46 import exceptions
47 import glob
47 import glob
48 import inspect
48 import inspect
49 import keyword
49 import keyword
50 import new
50 import new
51 import os
51 import os
52 import pdb
52 import pdb
53 import pydoc
53 import pydoc
54 import re
54 import re
55 import shutil
55 import shutil
56 import string
56 import string
57 import sys
57 import sys
58 import traceback
58 import traceback
59 import types
59 import types
60
60
61 from pprint import pprint, pformat
61 from pprint import pprint, pformat
62
62
63 # IPython's own modules
63 # IPython's own modules
64 import IPython
64 import IPython
65 from IPython import OInspect,PyColorize,ultraTB
65 from IPython import OInspect,PyColorize,ultraTB
66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
67 from IPython.FakeModule import FakeModule
67 from IPython.FakeModule import FakeModule
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
69 from IPython.Logger import Logger
69 from IPython.Logger import Logger
70 from IPython.Magic import Magic
70 from IPython.Magic import Magic
71 from IPython.Prompts import CachedOutput
71 from IPython.Prompts import CachedOutput
72 from IPython.Struct import Struct
72 from IPython.Struct import Struct
73 from IPython.background_jobs import BackgroundJobManager
73 from IPython.background_jobs import BackgroundJobManager
74 from IPython.usage import cmd_line_usage,interactive_usage
74 from IPython.usage import cmd_line_usage,interactive_usage
75 from IPython.genutils import *
75 from IPython.genutils import *
76
76
77 # store the builtin raw_input globally, and use this always, in case user code
77 # store the builtin raw_input globally, and use this always, in case user code
78 # overwrites it (like wx.py.PyShell does)
78 # overwrites it (like wx.py.PyShell does)
79 raw_input_original = raw_input
79 raw_input_original = raw_input
80
80
81 # compiled regexps for autoindent management
81 # compiled regexps for autoindent management
82 ini_spaces_re = re.compile(r'^(\s+)')
82 ini_spaces_re = re.compile(r'^(\s+)')
83 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
83 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
84
84
85 #****************************************************************************
85 #****************************************************************************
86 # Some utility function definitions
86 # Some utility function definitions
87
87
88 def softspace(file, newvalue):
88 def softspace(file, newvalue):
89 """Copied from code.py, to remove the dependency"""
89 """Copied from code.py, to remove the dependency"""
90 oldvalue = 0
90 oldvalue = 0
91 try:
91 try:
92 oldvalue = file.softspace
92 oldvalue = file.softspace
93 except AttributeError:
93 except AttributeError:
94 pass
94 pass
95 try:
95 try:
96 file.softspace = newvalue
96 file.softspace = newvalue
97 except (AttributeError, TypeError):
97 except (AttributeError, TypeError):
98 # "attribute-less object" or "read-only attributes"
98 # "attribute-less object" or "read-only attributes"
99 pass
99 pass
100 return oldvalue
100 return oldvalue
101
101
102 #****************************************************************************
102 #****************************************************************************
103 # These special functions get installed in the builtin namespace, to provide
103 # These special functions get installed in the builtin namespace, to provide
104 # programmatic (pure python) access to magics, aliases and system calls. This
104 # programmatic (pure python) access to magics, aliases and system calls. This
105 # is important for logging, user scripting, and more.
105 # is important for logging, user scripting, and more.
106
106
107 # We are basically exposing, via normal python functions, the three mechanisms
107 # We are basically exposing, via normal python functions, the three mechanisms
108 # in which ipython offers special call modes (magics for internal control,
108 # in which ipython offers special call modes (magics for internal control,
109 # aliases for direct system access via pre-selected names, and !cmd for
109 # aliases for direct system access via pre-selected names, and !cmd for
110 # calling arbitrary system commands).
110 # calling arbitrary system commands).
111
111
112 def ipmagic(arg_s):
112 def ipmagic(arg_s):
113 """Call a magic function by name.
113 """Call a magic function by name.
114
114
115 Input: a string containing the name of the magic function to call and any
115 Input: a string containing the name of the magic function to call and any
116 additional arguments to be passed to the magic.
116 additional arguments to be passed to the magic.
117
117
118 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
118 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
119 prompt:
119 prompt:
120
120
121 In[1]: %name -opt foo bar
121 In[1]: %name -opt foo bar
122
122
123 To call a magic without arguments, simply use ipmagic('name').
123 To call a magic without arguments, simply use ipmagic('name').
124
124
125 This provides a proper Python function to call IPython's magics in any
125 This provides a proper Python function to call IPython's magics in any
126 valid Python code you can type at the interpreter, including loops and
126 valid Python code you can type at the interpreter, including loops and
127 compound statements. It is added by IPython to the Python builtin
127 compound statements. It is added by IPython to the Python builtin
128 namespace upon initialization."""
128 namespace upon initialization."""
129
129
130 args = arg_s.split(' ',1)
130 args = arg_s.split(' ',1)
131 magic_name = args[0]
131 magic_name = args[0]
132 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
132 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
133 magic_name = magic_name[1:]
133 magic_name = magic_name[1:]
134 try:
134 try:
135 magic_args = args[1]
135 magic_args = args[1]
136 except IndexError:
136 except IndexError:
137 magic_args = ''
137 magic_args = ''
138 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
138 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
139 if fn is None:
139 if fn is None:
140 error("Magic function `%s` not found." % magic_name)
140 error("Magic function `%s` not found." % magic_name)
141 else:
141 else:
142 magic_args = __IPYTHON__.var_expand(magic_args)
142 magic_args = __IPYTHON__.var_expand(magic_args)
143 return fn(magic_args)
143 return fn(magic_args)
144
144
145 def ipalias(arg_s):
145 def ipalias(arg_s):
146 """Call an alias by name.
146 """Call an alias by name.
147
147
148 Input: a string containing the name of the alias to call and any
148 Input: a string containing the name of the alias to call and any
149 additional arguments to be passed to the magic.
149 additional arguments to be passed to the magic.
150
150
151 ipalias('name -opt foo bar') is equivalent to typing at the ipython
151 ipalias('name -opt foo bar') is equivalent to typing at the ipython
152 prompt:
152 prompt:
153
153
154 In[1]: name -opt foo bar
154 In[1]: name -opt foo bar
155
155
156 To call an alias without arguments, simply use ipalias('name').
156 To call an alias without arguments, simply use ipalias('name').
157
157
158 This provides a proper Python function to call IPython's aliases in any
158 This provides a proper Python function to call IPython's aliases in any
159 valid Python code you can type at the interpreter, including loops and
159 valid Python code you can type at the interpreter, including loops and
160 compound statements. It is added by IPython to the Python builtin
160 compound statements. It is added by IPython to the Python builtin
161 namespace upon initialization."""
161 namespace upon initialization."""
162
162
163 args = arg_s.split(' ',1)
163 args = arg_s.split(' ',1)
164 alias_name = args[0]
164 alias_name = args[0]
165 try:
165 try:
166 alias_args = args[1]
166 alias_args = args[1]
167 except IndexError:
167 except IndexError:
168 alias_args = ''
168 alias_args = ''
169 if alias_name in __IPYTHON__.alias_table:
169 if alias_name in __IPYTHON__.alias_table:
170 __IPYTHON__.call_alias(alias_name,alias_args)
170 __IPYTHON__.call_alias(alias_name,alias_args)
171 else:
171 else:
172 error("Alias `%s` not found." % alias_name)
172 error("Alias `%s` not found." % alias_name)
173
173
174 def ipsystem(arg_s):
174 def ipsystem(arg_s):
175 """Make a system call, using IPython."""
175 """Make a system call, using IPython."""
176 __IPYTHON__.system(arg_s)
176 __IPYTHON__.system(arg_s)
177
177
178
178
179 #****************************************************************************
179 #****************************************************************************
180 # Local use exceptions
180 # Local use exceptions
181 class SpaceInInput(exceptions.Exception): pass
181 class SpaceInInput(exceptions.Exception): pass
182
182
183 #****************************************************************************
183 #****************************************************************************
184 # Local use classes
184 # Local use classes
185 class Bunch: pass
185 class Bunch: pass
186
186
187 class InputList(list):
187 class InputList(list):
188 """Class to store user input.
188 """Class to store user input.
189
189
190 It's basically a list, but slices return a string instead of a list, thus
190 It's basically a list, but slices return a string instead of a list, thus
191 allowing things like (assuming 'In' is an instance):
191 allowing things like (assuming 'In' is an instance):
192
192
193 exec In[4:7]
193 exec In[4:7]
194
194
195 or
195 or
196
196
197 exec In[5:9] + In[14] + In[21:25]"""
197 exec In[5:9] + In[14] + In[21:25]"""
198
198
199 def __getslice__(self,i,j):
199 def __getslice__(self,i,j):
200 return ''.join(list.__getslice__(self,i,j))
200 return ''.join(list.__getslice__(self,i,j))
201
201
202 class SyntaxTB(ultraTB.ListTB):
202 class SyntaxTB(ultraTB.ListTB):
203 """Extension which holds some state: the last exception value"""
203 """Extension which holds some state: the last exception value"""
204
204
205 def __init__(self,color_scheme = 'NoColor'):
205 def __init__(self,color_scheme = 'NoColor'):
206 ultraTB.ListTB.__init__(self,color_scheme)
206 ultraTB.ListTB.__init__(self,color_scheme)
207 self.last_syntax_error = None
207 self.last_syntax_error = None
208
208
209 def __call__(self, etype, value, elist):
209 def __call__(self, etype, value, elist):
210 self.last_syntax_error = value
210 self.last_syntax_error = value
211 ultraTB.ListTB.__call__(self,etype,value,elist)
211 ultraTB.ListTB.__call__(self,etype,value,elist)
212
212
213 def clear_err_state(self):
213 def clear_err_state(self):
214 """Return the current error state and clear it"""
214 """Return the current error state and clear it"""
215 e = self.last_syntax_error
215 e = self.last_syntax_error
216 self.last_syntax_error = None
216 self.last_syntax_error = None
217 return e
217 return e
218
218
219 #****************************************************************************
219 #****************************************************************************
220 # Main IPython class
220 # Main IPython class
221
221
222 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
222 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
223 # until a full rewrite is made. I've cleaned all cross-class uses of
223 # until a full rewrite is made. I've cleaned all cross-class uses of
224 # attributes and methods, but too much user code out there relies on the
224 # attributes and methods, but too much user code out there relies on the
225 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
225 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
226 #
226 #
227 # But at least now, all the pieces have been separated and we could, in
227 # But at least now, all the pieces have been separated and we could, in
228 # principle, stop using the mixin. This will ease the transition to the
228 # principle, stop using the mixin. This will ease the transition to the
229 # chainsaw branch.
229 # chainsaw branch.
230
230
231 # For reference, the following is the list of 'self.foo' uses in the Magic
231 # For reference, the following is the list of 'self.foo' uses in the Magic
232 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
232 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
233 # class, to prevent clashes.
233 # class, to prevent clashes.
234
234
235 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
235 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
236 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
236 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
237 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
237 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
238 # 'self.value']
238 # 'self.value']
239
239
240 class InteractiveShell(Magic):
240 class InteractiveShell(Magic):
241 """An enhanced console for Python."""
241 """An enhanced console for Python."""
242
242
243 # class attribute to indicate whether the class supports threads or not.
243 # class attribute to indicate whether the class supports threads or not.
244 # Subclasses with thread support should override this as needed.
244 # Subclasses with thread support should override this as needed.
245 isthreaded = False
245 isthreaded = False
246
246
247 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
247 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
248 user_ns = None,user_global_ns=None,banner2='',
248 user_ns = None,user_global_ns=None,banner2='',
249 custom_exceptions=((),None),embedded=False):
249 custom_exceptions=((),None),embedded=False):
250
250
251 # some minimal strict typechecks. For some core data structures, I
251 # some minimal strict typechecks. For some core data structures, I
252 # want actual basic python types, not just anything that looks like
252 # want actual basic python types, not just anything that looks like
253 # one. This is especially true for namespaces.
253 # one. This is especially true for namespaces.
254 for ns in (user_ns,user_global_ns):
254 for ns in (user_ns,user_global_ns):
255 if ns is not None and type(ns) != types.DictType:
255 if ns is not None and type(ns) != types.DictType:
256 raise TypeError,'namespace must be a dictionary'
256 raise TypeError,'namespace must be a dictionary'
257
257
258 # Put a reference to self in builtins so that any form of embedded or
258 # Put a reference to self in builtins so that any form of embedded or
259 # imported code can test for being inside IPython.
259 # imported code can test for being inside IPython.
260 __builtin__.__IPYTHON__ = self
260 __builtin__.__IPYTHON__ = self
261
261
262 # And load into builtins ipmagic/ipalias/ipsystem as well
262 # And load into builtins ipmagic/ipalias/ipsystem as well
263 __builtin__.ipmagic = ipmagic
263 __builtin__.ipmagic = ipmagic
264 __builtin__.ipalias = ipalias
264 __builtin__.ipalias = ipalias
265 __builtin__.ipsystem = ipsystem
265 __builtin__.ipsystem = ipsystem
266
266
267 # Add to __builtin__ other parts of IPython's public API
267 # Add to __builtin__ other parts of IPython's public API
268 __builtin__.ip_set_hook = self.set_hook
268 __builtin__.ip_set_hook = self.set_hook
269
269
270 # Keep in the builtins a flag for when IPython is active. We set it
270 # Keep in the builtins a flag for when IPython is active. We set it
271 # with setdefault so that multiple nested IPythons don't clobber one
271 # with setdefault so that multiple nested IPythons don't clobber one
272 # another. Each will increase its value by one upon being activated,
272 # another. Each will increase its value by one upon being activated,
273 # which also gives us a way to determine the nesting level.
273 # which also gives us a way to determine the nesting level.
274 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
274 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
275
275
276 # Do the intuitively correct thing for quit/exit: we remove the
276 # Do the intuitively correct thing for quit/exit: we remove the
277 # builtins if they exist, and our own prefilter routine will handle
277 # builtins if they exist, and our own prefilter routine will handle
278 # these special cases
278 # these special cases
279 try:
279 try:
280 del __builtin__.exit, __builtin__.quit
280 del __builtin__.exit, __builtin__.quit
281 except AttributeError:
281 except AttributeError:
282 pass
282 pass
283
283
284 # Store the actual shell's name
284 # Store the actual shell's name
285 self.name = name
285 self.name = name
286
286
287 # We need to know whether the instance is meant for embedding, since
287 # We need to know whether the instance is meant for embedding, since
288 # global/local namespaces need to be handled differently in that case
288 # global/local namespaces need to be handled differently in that case
289 self.embedded = embedded
289 self.embedded = embedded
290
290
291 # command compiler
291 # command compiler
292 self.compile = codeop.CommandCompiler()
292 self.compile = codeop.CommandCompiler()
293
293
294 # User input buffer
294 # User input buffer
295 self.buffer = []
295 self.buffer = []
296
296
297 # Default name given in compilation of code
297 # Default name given in compilation of code
298 self.filename = '<ipython console>'
298 self.filename = '<ipython console>'
299
299
300 # Create the namespace where the user will operate. user_ns is
300 # Create the namespace where the user will operate. user_ns is
301 # normally the only one used, and it is passed to the exec calls as
301 # normally the only one used, and it is passed to the exec calls as
302 # the locals argument. But we do carry a user_global_ns namespace
302 # the locals argument. But we do carry a user_global_ns namespace
303 # given as the exec 'globals' argument, This is useful in embedding
303 # given as the exec 'globals' argument, This is useful in embedding
304 # situations where the ipython shell opens in a context where the
304 # situations where the ipython shell opens in a context where the
305 # distinction between locals and globals is meaningful.
305 # distinction between locals and globals is meaningful.
306
306
307 # FIXME. For some strange reason, __builtins__ is showing up at user
307 # FIXME. For some strange reason, __builtins__ is showing up at user
308 # level as a dict instead of a module. This is a manual fix, but I
308 # level as a dict instead of a module. This is a manual fix, but I
309 # should really track down where the problem is coming from. Alex
309 # should really track down where the problem is coming from. Alex
310 # Schmolck reported this problem first.
310 # Schmolck reported this problem first.
311
311
312 # A useful post by Alex Martelli on this topic:
312 # A useful post by Alex Martelli on this topic:
313 # Re: inconsistent value from __builtins__
313 # Re: inconsistent value from __builtins__
314 # Von: Alex Martelli <aleaxit@yahoo.com>
314 # Von: Alex Martelli <aleaxit@yahoo.com>
315 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
315 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
316 # Gruppen: comp.lang.python
316 # Gruppen: comp.lang.python
317
317
318 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
318 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
319 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
319 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
320 # > <type 'dict'>
320 # > <type 'dict'>
321 # > >>> print type(__builtins__)
321 # > >>> print type(__builtins__)
322 # > <type 'module'>
322 # > <type 'module'>
323 # > Is this difference in return value intentional?
323 # > Is this difference in return value intentional?
324
324
325 # Well, it's documented that '__builtins__' can be either a dictionary
325 # Well, it's documented that '__builtins__' can be either a dictionary
326 # or a module, and it's been that way for a long time. Whether it's
326 # or a module, and it's been that way for a long time. Whether it's
327 # intentional (or sensible), I don't know. In any case, the idea is
327 # intentional (or sensible), I don't know. In any case, the idea is
328 # that if you need to access the built-in namespace directly, you
328 # that if you need to access the built-in namespace directly, you
329 # should start with "import __builtin__" (note, no 's') which will
329 # should start with "import __builtin__" (note, no 's') which will
330 # definitely give you a module. Yeah, it's somewhatΒ confusing:-(.
330 # definitely give you a module. Yeah, it's somewhatΒ confusing:-(.
331
331
332 if user_ns is None:
332 if user_ns is None:
333 # Set __name__ to __main__ to better match the behavior of the
333 # Set __name__ to __main__ to better match the behavior of the
334 # normal interpreter.
334 # normal interpreter.
335 user_ns = {'__name__' :'__main__',
335 user_ns = {'__name__' :'__main__',
336 '__builtins__' : __builtin__,
336 '__builtins__' : __builtin__,
337 }
337 }
338
338
339 if user_global_ns is None:
339 if user_global_ns is None:
340 user_global_ns = {}
340 user_global_ns = {}
341
341
342 # Assign namespaces
342 # Assign namespaces
343 # This is the namespace where all normal user variables live
343 # This is the namespace where all normal user variables live
344 self.user_ns = user_ns
344 self.user_ns = user_ns
345 # Embedded instances require a separate namespace for globals.
345 # Embedded instances require a separate namespace for globals.
346 # Normally this one is unused by non-embedded instances.
346 # Normally this one is unused by non-embedded instances.
347 self.user_global_ns = user_global_ns
347 self.user_global_ns = user_global_ns
348 # A namespace to keep track of internal data structures to prevent
348 # A namespace to keep track of internal data structures to prevent
349 # them from cluttering user-visible stuff. Will be updated later
349 # them from cluttering user-visible stuff. Will be updated later
350 self.internal_ns = {}
350 self.internal_ns = {}
351
351
352 # Namespace of system aliases. Each entry in the alias
352 # Namespace of system aliases. Each entry in the alias
353 # table must be a 2-tuple of the form (N,name), where N is the number
353 # table must be a 2-tuple of the form (N,name), where N is the number
354 # of positional arguments of the alias.
354 # of positional arguments of the alias.
355 self.alias_table = {}
355 self.alias_table = {}
356
356
357 # A table holding all the namespaces IPython deals with, so that
357 # A table holding all the namespaces IPython deals with, so that
358 # introspection facilities can search easily.
358 # introspection facilities can search easily.
359 self.ns_table = {'user':user_ns,
359 self.ns_table = {'user':user_ns,
360 'user_global':user_global_ns,
360 'user_global':user_global_ns,
361 'alias':self.alias_table,
361 'alias':self.alias_table,
362 'internal':self.internal_ns,
362 'internal':self.internal_ns,
363 'builtin':__builtin__.__dict__
363 'builtin':__builtin__.__dict__
364 }
364 }
365
365
366 # The user namespace MUST have a pointer to the shell itself.
366 # The user namespace MUST have a pointer to the shell itself.
367 self.user_ns[name] = self
367 self.user_ns[name] = self
368
368
369 # We need to insert into sys.modules something that looks like a
369 # We need to insert into sys.modules something that looks like a
370 # module but which accesses the IPython namespace, for shelve and
370 # module but which accesses the IPython namespace, for shelve and
371 # pickle to work interactively. Normally they rely on getting
371 # pickle to work interactively. Normally they rely on getting
372 # everything out of __main__, but for embedding purposes each IPython
372 # everything out of __main__, but for embedding purposes each IPython
373 # instance has its own private namespace, so we can't go shoving
373 # instance has its own private namespace, so we can't go shoving
374 # everything into __main__.
374 # everything into __main__.
375
375
376 # note, however, that we should only do this for non-embedded
376 # note, however, that we should only do this for non-embedded
377 # ipythons, which really mimic the __main__.__dict__ with their own
377 # ipythons, which really mimic the __main__.__dict__ with their own
378 # namespace. Embedded instances, on the other hand, should not do
378 # namespace. Embedded instances, on the other hand, should not do
379 # this because they need to manage the user local/global namespaces
379 # this because they need to manage the user local/global namespaces
380 # only, but they live within a 'normal' __main__ (meaning, they
380 # only, but they live within a 'normal' __main__ (meaning, they
381 # shouldn't overtake the execution environment of the script they're
381 # shouldn't overtake the execution environment of the script they're
382 # embedded in).
382 # embedded in).
383
383
384 if not embedded:
384 if not embedded:
385 try:
385 try:
386 main_name = self.user_ns['__name__']
386 main_name = self.user_ns['__name__']
387 except KeyError:
387 except KeyError:
388 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
388 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
389 else:
389 else:
390 #print "pickle hack in place" # dbg
390 #print "pickle hack in place" # dbg
391 sys.modules[main_name] = FakeModule(self.user_ns)
391 sys.modules[main_name] = FakeModule(self.user_ns)
392
392
393 # List of input with multi-line handling.
393 # List of input with multi-line handling.
394 # Fill its zero entry, user counter starts at 1
394 # Fill its zero entry, user counter starts at 1
395 self.input_hist = InputList(['\n'])
395 self.input_hist = InputList(['\n'])
396
396
397 # list of visited directories
397 # list of visited directories
398 try:
398 try:
399 self.dir_hist = [os.getcwd()]
399 self.dir_hist = [os.getcwd()]
400 except IOError, e:
400 except IOError, e:
401 self.dir_hist = []
401 self.dir_hist = []
402
402
403 # dict of output history
403 # dict of output history
404 self.output_hist = {}
404 self.output_hist = {}
405
405
406 # dict of things NOT to alias (keywords, builtins and some magics)
406 # dict of things NOT to alias (keywords, builtins and some magics)
407 no_alias = {}
407 no_alias = {}
408 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
408 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
409 for key in keyword.kwlist + no_alias_magics:
409 for key in keyword.kwlist + no_alias_magics:
410 no_alias[key] = 1
410 no_alias[key] = 1
411 no_alias.update(__builtin__.__dict__)
411 no_alias.update(__builtin__.__dict__)
412 self.no_alias = no_alias
412 self.no_alias = no_alias
413
413
414 # make global variables for user access to these
414 # make global variables for user access to these
415 self.user_ns['_ih'] = self.input_hist
415 self.user_ns['_ih'] = self.input_hist
416 self.user_ns['_oh'] = self.output_hist
416 self.user_ns['_oh'] = self.output_hist
417 self.user_ns['_dh'] = self.dir_hist
417 self.user_ns['_dh'] = self.dir_hist
418
418
419 # user aliases to input and output histories
419 # user aliases to input and output histories
420 self.user_ns['In'] = self.input_hist
420 self.user_ns['In'] = self.input_hist
421 self.user_ns['Out'] = self.output_hist
421 self.user_ns['Out'] = self.output_hist
422
422
423 # Object variable to store code object waiting execution. This is
423 # Object variable to store code object waiting execution. This is
424 # used mainly by the multithreaded shells, but it can come in handy in
424 # used mainly by the multithreaded shells, but it can come in handy in
425 # other situations. No need to use a Queue here, since it's a single
425 # other situations. No need to use a Queue here, since it's a single
426 # item which gets cleared once run.
426 # item which gets cleared once run.
427 self.code_to_run = None
427 self.code_to_run = None
428
428
429 # Job manager (for jobs run as background threads)
429 # Job manager (for jobs run as background threads)
430 self.jobs = BackgroundJobManager()
430 self.jobs = BackgroundJobManager()
431 # Put the job manager into builtins so it's always there.
431 # Put the job manager into builtins so it's always there.
432 __builtin__.jobs = self.jobs
432 __builtin__.jobs = self.jobs
433
433
434 # escapes for automatic behavior on the command line
434 # escapes for automatic behavior on the command line
435 self.ESC_SHELL = '!'
435 self.ESC_SHELL = '!'
436 self.ESC_HELP = '?'
436 self.ESC_HELP = '?'
437 self.ESC_MAGIC = '%'
437 self.ESC_MAGIC = '%'
438 self.ESC_QUOTE = ','
438 self.ESC_QUOTE = ','
439 self.ESC_QUOTE2 = ';'
439 self.ESC_QUOTE2 = ';'
440 self.ESC_PAREN = '/'
440 self.ESC_PAREN = '/'
441
441
442 # And their associated handlers
442 # And their associated handlers
443 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
443 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
444 self.ESC_QUOTE : self.handle_auto,
444 self.ESC_QUOTE : self.handle_auto,
445 self.ESC_QUOTE2 : self.handle_auto,
445 self.ESC_QUOTE2 : self.handle_auto,
446 self.ESC_MAGIC : self.handle_magic,
446 self.ESC_MAGIC : self.handle_magic,
447 self.ESC_HELP : self.handle_help,
447 self.ESC_HELP : self.handle_help,
448 self.ESC_SHELL : self.handle_shell_escape,
448 self.ESC_SHELL : self.handle_shell_escape,
449 }
449 }
450
450
451 # class initializations
451 # class initializations
452 Magic.__init__(self,self)
452 Magic.__init__(self,self)
453
453
454 # Python source parser/formatter for syntax highlighting
454 # Python source parser/formatter for syntax highlighting
455 pyformat = PyColorize.Parser().format
455 pyformat = PyColorize.Parser().format
456 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
456 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
457
457
458 # hooks holds pointers used for user-side customizations
458 # hooks holds pointers used for user-side customizations
459 self.hooks = Struct()
459 self.hooks = Struct()
460
460
461 # Set all default hooks, defined in the IPython.hooks module.
461 # Set all default hooks, defined in the IPython.hooks module.
462 hooks = IPython.hooks
462 hooks = IPython.hooks
463 for hook_name in hooks.__all__:
463 for hook_name in hooks.__all__:
464 self.set_hook(hook_name,getattr(hooks,hook_name))
464 self.set_hook(hook_name,getattr(hooks,hook_name))
465
465
466 # Flag to mark unconditional exit
466 # Flag to mark unconditional exit
467 self.exit_now = False
467 self.exit_now = False
468
468
469 self.usage_min = """\
469 self.usage_min = """\
470 An enhanced console for Python.
470 An enhanced console for Python.
471 Some of its features are:
471 Some of its features are:
472 - Readline support if the readline library is present.
472 - Readline support if the readline library is present.
473 - Tab completion in the local namespace.
473 - Tab completion in the local namespace.
474 - Logging of input, see command-line options.
474 - Logging of input, see command-line options.
475 - System shell escape via ! , eg !ls.
475 - System shell escape via ! , eg !ls.
476 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
476 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
477 - Keeps track of locally defined variables via %who, %whos.
477 - Keeps track of locally defined variables via %who, %whos.
478 - Show object information with a ? eg ?x or x? (use ?? for more info).
478 - Show object information with a ? eg ?x or x? (use ?? for more info).
479 """
479 """
480 if usage: self.usage = usage
480 if usage: self.usage = usage
481 else: self.usage = self.usage_min
481 else: self.usage = self.usage_min
482
482
483 # Storage
483 # Storage
484 self.rc = rc # This will hold all configuration information
484 self.rc = rc # This will hold all configuration information
485 self.pager = 'less'
485 self.pager = 'less'
486 # temporary files used for various purposes. Deleted at exit.
486 # temporary files used for various purposes. Deleted at exit.
487 self.tempfiles = []
487 self.tempfiles = []
488
488
489 # Keep track of readline usage (later set by init_readline)
489 # Keep track of readline usage (later set by init_readline)
490 self.has_readline = False
490 self.has_readline = False
491
491
492 # template for logfile headers. It gets resolved at runtime by the
492 # template for logfile headers. It gets resolved at runtime by the
493 # logstart method.
493 # logstart method.
494 self.loghead_tpl = \
494 self.loghead_tpl = \
495 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
495 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
496 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
496 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
497 #log# opts = %s
497 #log# opts = %s
498 #log# args = %s
498 #log# args = %s
499 #log# It is safe to make manual edits below here.
499 #log# It is safe to make manual edits below here.
500 #log#-----------------------------------------------------------------------
500 #log#-----------------------------------------------------------------------
501 """
501 """
502 # for pushd/popd management
502 # for pushd/popd management
503 try:
503 try:
504 self.home_dir = get_home_dir()
504 self.home_dir = get_home_dir()
505 except HomeDirError,msg:
505 except HomeDirError,msg:
506 fatal(msg)
506 fatal(msg)
507
507
508 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
508 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
509
509
510 # Functions to call the underlying shell.
510 # Functions to call the underlying shell.
511
511
512 # utility to expand user variables via Itpl
512 # utility to expand user variables via Itpl
513 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
513 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
514 self.user_ns))
514 self.user_ns))
515 # The first is similar to os.system, but it doesn't return a value,
515 # The first is similar to os.system, but it doesn't return a value,
516 # and it allows interpolation of variables in the user's namespace.
516 # and it allows interpolation of variables in the user's namespace.
517 self.system = lambda cmd: shell(self.var_expand(cmd),
517 self.system = lambda cmd: shell(self.var_expand(cmd),
518 header='IPython system call: ',
518 header='IPython system call: ',
519 verbose=self.rc.system_verbose)
519 verbose=self.rc.system_verbose)
520 # These are for getoutput and getoutputerror:
520 # These are for getoutput and getoutputerror:
521 self.getoutput = lambda cmd: \
521 self.getoutput = lambda cmd: \
522 getoutput(self.var_expand(cmd),
522 getoutput(self.var_expand(cmd),
523 header='IPython system call: ',
523 header='IPython system call: ',
524 verbose=self.rc.system_verbose)
524 verbose=self.rc.system_verbose)
525 self.getoutputerror = lambda cmd: \
525 self.getoutputerror = lambda cmd: \
526 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
526 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
527 self.user_ns)),
527 self.user_ns)),
528 header='IPython system call: ',
528 header='IPython system call: ',
529 verbose=self.rc.system_verbose)
529 verbose=self.rc.system_verbose)
530
530
531 # RegExp for splitting line contents into pre-char//first
531 # RegExp for splitting line contents into pre-char//first
532 # word-method//rest. For clarity, each group in on one line.
532 # word-method//rest. For clarity, each group in on one line.
533
533
534 # WARNING: update the regexp if the above escapes are changed, as they
534 # WARNING: update the regexp if the above escapes are changed, as they
535 # are hardwired in.
535 # are hardwired in.
536
536
537 # Don't get carried away with trying to make the autocalling catch too
537 # Don't get carried away with trying to make the autocalling catch too
538 # much: it's better to be conservative rather than to trigger hidden
538 # much: it's better to be conservative rather than to trigger hidden
539 # evals() somewhere and end up causing side effects.
539 # evals() somewhere and end up causing side effects.
540
540
541 self.line_split = re.compile(r'^([\s*,;/])'
541 self.line_split = re.compile(r'^([\s*,;/])'
542 r'([\?\w\.]+\w*\s*)'
542 r'([\?\w\.]+\w*\s*)'
543 r'(\(?.*$)')
543 r'(\(?.*$)')
544
544
545 # Original re, keep around for a while in case changes break something
545 # Original re, keep around for a while in case changes break something
546 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
546 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
547 # r'(\s*[\?\w\.]+\w*\s*)'
547 # r'(\s*[\?\w\.]+\w*\s*)'
548 # r'(\(?.*$)')
548 # r'(\(?.*$)')
549
549
550 # RegExp to identify potential function names
550 # RegExp to identify potential function names
551 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
551 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
552 # RegExp to exclude strings with this start from autocalling
552 # RegExp to exclude strings with this start from autocalling
553 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
553 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
554
554
555 # try to catch also methods for stuff in lists/tuples/dicts: off
555 # try to catch also methods for stuff in lists/tuples/dicts: off
556 # (experimental). For this to work, the line_split regexp would need
556 # (experimental). For this to work, the line_split regexp would need
557 # to be modified so it wouldn't break things at '['. That line is
557 # to be modified so it wouldn't break things at '['. That line is
558 # nasty enough that I shouldn't change it until I can test it _well_.
558 # nasty enough that I shouldn't change it until I can test it _well_.
559 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
559 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
560
560
561 # keep track of where we started running (mainly for crash post-mortem)
561 # keep track of where we started running (mainly for crash post-mortem)
562 self.starting_dir = os.getcwd()
562 self.starting_dir = os.getcwd()
563
563
564 # Various switches which can be set
564 # Various switches which can be set
565 self.CACHELENGTH = 5000 # this is cheap, it's just text
565 self.CACHELENGTH = 5000 # this is cheap, it's just text
566 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
566 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
567 self.banner2 = banner2
567 self.banner2 = banner2
568
568
569 # TraceBack handlers:
569 # TraceBack handlers:
570
570
571 # Syntax error handler.
571 # Syntax error handler.
572 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
572 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
573
573
574 # The interactive one is initialized with an offset, meaning we always
574 # The interactive one is initialized with an offset, meaning we always
575 # want to remove the topmost item in the traceback, which is our own
575 # want to remove the topmost item in the traceback, which is our own
576 # internal code. Valid modes: ['Plain','Context','Verbose']
576 # internal code. Valid modes: ['Plain','Context','Verbose']
577 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
577 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
578 color_scheme='NoColor',
578 color_scheme='NoColor',
579 tb_offset = 1)
579 tb_offset = 1)
580
580
581 # IPython itself shouldn't crash. This will produce a detailed
581 # IPython itself shouldn't crash. This will produce a detailed
582 # post-mortem if it does. But we only install the crash handler for
582 # post-mortem if it does. But we only install the crash handler for
583 # non-threaded shells, the threaded ones use a normal verbose reporter
583 # non-threaded shells, the threaded ones use a normal verbose reporter
584 # and lose the crash handler. This is because exceptions in the main
584 # and lose the crash handler. This is because exceptions in the main
585 # thread (such as in GUI code) propagate directly to sys.excepthook,
585 # thread (such as in GUI code) propagate directly to sys.excepthook,
586 # and there's no point in printing crash dumps for every user exception.
586 # and there's no point in printing crash dumps for every user exception.
587 if self.isthreaded:
587 if self.isthreaded:
588 sys.excepthook = ultraTB.FormattedTB()
588 sys.excepthook = ultraTB.FormattedTB()
589 else:
589 else:
590 from IPython import CrashHandler
590 from IPython import CrashHandler
591 sys.excepthook = CrashHandler.CrashHandler(self)
591 sys.excepthook = CrashHandler.CrashHandler(self)
592
592
593 # The instance will store a pointer to this, so that runtime code
593 # The instance will store a pointer to this, so that runtime code
594 # (such as magics) can access it. This is because during the
594 # (such as magics) can access it. This is because during the
595 # read-eval loop, it gets temporarily overwritten (to deal with GUI
595 # read-eval loop, it gets temporarily overwritten (to deal with GUI
596 # frameworks).
596 # frameworks).
597 self.sys_excepthook = sys.excepthook
597 self.sys_excepthook = sys.excepthook
598
598
599 # and add any custom exception handlers the user may have specified
599 # and add any custom exception handlers the user may have specified
600 self.set_custom_exc(*custom_exceptions)
600 self.set_custom_exc(*custom_exceptions)
601
601
602 # Object inspector
602 # Object inspector
603 self.inspector = OInspect.Inspector(OInspect.InspectColors,
603 self.inspector = OInspect.Inspector(OInspect.InspectColors,
604 PyColorize.ANSICodeColors,
604 PyColorize.ANSICodeColors,
605 'NoColor')
605 'NoColor')
606 # indentation management
606 # indentation management
607 self.autoindent = False
607 self.autoindent = False
608 self.indent_current_nsp = 0
608 self.indent_current_nsp = 0
609 self.indent_current = '' # actual indent string
609 self.indent_current = '' # actual indent string
610
610
611 # Make some aliases automatically
611 # Make some aliases automatically
612 # Prepare list of shell aliases to auto-define
612 # Prepare list of shell aliases to auto-define
613 if os.name == 'posix':
613 if os.name == 'posix':
614 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
614 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
615 'mv mv -i','rm rm -i','cp cp -i',
615 'mv mv -i','rm rm -i','cp cp -i',
616 'cat cat','less less','clear clear',
616 'cat cat','less less','clear clear',
617 # a better ls
617 # a better ls
618 'ls ls -F',
618 'ls ls -F',
619 # long ls
619 # long ls
620 'll ls -lF',
620 'll ls -lF',
621 # color ls
621 # color ls
622 'lc ls -F -o --color',
622 'lc ls -F -o --color',
623 # ls normal files only
623 # ls normal files only
624 'lf ls -F -o --color %l | grep ^-',
624 'lf ls -F -o --color %l | grep ^-',
625 # ls symbolic links
625 # ls symbolic links
626 'lk ls -F -o --color %l | grep ^l',
626 'lk ls -F -o --color %l | grep ^l',
627 # directories or links to directories,
627 # directories or links to directories,
628 'ldir ls -F -o --color %l | grep /$',
628 'ldir ls -F -o --color %l | grep /$',
629 # things which are executable
629 # things which are executable
630 'lx ls -F -o --color %l | grep ^-..x',
630 'lx ls -F -o --color %l | grep ^-..x',
631 )
631 )
632 elif os.name in ['nt','dos']:
632 elif os.name in ['nt','dos']:
633 auto_alias = ('dir dir /on', 'ls dir /on',
633 auto_alias = ('dir dir /on', 'ls dir /on',
634 'ddir dir /ad /on', 'ldir dir /ad /on',
634 'ddir dir /ad /on', 'ldir dir /ad /on',
635 'mkdir mkdir','rmdir rmdir','echo echo',
635 'mkdir mkdir','rmdir rmdir','echo echo',
636 'ren ren','cls cls','copy copy')
636 'ren ren','cls cls','copy copy')
637 else:
637 else:
638 auto_alias = ()
638 auto_alias = ()
639 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
639 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
640 # Call the actual (public) initializer
640 # Call the actual (public) initializer
641 self.init_auto_alias()
641 self.init_auto_alias()
642 # end __init__
642 # end __init__
643
643
644 def post_config_initialization(self):
644 def post_config_initialization(self):
645 """Post configuration init method
645 """Post configuration init method
646
646
647 This is called after the configuration files have been processed to
647 This is called after the configuration files have been processed to
648 'finalize' the initialization."""
648 'finalize' the initialization."""
649
649
650 rc = self.rc
650 rc = self.rc
651
651
652 # Load readline proper
652 # Load readline proper
653 if rc.readline:
653 if rc.readline:
654 self.init_readline()
654 self.init_readline()
655
655
656 # log system
656 # log system
657 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
657 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
658 # local shortcut, this is used a LOT
658 # local shortcut, this is used a LOT
659 self.log = self.logger.log
659 self.log = self.logger.log
660
660
661 # Initialize cache, set in/out prompts and printing system
661 # Initialize cache, set in/out prompts and printing system
662 self.outputcache = CachedOutput(self,
662 self.outputcache = CachedOutput(self,
663 rc.cache_size,
663 rc.cache_size,
664 rc.pprint,
664 rc.pprint,
665 input_sep = rc.separate_in,
665 input_sep = rc.separate_in,
666 output_sep = rc.separate_out,
666 output_sep = rc.separate_out,
667 output_sep2 = rc.separate_out2,
667 output_sep2 = rc.separate_out2,
668 ps1 = rc.prompt_in1,
668 ps1 = rc.prompt_in1,
669 ps2 = rc.prompt_in2,
669 ps2 = rc.prompt_in2,
670 ps_out = rc.prompt_out,
670 ps_out = rc.prompt_out,
671 pad_left = rc.prompts_pad_left)
671 pad_left = rc.prompts_pad_left)
672
672
673 # user may have over-ridden the default print hook:
673 # user may have over-ridden the default print hook:
674 try:
674 try:
675 self.outputcache.__class__.display = self.hooks.display
675 self.outputcache.__class__.display = self.hooks.display
676 except AttributeError:
676 except AttributeError:
677 pass
677 pass
678
678
679 # I don't like assigning globally to sys, because it means when embedding
679 # I don't like assigning globally to sys, because it means when embedding
680 # instances, each embedded instance overrides the previous choice. But
680 # instances, each embedded instance overrides the previous choice. But
681 # sys.displayhook seems to be called internally by exec, so I don't see a
681 # sys.displayhook seems to be called internally by exec, so I don't see a
682 # way around it.
682 # way around it.
683 sys.displayhook = self.outputcache
683 sys.displayhook = self.outputcache
684
684
685 # Set user colors (don't do it in the constructor above so that it
685 # Set user colors (don't do it in the constructor above so that it
686 # doesn't crash if colors option is invalid)
686 # doesn't crash if colors option is invalid)
687 self.magic_colors(rc.colors)
687 self.magic_colors(rc.colors)
688
688
689 # Set calling of pdb on exceptions
689 # Set calling of pdb on exceptions
690 self.call_pdb = rc.pdb
690 self.call_pdb = rc.pdb
691
691
692 # Load user aliases
692 # Load user aliases
693 for alias in rc.alias:
693 for alias in rc.alias:
694 self.magic_alias(alias)
694 self.magic_alias(alias)
695
695
696 # dynamic data that survives through sessions
696 # dynamic data that survives through sessions
697 # XXX make the filename a config option?
697 # XXX make the filename a config option?
698 persist_base = 'persist'
698 persist_base = 'persist'
699 if rc.profile:
699 if rc.profile:
700 persist_base += '_%s' % rc.profile
700 persist_base += '_%s' % rc.profile
701 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
701 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
702
702
703 try:
703 try:
704 self.persist = pickle.load(file(self.persist_fname))
704 self.persist = pickle.load(file(self.persist_fname))
705 except:
705 except:
706 self.persist = {}
706 self.persist = {}
707
707
708
708
709 for (key, value) in [(k[2:],v) for (k,v) in self.persist.items() if k.startswith('S:')]:
709 for (key, value) in [(k[2:],v) for (k,v) in self.persist.items() if k.startswith('S:')]:
710 try:
710 try:
711 obj = pickle.loads(value)
711 obj = pickle.loads(value)
712 except:
712 except:
713
713
714 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % key
714 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % key
715 print "The error was:",sys.exc_info()[0]
715 print "The error was:",sys.exc_info()[0]
716 continue
716 continue
717
717
718
718
719 self.user_ns[key] = obj
719 self.user_ns[key] = obj
720
720
721
721
722
722
723
723
724 def set_hook(self,name,hook):
724 def set_hook(self,name,hook):
725 """set_hook(name,hook) -> sets an internal IPython hook.
725 """set_hook(name,hook) -> sets an internal IPython hook.
726
726
727 IPython exposes some of its internal API as user-modifiable hooks. By
727 IPython exposes some of its internal API as user-modifiable hooks. By
728 resetting one of these hooks, you can modify IPython's behavior to
728 resetting one of these hooks, you can modify IPython's behavior to
729 call at runtime your own routines."""
729 call at runtime your own routines."""
730
730
731 # At some point in the future, this should validate the hook before it
731 # At some point in the future, this should validate the hook before it
732 # accepts it. Probably at least check that the hook takes the number
732 # accepts it. Probably at least check that the hook takes the number
733 # of args it's supposed to.
733 # of args it's supposed to.
734 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
734 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
735
735
736 def set_custom_exc(self,exc_tuple,handler):
736 def set_custom_exc(self,exc_tuple,handler):
737 """set_custom_exc(exc_tuple,handler)
737 """set_custom_exc(exc_tuple,handler)
738
738
739 Set a custom exception handler, which will be called if any of the
739 Set a custom exception handler, which will be called if any of the
740 exceptions in exc_tuple occur in the mainloop (specifically, in the
740 exceptions in exc_tuple occur in the mainloop (specifically, in the
741 runcode() method.
741 runcode() method.
742
742
743 Inputs:
743 Inputs:
744
744
745 - exc_tuple: a *tuple* of valid exceptions to call the defined
745 - exc_tuple: a *tuple* of valid exceptions to call the defined
746 handler for. It is very important that you use a tuple, and NOT A
746 handler for. It is very important that you use a tuple, and NOT A
747 LIST here, because of the way Python's except statement works. If
747 LIST here, because of the way Python's except statement works. If
748 you only want to trap a single exception, use a singleton tuple:
748 you only want to trap a single exception, use a singleton tuple:
749
749
750 exc_tuple == (MyCustomException,)
750 exc_tuple == (MyCustomException,)
751
751
752 - handler: this must be defined as a function with the following
752 - handler: this must be defined as a function with the following
753 basic interface: def my_handler(self,etype,value,tb).
753 basic interface: def my_handler(self,etype,value,tb).
754
754
755 This will be made into an instance method (via new.instancemethod)
755 This will be made into an instance method (via new.instancemethod)
756 of IPython itself, and it will be called if any of the exceptions
756 of IPython itself, and it will be called if any of the exceptions
757 listed in the exc_tuple are caught. If the handler is None, an
757 listed in the exc_tuple are caught. If the handler is None, an
758 internal basic one is used, which just prints basic info.
758 internal basic one is used, which just prints basic info.
759
759
760 WARNING: by putting in your own exception handler into IPython's main
760 WARNING: by putting in your own exception handler into IPython's main
761 execution loop, you run a very good chance of nasty crashes. This
761 execution loop, you run a very good chance of nasty crashes. This
762 facility should only be used if you really know what you are doing."""
762 facility should only be used if you really know what you are doing."""
763
763
764 assert type(exc_tuple)==type(()) , \
764 assert type(exc_tuple)==type(()) , \
765 "The custom exceptions must be given AS A TUPLE."
765 "The custom exceptions must be given AS A TUPLE."
766
766
767 def dummy_handler(self,etype,value,tb):
767 def dummy_handler(self,etype,value,tb):
768 print '*** Simple custom exception handler ***'
768 print '*** Simple custom exception handler ***'
769 print 'Exception type :',etype
769 print 'Exception type :',etype
770 print 'Exception value:',value
770 print 'Exception value:',value
771 print 'Traceback :',tb
771 print 'Traceback :',tb
772 print 'Source code :','\n'.join(self.buffer)
772 print 'Source code :','\n'.join(self.buffer)
773
773
774 if handler is None: handler = dummy_handler
774 if handler is None: handler = dummy_handler
775
775
776 self.CustomTB = new.instancemethod(handler,self,self.__class__)
776 self.CustomTB = new.instancemethod(handler,self,self.__class__)
777 self.custom_exceptions = exc_tuple
777 self.custom_exceptions = exc_tuple
778
778
779 def set_custom_completer(self,completer,pos=0):
779 def set_custom_completer(self,completer,pos=0):
780 """set_custom_completer(completer,pos=0)
780 """set_custom_completer(completer,pos=0)
781
781
782 Adds a new custom completer function.
782 Adds a new custom completer function.
783
783
784 The position argument (defaults to 0) is the index in the completers
784 The position argument (defaults to 0) is the index in the completers
785 list where you want the completer to be inserted."""
785 list where you want the completer to be inserted."""
786
786
787 newcomp = new.instancemethod(completer,self.Completer,
787 newcomp = new.instancemethod(completer,self.Completer,
788 self.Completer.__class__)
788 self.Completer.__class__)
789 self.Completer.matchers.insert(pos,newcomp)
789 self.Completer.matchers.insert(pos,newcomp)
790
790
791 def _get_call_pdb(self):
791 def _get_call_pdb(self):
792 return self._call_pdb
792 return self._call_pdb
793
793
794 def _set_call_pdb(self,val):
794 def _set_call_pdb(self,val):
795
795
796 if val not in (0,1,False,True):
796 if val not in (0,1,False,True):
797 raise ValueError,'new call_pdb value must be boolean'
797 raise ValueError,'new call_pdb value must be boolean'
798
798
799 # store value in instance
799 # store value in instance
800 self._call_pdb = val
800 self._call_pdb = val
801
801
802 # notify the actual exception handlers
802 # notify the actual exception handlers
803 self.InteractiveTB.call_pdb = val
803 self.InteractiveTB.call_pdb = val
804 if self.isthreaded:
804 if self.isthreaded:
805 try:
805 try:
806 self.sys_excepthook.call_pdb = val
806 self.sys_excepthook.call_pdb = val
807 except:
807 except:
808 warn('Failed to activate pdb for threaded exception handler')
808 warn('Failed to activate pdb for threaded exception handler')
809
809
810 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
810 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
811 'Control auto-activation of pdb at exceptions')
811 'Control auto-activation of pdb at exceptions')
812
812
813 def complete(self,text):
813 def complete(self,text):
814 """Return a sorted list of all possible completions on text.
814 """Return a sorted list of all possible completions on text.
815
815
816 Inputs:
816 Inputs:
817
817
818 - text: a string of text to be completed on.
818 - text: a string of text to be completed on.
819
819
820 This is a wrapper around the completion mechanism, similar to what
820 This is a wrapper around the completion mechanism, similar to what
821 readline does at the command line when the TAB key is hit. By
821 readline does at the command line when the TAB key is hit. By
822 exposing it as a method, it can be used by other non-readline
822 exposing it as a method, it can be used by other non-readline
823 environments (such as GUIs) for text completion.
823 environments (such as GUIs) for text completion.
824
824
825 Simple usage example:
825 Simple usage example:
826
826
827 In [1]: x = 'hello'
827 In [1]: x = 'hello'
828
828
829 In [2]: __IP.complete('x.l')
829 In [2]: __IP.complete('x.l')
830 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
830 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
831
831
832 complete = self.Completer.complete
832 complete = self.Completer.complete
833 state = 0
833 state = 0
834 # use a dict so we get unique keys, since ipyhton's multiple
834 # use a dict so we get unique keys, since ipyhton's multiple
835 # completers can return duplicates.
835 # completers can return duplicates.
836 comps = {}
836 comps = {}
837 while True:
837 while True:
838 newcomp = complete(text,state)
838 newcomp = complete(text,state)
839 if newcomp is None:
839 if newcomp is None:
840 break
840 break
841 comps[newcomp] = 1
841 comps[newcomp] = 1
842 state += 1
842 state += 1
843 outcomps = comps.keys()
843 outcomps = comps.keys()
844 outcomps.sort()
844 outcomps.sort()
845 return outcomps
845 return outcomps
846
846
847 def set_completer_frame(self, frame):
847 def set_completer_frame(self, frame):
848 if frame:
848 if frame:
849 self.Completer.namespace = frame.f_locals
849 self.Completer.namespace = frame.f_locals
850 self.Completer.global_namespace = frame.f_globals
850 self.Completer.global_namespace = frame.f_globals
851 else:
851 else:
852 self.Completer.namespace = self.user_ns
852 self.Completer.namespace = self.user_ns
853 self.Completer.global_namespace = self.user_global_ns
853 self.Completer.global_namespace = self.user_global_ns
854
854
855 def init_auto_alias(self):
855 def init_auto_alias(self):
856 """Define some aliases automatically.
856 """Define some aliases automatically.
857
857
858 These are ALL parameter-less aliases"""
858 These are ALL parameter-less aliases"""
859 for alias,cmd in self.auto_alias:
859 for alias,cmd in self.auto_alias:
860 self.alias_table[alias] = (0,cmd)
860 self.alias_table[alias] = (0,cmd)
861
861
862 def alias_table_validate(self,verbose=0):
862 def alias_table_validate(self,verbose=0):
863 """Update information about the alias table.
863 """Update information about the alias table.
864
864
865 In particular, make sure no Python keywords/builtins are in it."""
865 In particular, make sure no Python keywords/builtins are in it."""
866
866
867 no_alias = self.no_alias
867 no_alias = self.no_alias
868 for k in self.alias_table.keys():
868 for k in self.alias_table.keys():
869 if k in no_alias:
869 if k in no_alias:
870 del self.alias_table[k]
870 del self.alias_table[k]
871 if verbose:
871 if verbose:
872 print ("Deleting alias <%s>, it's a Python "
872 print ("Deleting alias <%s>, it's a Python "
873 "keyword or builtin." % k)
873 "keyword or builtin." % k)
874
874
875 def set_autoindent(self,value=None):
875 def set_autoindent(self,value=None):
876 """Set the autoindent flag, checking for readline support.
876 """Set the autoindent flag, checking for readline support.
877
877
878 If called with no arguments, it acts as a toggle."""
878 If called with no arguments, it acts as a toggle."""
879
879
880 if not self.has_readline:
880 if not self.has_readline:
881 if os.name == 'posix':
881 if os.name == 'posix':
882 warn("The auto-indent feature requires the readline library")
882 warn("The auto-indent feature requires the readline library")
883 self.autoindent = 0
883 self.autoindent = 0
884 return
884 return
885 if value is None:
885 if value is None:
886 self.autoindent = not self.autoindent
886 self.autoindent = not self.autoindent
887 else:
887 else:
888 self.autoindent = value
888 self.autoindent = value
889
889
890 def rc_set_toggle(self,rc_field,value=None):
890 def rc_set_toggle(self,rc_field,value=None):
891 """Set or toggle a field in IPython's rc config. structure.
891 """Set or toggle a field in IPython's rc config. structure.
892
892
893 If called with no arguments, it acts as a toggle.
893 If called with no arguments, it acts as a toggle.
894
894
895 If called with a non-existent field, the resulting AttributeError
895 If called with a non-existent field, the resulting AttributeError
896 exception will propagate out."""
896 exception will propagate out."""
897
897
898 rc_val = getattr(self.rc,rc_field)
898 rc_val = getattr(self.rc,rc_field)
899 if value is None:
899 if value is None:
900 value = not rc_val
900 value = not rc_val
901 setattr(self.rc,rc_field,value)
901 setattr(self.rc,rc_field,value)
902
902
903 def user_setup(self,ipythondir,rc_suffix,mode='install'):
903 def user_setup(self,ipythondir,rc_suffix,mode='install'):
904 """Install the user configuration directory.
904 """Install the user configuration directory.
905
905
906 Can be called when running for the first time or to upgrade the user's
906 Can be called when running for the first time or to upgrade the user's
907 .ipython/ directory with the mode parameter. Valid modes are 'install'
907 .ipython/ directory with the mode parameter. Valid modes are 'install'
908 and 'upgrade'."""
908 and 'upgrade'."""
909
909
910 def wait():
910 def wait():
911 try:
911 try:
912 raw_input("Please press <RETURN> to start IPython.")
912 raw_input("Please press <RETURN> to start IPython.")
913 except EOFError:
913 except EOFError:
914 print >> Term.cout
914 print >> Term.cout
915 print '*'*70
915 print '*'*70
916
916
917 cwd = os.getcwd() # remember where we started
917 cwd = os.getcwd() # remember where we started
918 glb = glob.glob
918 glb = glob.glob
919 print '*'*70
919 print '*'*70
920 if mode == 'install':
920 if mode == 'install':
921 print \
921 print \
922 """Welcome to IPython. I will try to create a personal configuration directory
922 """Welcome to IPython. I will try to create a personal configuration directory
923 where you can customize many aspects of IPython's functionality in:\n"""
923 where you can customize many aspects of IPython's functionality in:\n"""
924 else:
924 else:
925 print 'I am going to upgrade your configuration in:'
925 print 'I am going to upgrade your configuration in:'
926
926
927 print ipythondir
927 print ipythondir
928
928
929 rcdirend = os.path.join('IPython','UserConfig')
929 rcdirend = os.path.join('IPython','UserConfig')
930 cfg = lambda d: os.path.join(d,rcdirend)
930 cfg = lambda d: os.path.join(d,rcdirend)
931 try:
931 try:
932 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
932 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
933 except IOError:
933 except IOError:
934 warning = """
934 warning = """
935 Installation error. IPython's directory was not found.
935 Installation error. IPython's directory was not found.
936
936
937 Check the following:
937 Check the following:
938
938
939 The ipython/IPython directory should be in a directory belonging to your
939 The ipython/IPython directory should be in a directory belonging to your
940 PYTHONPATH environment variable (that is, it should be in a directory
940 PYTHONPATH environment variable (that is, it should be in a directory
941 belonging to sys.path). You can copy it explicitly there or just link to it.
941 belonging to sys.path). You can copy it explicitly there or just link to it.
942
942
943 IPython will proceed with builtin defaults.
943 IPython will proceed with builtin defaults.
944 """
944 """
945 warn(warning)
945 warn(warning)
946 wait()
946 wait()
947 return
947 return
948
948
949 if mode == 'install':
949 if mode == 'install':
950 try:
950 try:
951 shutil.copytree(rcdir,ipythondir)
951 shutil.copytree(rcdir,ipythondir)
952 os.chdir(ipythondir)
952 os.chdir(ipythondir)
953 rc_files = glb("ipythonrc*")
953 rc_files = glb("ipythonrc*")
954 for rc_file in rc_files:
954 for rc_file in rc_files:
955 os.rename(rc_file,rc_file+rc_suffix)
955 os.rename(rc_file,rc_file+rc_suffix)
956 except:
956 except:
957 warning = """
957 warning = """
958
958
959 There was a problem with the installation:
959 There was a problem with the installation:
960 %s
960 %s
961 Try to correct it or contact the developers if you think it's a bug.
961 Try to correct it or contact the developers if you think it's a bug.
962 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
962 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
963 warn(warning)
963 warn(warning)
964 wait()
964 wait()
965 return
965 return
966
966
967 elif mode == 'upgrade':
967 elif mode == 'upgrade':
968 try:
968 try:
969 os.chdir(ipythondir)
969 os.chdir(ipythondir)
970 except:
970 except:
971 print """
971 print """
972 Can not upgrade: changing to directory %s failed. Details:
972 Can not upgrade: changing to directory %s failed. Details:
973 %s
973 %s
974 """ % (ipythondir,sys.exc_info()[1])
974 """ % (ipythondir,sys.exc_info()[1])
975 wait()
975 wait()
976 return
976 return
977 else:
977 else:
978 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
978 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
979 for new_full_path in sources:
979 for new_full_path in sources:
980 new_filename = os.path.basename(new_full_path)
980 new_filename = os.path.basename(new_full_path)
981 if new_filename.startswith('ipythonrc'):
981 if new_filename.startswith('ipythonrc'):
982 new_filename = new_filename + rc_suffix
982 new_filename = new_filename + rc_suffix
983 # The config directory should only contain files, skip any
983 # The config directory should only contain files, skip any
984 # directories which may be there (like CVS)
984 # directories which may be there (like CVS)
985 if os.path.isdir(new_full_path):
985 if os.path.isdir(new_full_path):
986 continue
986 continue
987 if os.path.exists(new_filename):
987 if os.path.exists(new_filename):
988 old_file = new_filename+'.old'
988 old_file = new_filename+'.old'
989 if os.path.exists(old_file):
989 if os.path.exists(old_file):
990 os.remove(old_file)
990 os.remove(old_file)
991 os.rename(new_filename,old_file)
991 os.rename(new_filename,old_file)
992 shutil.copy(new_full_path,new_filename)
992 shutil.copy(new_full_path,new_filename)
993 else:
993 else:
994 raise ValueError,'unrecognized mode for install:',`mode`
994 raise ValueError,'unrecognized mode for install:',`mode`
995
995
996 # Fix line-endings to those native to each platform in the config
996 # Fix line-endings to those native to each platform in the config
997 # directory.
997 # directory.
998 try:
998 try:
999 os.chdir(ipythondir)
999 os.chdir(ipythondir)
1000 except:
1000 except:
1001 print """
1001 print """
1002 Problem: changing to directory %s failed.
1002 Problem: changing to directory %s failed.
1003 Details:
1003 Details:
1004 %s
1004 %s
1005
1005
1006 Some configuration files may have incorrect line endings. This should not
1006 Some configuration files may have incorrect line endings. This should not
1007 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1007 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1008 wait()
1008 wait()
1009 else:
1009 else:
1010 for fname in glb('ipythonrc*'):
1010 for fname in glb('ipythonrc*'):
1011 try:
1011 try:
1012 native_line_ends(fname,backup=0)
1012 native_line_ends(fname,backup=0)
1013 except IOError:
1013 except IOError:
1014 pass
1014 pass
1015
1015
1016 if mode == 'install':
1016 if mode == 'install':
1017 print """
1017 print """
1018 Successful installation!
1018 Successful installation!
1019
1019
1020 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1020 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1021 IPython manual (there are both HTML and PDF versions supplied with the
1021 IPython manual (there are both HTML and PDF versions supplied with the
1022 distribution) to make sure that your system environment is properly configured
1022 distribution) to make sure that your system environment is properly configured
1023 to take advantage of IPython's features."""
1023 to take advantage of IPython's features."""
1024 else:
1024 else:
1025 print """
1025 print """
1026 Successful upgrade!
1026 Successful upgrade!
1027
1027
1028 All files in your directory:
1028 All files in your directory:
1029 %(ipythondir)s
1029 %(ipythondir)s
1030 which would have been overwritten by the upgrade were backed up with a .old
1030 which would have been overwritten by the upgrade were backed up with a .old
1031 extension. If you had made particular customizations in those files you may
1031 extension. If you had made particular customizations in those files you may
1032 want to merge them back into the new files.""" % locals()
1032 want to merge them back into the new files.""" % locals()
1033 wait()
1033 wait()
1034 os.chdir(cwd)
1034 os.chdir(cwd)
1035 # end user_setup()
1035 # end user_setup()
1036
1036
1037 def atexit_operations(self):
1037 def atexit_operations(self):
1038 """This will be executed at the time of exit.
1038 """This will be executed at the time of exit.
1039
1039
1040 Saving of persistent data should be performed here. """
1040 Saving of persistent data should be performed here. """
1041
1041
1042 # input history
1042 # input history
1043 self.savehist()
1043 self.savehist()
1044
1044
1045 # Cleanup all tempfiles left around
1045 # Cleanup all tempfiles left around
1046 for tfile in self.tempfiles:
1046 for tfile in self.tempfiles:
1047 try:
1047 try:
1048 os.unlink(tfile)
1048 os.unlink(tfile)
1049 except OSError:
1049 except OSError:
1050 pass
1050 pass
1051
1051
1052 # save the "persistent data" catch-all dictionary
1052 # save the "persistent data" catch-all dictionary
1053 try:
1053 try:
1054 pickle.dump(self.persist, open(self.persist_fname,"w"))
1054 pickle.dump(self.persist, open(self.persist_fname,"w"))
1055 except:
1055 except:
1056 print "*** ERROR *** persistent data saving failed."
1056 print "*** ERROR *** persistent data saving failed."
1057
1057
1058 def savehist(self):
1058 def savehist(self):
1059 """Save input history to a file (via readline library)."""
1059 """Save input history to a file (via readline library)."""
1060 try:
1060 try:
1061 self.readline.write_history_file(self.histfile)
1061 self.readline.write_history_file(self.histfile)
1062 except:
1062 except:
1063 print 'Unable to save IPython command history to file: ' + \
1063 print 'Unable to save IPython command history to file: ' + \
1064 `self.histfile`
1064 `self.histfile`
1065
1065
1066 def pre_readline(self):
1066 def pre_readline(self):
1067 """readline hook to be used at the start of each line.
1067 """readline hook to be used at the start of each line.
1068
1068
1069 Currently it handles auto-indent only."""
1069 Currently it handles auto-indent only."""
1070
1070
1071 self.readline.insert_text(self.indent_current)
1071 self.readline.insert_text(self.indent_current)
1072
1072
1073 def init_readline(self):
1073 def init_readline(self):
1074 """Command history completion/saving/reloading."""
1074 """Command history completion/saving/reloading."""
1075 try:
1075 try:
1076 import readline
1076 import readline
1077 except ImportError:
1077 except ImportError:
1078 self.has_readline = 0
1078 self.has_readline = 0
1079 self.readline = None
1079 self.readline = None
1080 # no point in bugging windows users with this every time:
1080 # no point in bugging windows users with this every time:
1081 if os.name == 'posix':
1081 if os.name == 'posix':
1082 warn('Readline services not available on this platform.')
1082 warn('Readline services not available on this platform.')
1083 else:
1083 else:
1084 import atexit
1084 import atexit
1085 from IPython.completer import IPCompleter
1085 from IPython.completer import IPCompleter
1086 self.Completer = IPCompleter(self,
1086 self.Completer = IPCompleter(self,
1087 self.user_ns,
1087 self.user_ns,
1088 self.user_global_ns,
1088 self.user_global_ns,
1089 self.rc.readline_omit__names,
1089 self.rc.readline_omit__names,
1090 self.alias_table)
1090 self.alias_table)
1091
1091
1092 # Platform-specific configuration
1092 # Platform-specific configuration
1093 if os.name == 'nt':
1093 if os.name == 'nt':
1094 self.readline_startup_hook = readline.set_pre_input_hook
1094 self.readline_startup_hook = readline.set_pre_input_hook
1095 else:
1095 else:
1096 self.readline_startup_hook = readline.set_startup_hook
1096 self.readline_startup_hook = readline.set_startup_hook
1097
1097
1098 # Load user's initrc file (readline config)
1098 # Load user's initrc file (readline config)
1099 inputrc_name = os.environ.get('INPUTRC')
1099 inputrc_name = os.environ.get('INPUTRC')
1100 if inputrc_name is None:
1100 if inputrc_name is None:
1101 home_dir = get_home_dir()
1101 home_dir = get_home_dir()
1102 if home_dir is not None:
1102 if home_dir is not None:
1103 inputrc_name = os.path.join(home_dir,'.inputrc')
1103 inputrc_name = os.path.join(home_dir,'.inputrc')
1104 if os.path.isfile(inputrc_name):
1104 if os.path.isfile(inputrc_name):
1105 try:
1105 try:
1106 readline.read_init_file(inputrc_name)
1106 readline.read_init_file(inputrc_name)
1107 except:
1107 except:
1108 warn('Problems reading readline initialization file <%s>'
1108 warn('Problems reading readline initialization file <%s>'
1109 % inputrc_name)
1109 % inputrc_name)
1110
1110
1111 self.has_readline = 1
1111 self.has_readline = 1
1112 self.readline = readline
1112 self.readline = readline
1113 # save this in sys so embedded copies can restore it properly
1113 # save this in sys so embedded copies can restore it properly
1114 sys.ipcompleter = self.Completer.complete
1114 sys.ipcompleter = self.Completer.complete
1115 readline.set_completer(self.Completer.complete)
1115 readline.set_completer(self.Completer.complete)
1116
1116
1117 # Configure readline according to user's prefs
1117 # Configure readline according to user's prefs
1118 for rlcommand in self.rc.readline_parse_and_bind:
1118 for rlcommand in self.rc.readline_parse_and_bind:
1119 readline.parse_and_bind(rlcommand)
1119 readline.parse_and_bind(rlcommand)
1120
1120
1121 # remove some chars from the delimiters list
1121 # remove some chars from the delimiters list
1122 delims = readline.get_completer_delims()
1122 delims = readline.get_completer_delims()
1123 delims = delims.translate(string._idmap,
1123 delims = delims.translate(string._idmap,
1124 self.rc.readline_remove_delims)
1124 self.rc.readline_remove_delims)
1125 readline.set_completer_delims(delims)
1125 readline.set_completer_delims(delims)
1126 # otherwise we end up with a monster history after a while:
1126 # otherwise we end up with a monster history after a while:
1127 readline.set_history_length(1000)
1127 readline.set_history_length(1000)
1128 try:
1128 try:
1129 #print '*** Reading readline history' # dbg
1129 #print '*** Reading readline history' # dbg
1130 readline.read_history_file(self.histfile)
1130 readline.read_history_file(self.histfile)
1131 except IOError:
1131 except IOError:
1132 pass # It doesn't exist yet.
1132 pass # It doesn't exist yet.
1133
1133
1134 atexit.register(self.atexit_operations)
1134 atexit.register(self.atexit_operations)
1135 del atexit
1135 del atexit
1136
1136
1137 # Configure auto-indent for all platforms
1137 # Configure auto-indent for all platforms
1138 self.set_autoindent(self.rc.autoindent)
1138 self.set_autoindent(self.rc.autoindent)
1139
1139
1140 def _should_recompile(self,e):
1140 def _should_recompile(self,e):
1141 """Utility routine for edit_syntax_error"""
1141 """Utility routine for edit_syntax_error"""
1142
1142
1143 if e.filename in ('<ipython console>','<input>','<string>',
1143 if e.filename in ('<ipython console>','<input>','<string>',
1144 '<console>'):
1144 '<console>'):
1145 return False
1145 return False
1146 try:
1146 try:
1147 if not ask_yes_no('Return to editor to correct syntax error? '
1147 if not ask_yes_no('Return to editor to correct syntax error? '
1148 '[Y/n] ','y'):
1148 '[Y/n] ','y'):
1149 return False
1149 return False
1150 except EOFError:
1150 except EOFError:
1151 return False
1151 return False
1152 self.hooks.fix_error_editor(e.filename,e.lineno,e.offset,e.msg)
1152 self.hooks.fix_error_editor(e.filename,e.lineno,e.offset,e.msg)
1153 return True
1153 return True
1154
1154
1155 def edit_syntax_error(self):
1155 def edit_syntax_error(self):
1156 """The bottom half of the syntax error handler called in the main loop.
1156 """The bottom half of the syntax error handler called in the main loop.
1157
1157
1158 Loop until syntax error is fixed or user cancels.
1158 Loop until syntax error is fixed or user cancels.
1159 """
1159 """
1160
1160
1161 while self.SyntaxTB.last_syntax_error:
1161 while self.SyntaxTB.last_syntax_error:
1162 # copy and clear last_syntax_error
1162 # copy and clear last_syntax_error
1163 err = self.SyntaxTB.clear_err_state()
1163 err = self.SyntaxTB.clear_err_state()
1164 if not self._should_recompile(err):
1164 if not self._should_recompile(err):
1165 return
1165 return
1166 try:
1166 try:
1167 # may set last_syntax_error again if a SyntaxError is raised
1167 # may set last_syntax_error again if a SyntaxError is raised
1168 self.safe_execfile(err.filename,self.shell.user_ns)
1168 self.safe_execfile(err.filename,self.shell.user_ns)
1169 except:
1169 except:
1170 self.showtraceback()
1170 self.showtraceback()
1171 else:
1171 else:
1172 f = file(err.filename)
1172 f = file(err.filename)
1173 try:
1173 try:
1174 sys.displayhook(f.read())
1174 sys.displayhook(f.read())
1175 finally:
1175 finally:
1176 f.close()
1176 f.close()
1177
1177
1178 def showsyntaxerror(self, filename=None):
1178 def showsyntaxerror(self, filename=None):
1179 """Display the syntax error that just occurred.
1179 """Display the syntax error that just occurred.
1180
1180
1181 This doesn't display a stack trace because there isn't one.
1181 This doesn't display a stack trace because there isn't one.
1182
1182
1183 If a filename is given, it is stuffed in the exception instead
1183 If a filename is given, it is stuffed in the exception instead
1184 of what was there before (because Python's parser always uses
1184 of what was there before (because Python's parser always uses
1185 "<string>" when reading from a string).
1185 "<string>" when reading from a string).
1186 """
1186 """
1187 etype, value, last_traceback = sys.exc_info()
1187 etype, value, last_traceback = sys.exc_info()
1188 if filename and etype is SyntaxError:
1188 if filename and etype is SyntaxError:
1189 # Work hard to stuff the correct filename in the exception
1189 # Work hard to stuff the correct filename in the exception
1190 try:
1190 try:
1191 msg, (dummy_filename, lineno, offset, line) = value
1191 msg, (dummy_filename, lineno, offset, line) = value
1192 except:
1192 except:
1193 # Not the format we expect; leave it alone
1193 # Not the format we expect; leave it alone
1194 pass
1194 pass
1195 else:
1195 else:
1196 # Stuff in the right filename
1196 # Stuff in the right filename
1197 try:
1197 try:
1198 # Assume SyntaxError is a class exception
1198 # Assume SyntaxError is a class exception
1199 value = SyntaxError(msg, (filename, lineno, offset, line))
1199 value = SyntaxError(msg, (filename, lineno, offset, line))
1200 except:
1200 except:
1201 # If that failed, assume SyntaxError is a string
1201 # If that failed, assume SyntaxError is a string
1202 value = msg, (filename, lineno, offset, line)
1202 value = msg, (filename, lineno, offset, line)
1203 self.SyntaxTB(etype,value,[])
1203 self.SyntaxTB(etype,value,[])
1204
1204
1205 def debugger(self):
1205 def debugger(self):
1206 """Call the pdb debugger."""
1206 """Call the pdb debugger."""
1207
1207
1208 if not self.rc.pdb:
1208 if not self.rc.pdb:
1209 return
1209 return
1210 pdb.pm()
1210 pdb.pm()
1211
1211
1212 def showtraceback(self,exc_tuple = None,filename=None):
1212 def showtraceback(self,exc_tuple = None,filename=None):
1213 """Display the exception that just occurred."""
1213 """Display the exception that just occurred."""
1214
1214
1215 # Though this won't be called by syntax errors in the input line,
1215 # Though this won't be called by syntax errors in the input line,
1216 # there may be SyntaxError cases whith imported code.
1216 # there may be SyntaxError cases whith imported code.
1217 if exc_tuple is None:
1217 if exc_tuple is None:
1218 type, value, tb = sys.exc_info()
1218 type, value, tb = sys.exc_info()
1219 else:
1219 else:
1220 type, value, tb = exc_tuple
1220 type, value, tb = exc_tuple
1221 if type is SyntaxError:
1221 if type is SyntaxError:
1222 self.showsyntaxerror(filename)
1222 self.showsyntaxerror(filename)
1223 else:
1223 else:
1224 self.InteractiveTB()
1224 self.InteractiveTB()
1225 if self.InteractiveTB.call_pdb and self.has_readline:
1225 if self.InteractiveTB.call_pdb and self.has_readline:
1226 # pdb mucks up readline, fix it back
1226 # pdb mucks up readline, fix it back
1227 self.readline.set_completer(self.Completer.complete)
1227 self.readline.set_completer(self.Completer.complete)
1228
1228
1229 def mainloop(self,banner=None):
1229 def mainloop(self,banner=None):
1230 """Creates the local namespace and starts the mainloop.
1230 """Creates the local namespace and starts the mainloop.
1231
1231
1232 If an optional banner argument is given, it will override the
1232 If an optional banner argument is given, it will override the
1233 internally created default banner."""
1233 internally created default banner."""
1234
1234
1235 if self.rc.c: # Emulate Python's -c option
1235 if self.rc.c: # Emulate Python's -c option
1236 self.exec_init_cmd()
1236 self.exec_init_cmd()
1237 if banner is None:
1237 if banner is None:
1238 if self.rc.banner:
1238 if self.rc.banner:
1239 banner = self.BANNER+self.banner2
1239 banner = self.BANNER+self.banner2
1240 else:
1240 else:
1241 banner = ''
1241 banner = ''
1242 self.interact(banner)
1242 self.interact(banner)
1243
1243
1244 def exec_init_cmd(self):
1244 def exec_init_cmd(self):
1245 """Execute a command given at the command line.
1245 """Execute a command given at the command line.
1246
1246
1247 This emulates Python's -c option."""
1247 This emulates Python's -c option."""
1248
1248
1249 sys.argv = ['-c']
1249 sys.argv = ['-c']
1250 self.push(self.rc.c)
1250 self.push(self.rc.c)
1251
1251
1252 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1252 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1253 """Embeds IPython into a running python program.
1253 """Embeds IPython into a running python program.
1254
1254
1255 Input:
1255 Input:
1256
1256
1257 - header: An optional header message can be specified.
1257 - header: An optional header message can be specified.
1258
1258
1259 - local_ns, global_ns: working namespaces. If given as None, the
1259 - local_ns, global_ns: working namespaces. If given as None, the
1260 IPython-initialized one is updated with __main__.__dict__, so that
1260 IPython-initialized one is updated with __main__.__dict__, so that
1261 program variables become visible but user-specific configuration
1261 program variables become visible but user-specific configuration
1262 remains possible.
1262 remains possible.
1263
1263
1264 - stack_depth: specifies how many levels in the stack to go to
1264 - stack_depth: specifies how many levels in the stack to go to
1265 looking for namespaces (when local_ns and global_ns are None). This
1265 looking for namespaces (when local_ns and global_ns are None). This
1266 allows an intermediate caller to make sure that this function gets
1266 allows an intermediate caller to make sure that this function gets
1267 the namespace from the intended level in the stack. By default (0)
1267 the namespace from the intended level in the stack. By default (0)
1268 it will get its locals and globals from the immediate caller.
1268 it will get its locals and globals from the immediate caller.
1269
1269
1270 Warning: it's possible to use this in a program which is being run by
1270 Warning: it's possible to use this in a program which is being run by
1271 IPython itself (via %run), but some funny things will happen (a few
1271 IPython itself (via %run), but some funny things will happen (a few
1272 globals get overwritten). In the future this will be cleaned up, as
1272 globals get overwritten). In the future this will be cleaned up, as
1273 there is no fundamental reason why it can't work perfectly."""
1273 there is no fundamental reason why it can't work perfectly."""
1274
1274
1275 # Get locals and globals from caller
1275 # Get locals and globals from caller
1276 if local_ns is None or global_ns is None:
1276 if local_ns is None or global_ns is None:
1277 call_frame = sys._getframe(stack_depth).f_back
1277 call_frame = sys._getframe(stack_depth).f_back
1278
1278
1279 if local_ns is None:
1279 if local_ns is None:
1280 local_ns = call_frame.f_locals
1280 local_ns = call_frame.f_locals
1281 if global_ns is None:
1281 if global_ns is None:
1282 global_ns = call_frame.f_globals
1282 global_ns = call_frame.f_globals
1283
1283
1284 # Update namespaces and fire up interpreter
1284 # Update namespaces and fire up interpreter
1285 self.user_ns = local_ns
1285 self.user_ns = local_ns
1286 self.user_global_ns = global_ns
1286 self.user_global_ns = global_ns
1287
1287
1288 # Patch for global embedding to make sure that things don't overwrite
1288 # Patch for global embedding to make sure that things don't overwrite
1289 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1289 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1290 # FIXME. Test this a bit more carefully (the if.. is new)
1290 # FIXME. Test this a bit more carefully (the if.. is new)
1291 if local_ns is None and global_ns is None:
1291 if local_ns is None and global_ns is None:
1292 self.user_global_ns.update(__main__.__dict__)
1292 self.user_global_ns.update(__main__.__dict__)
1293
1293
1294 # make sure the tab-completer has the correct frame information, so it
1294 # make sure the tab-completer has the correct frame information, so it
1295 # actually completes using the frame's locals/globals
1295 # actually completes using the frame's locals/globals
1296 self.set_completer_frame(call_frame)
1296 self.set_completer_frame(call_frame)
1297
1297
1298 self.interact(header)
1298 self.interact(header)
1299
1299
1300 def interact(self, banner=None):
1300 def interact(self, banner=None):
1301 """Closely emulate the interactive Python console.
1301 """Closely emulate the interactive Python console.
1302
1302
1303 The optional banner argument specify the banner to print
1303 The optional banner argument specify the banner to print
1304 before the first interaction; by default it prints a banner
1304 before the first interaction; by default it prints a banner
1305 similar to the one printed by the real Python interpreter,
1305 similar to the one printed by the real Python interpreter,
1306 followed by the current class name in parentheses (so as not
1306 followed by the current class name in parentheses (so as not
1307 to confuse this with the real interpreter -- since it's so
1307 to confuse this with the real interpreter -- since it's so
1308 close!).
1308 close!).
1309
1309
1310 """
1310 """
1311 cprt = 'Type "copyright", "credits" or "license" for more information.'
1311 cprt = 'Type "copyright", "credits" or "license" for more information.'
1312 if banner is None:
1312 if banner is None:
1313 self.write("Python %s on %s\n%s\n(%s)\n" %
1313 self.write("Python %s on %s\n%s\n(%s)\n" %
1314 (sys.version, sys.platform, cprt,
1314 (sys.version, sys.platform, cprt,
1315 self.__class__.__name__))
1315 self.__class__.__name__))
1316 else:
1316 else:
1317 self.write(banner)
1317 self.write(banner)
1318
1318
1319 more = 0
1319 more = 0
1320
1320
1321 # Mark activity in the builtins
1321 # Mark activity in the builtins
1322 __builtin__.__dict__['__IPYTHON__active'] += 1
1322 __builtin__.__dict__['__IPYTHON__active'] += 1
1323
1323
1324 # exit_now is set by a call to %Exit or %Quit
1324 # exit_now is set by a call to %Exit or %Quit
1325 while not self.exit_now:
1325 while not self.exit_now:
1326 try:
1326 try:
1327 if more:
1327 if more:
1328 prompt = self.outputcache.prompt2
1328 prompt = self.outputcache.prompt2
1329 if self.autoindent:
1329 if self.autoindent:
1330 self.readline_startup_hook(self.pre_readline)
1330 self.readline_startup_hook(self.pre_readline)
1331 else:
1331 else:
1332 prompt = self.outputcache.prompt1
1332 prompt = self.outputcache.prompt1
1333 try:
1333 try:
1334 line = self.raw_input(prompt,more)
1334 line = self.raw_input(prompt,more)
1335 if self.autoindent:
1335 if self.autoindent:
1336 self.readline_startup_hook(None)
1336 self.readline_startup_hook(None)
1337 except EOFError:
1337 except EOFError:
1338 if self.autoindent:
1338 if self.autoindent:
1339 self.readline_startup_hook(None)
1339 self.readline_startup_hook(None)
1340 self.write("\n")
1340 self.write("\n")
1341 self.exit()
1341 self.exit()
1342 else:
1342 else:
1343 more = self.push(line)
1343 more = self.push(line)
1344
1344
1345 if (self.SyntaxTB.last_syntax_error and
1345 if (self.SyntaxTB.last_syntax_error and
1346 self.rc.autoedit_syntax):
1346 self.rc.autoedit_syntax):
1347 self.edit_syntax_error()
1347 self.edit_syntax_error()
1348
1348
1349 except KeyboardInterrupt:
1349 except KeyboardInterrupt:
1350 self.write("\nKeyboardInterrupt\n")
1350 self.write("\nKeyboardInterrupt\n")
1351 self.resetbuffer()
1351 self.resetbuffer()
1352 more = 0
1352 more = 0
1353 # keep cache in sync with the prompt counter:
1353 # keep cache in sync with the prompt counter:
1354 self.outputcache.prompt_count -= 1
1354 self.outputcache.prompt_count -= 1
1355
1355
1356 if self.autoindent:
1356 if self.autoindent:
1357 self.indent_current_nsp = 0
1357 self.indent_current_nsp = 0
1358 self.indent_current = ' '* self.indent_current_nsp
1358 self.indent_current = ' '* self.indent_current_nsp
1359
1359
1360 except bdb.BdbQuit:
1360 except bdb.BdbQuit:
1361 warn("The Python debugger has exited with a BdbQuit exception.\n"
1361 warn("The Python debugger has exited with a BdbQuit exception.\n"
1362 "Because of how pdb handles the stack, it is impossible\n"
1362 "Because of how pdb handles the stack, it is impossible\n"
1363 "for IPython to properly format this particular exception.\n"
1363 "for IPython to properly format this particular exception.\n"
1364 "IPython will resume normal operation.")
1364 "IPython will resume normal operation.")
1365
1365
1366 # We are off again...
1366 # We are off again...
1367 __builtin__.__dict__['__IPYTHON__active'] -= 1
1367 __builtin__.__dict__['__IPYTHON__active'] -= 1
1368
1368
1369 def excepthook(self, type, value, tb):
1369 def excepthook(self, type, value, tb):
1370 """One more defense for GUI apps that call sys.excepthook.
1370 """One more defense for GUI apps that call sys.excepthook.
1371
1371
1372 GUI frameworks like wxPython trap exceptions and call
1372 GUI frameworks like wxPython trap exceptions and call
1373 sys.excepthook themselves. I guess this is a feature that
1373 sys.excepthook themselves. I guess this is a feature that
1374 enables them to keep running after exceptions that would
1374 enables them to keep running after exceptions that would
1375 otherwise kill their mainloop. This is a bother for IPython
1375 otherwise kill their mainloop. This is a bother for IPython
1376 which excepts to catch all of the program exceptions with a try:
1376 which excepts to catch all of the program exceptions with a try:
1377 except: statement.
1377 except: statement.
1378
1378
1379 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1379 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1380 any app directly invokes sys.excepthook, it will look to the user like
1380 any app directly invokes sys.excepthook, it will look to the user like
1381 IPython crashed. In order to work around this, we can disable the
1381 IPython crashed. In order to work around this, we can disable the
1382 CrashHandler and replace it with this excepthook instead, which prints a
1382 CrashHandler and replace it with this excepthook instead, which prints a
1383 regular traceback using our InteractiveTB. In this fashion, apps which
1383 regular traceback using our InteractiveTB. In this fashion, apps which
1384 call sys.excepthook will generate a regular-looking exception from
1384 call sys.excepthook will generate a regular-looking exception from
1385 IPython, and the CrashHandler will only be triggered by real IPython
1385 IPython, and the CrashHandler will only be triggered by real IPython
1386 crashes.
1386 crashes.
1387
1387
1388 This hook should be used sparingly, only in places which are not likely
1388 This hook should be used sparingly, only in places which are not likely
1389 to be true IPython errors.
1389 to be true IPython errors.
1390 """
1390 """
1391
1391
1392 self.InteractiveTB(type, value, tb, tb_offset=0)
1392 self.InteractiveTB(type, value, tb, tb_offset=0)
1393 if self.InteractiveTB.call_pdb and self.has_readline:
1393 if self.InteractiveTB.call_pdb and self.has_readline:
1394 self.readline.set_completer(self.Completer.complete)
1394 self.readline.set_completer(self.Completer.complete)
1395
1395
1396 def call_alias(self,alias,rest=''):
1396 def call_alias(self,alias,rest=''):
1397 """Call an alias given its name and the rest of the line.
1397 """Call an alias given its name and the rest of the line.
1398
1398
1399 This function MUST be given a proper alias, because it doesn't make
1399 This function MUST be given a proper alias, because it doesn't make
1400 any checks when looking up into the alias table. The caller is
1400 any checks when looking up into the alias table. The caller is
1401 responsible for invoking it only with a valid alias."""
1401 responsible for invoking it only with a valid alias."""
1402
1402
1403 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1403 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1404 nargs,cmd = self.alias_table[alias]
1404 nargs,cmd = self.alias_table[alias]
1405 # Expand the %l special to be the user's input line
1405 # Expand the %l special to be the user's input line
1406 if cmd.find('%l') >= 0:
1406 if cmd.find('%l') >= 0:
1407 cmd = cmd.replace('%l',rest)
1407 cmd = cmd.replace('%l',rest)
1408 rest = ''
1408 rest = ''
1409 if nargs==0:
1409 if nargs==0:
1410 # Simple, argument-less aliases
1410 # Simple, argument-less aliases
1411 cmd = '%s %s' % (cmd,rest)
1411 cmd = '%s %s' % (cmd,rest)
1412 else:
1412 else:
1413 # Handle aliases with positional arguments
1413 # Handle aliases with positional arguments
1414 args = rest.split(None,nargs)
1414 args = rest.split(None,nargs)
1415 if len(args)< nargs:
1415 if len(args)< nargs:
1416 error('Alias <%s> requires %s arguments, %s given.' %
1416 error('Alias <%s> requires %s arguments, %s given.' %
1417 (alias,nargs,len(args)))
1417 (alias,nargs,len(args)))
1418 return
1418 return
1419 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1419 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1420 # Now call the macro, evaluating in the user's namespace
1420 # Now call the macro, evaluating in the user's namespace
1421 try:
1421 try:
1422 self.system(cmd)
1422 self.system(cmd)
1423 except:
1423 except:
1424 self.showtraceback()
1424 self.showtraceback()
1425
1425
1426 def autoindent_update(self,line):
1426 def autoindent_update(self,line):
1427 """Keep track of the indent level."""
1427 """Keep track of the indent level."""
1428 if self.autoindent:
1428 if self.autoindent:
1429 if line:
1429 if line:
1430 ini_spaces = ini_spaces_re.match(line)
1430 ini_spaces = ini_spaces_re.match(line)
1431 if ini_spaces:
1431 if ini_spaces:
1432 nspaces = ini_spaces.end()
1432 nspaces = ini_spaces.end()
1433 else:
1433 else:
1434 nspaces = 0
1434 nspaces = 0
1435 self.indent_current_nsp = nspaces
1435 self.indent_current_nsp = nspaces
1436
1436
1437 if line[-1] == ':':
1437 if line[-1] == ':':
1438 self.indent_current_nsp += 4
1438 self.indent_current_nsp += 4
1439 elif dedent_re.match(line):
1439 elif dedent_re.match(line):
1440 self.indent_current_nsp -= 4
1440 self.indent_current_nsp -= 4
1441 else:
1441 else:
1442 self.indent_current_nsp = 0
1442 self.indent_current_nsp = 0
1443
1443
1444 # indent_current is the actual string to be inserted
1444 # indent_current is the actual string to be inserted
1445 # by the readline hooks for indentation
1445 # by the readline hooks for indentation
1446 self.indent_current = ' '* self.indent_current_nsp
1446 self.indent_current = ' '* self.indent_current_nsp
1447
1447
1448 def runlines(self,lines):
1448 def runlines(self,lines):
1449 """Run a string of one or more lines of source.
1449 """Run a string of one or more lines of source.
1450
1450
1451 This method is capable of running a string containing multiple source
1451 This method is capable of running a string containing multiple source
1452 lines, as if they had been entered at the IPython prompt. Since it
1452 lines, as if they had been entered at the IPython prompt. Since it
1453 exposes IPython's processing machinery, the given strings can contain
1453 exposes IPython's processing machinery, the given strings can contain
1454 magic calls (%magic), special shell access (!cmd), etc."""
1454 magic calls (%magic), special shell access (!cmd), etc."""
1455
1455
1456 # We must start with a clean buffer, in case this is run from an
1456 # We must start with a clean buffer, in case this is run from an
1457 # interactive IPython session (via a magic, for example).
1457 # interactive IPython session (via a magic, for example).
1458 self.resetbuffer()
1458 self.resetbuffer()
1459 lines = lines.split('\n')
1459 lines = lines.split('\n')
1460 more = 0
1460 more = 0
1461 for line in lines:
1461 for line in lines:
1462 # skip blank lines so we don't mess up the prompt counter, but do
1462 # skip blank lines so we don't mess up the prompt counter, but do
1463 # NOT skip even a blank line if we are in a code block (more is
1463 # NOT skip even a blank line if we are in a code block (more is
1464 # true)
1464 # true)
1465 if line or more:
1465 if line or more:
1466 more = self.push(self.prefilter(line,more))
1466 more = self.push(self.prefilter(line,more))
1467 # IPython's runsource returns None if there was an error
1467 # IPython's runsource returns None if there was an error
1468 # compiling the code. This allows us to stop processing right
1468 # compiling the code. This allows us to stop processing right
1469 # away, so the user gets the error message at the right place.
1469 # away, so the user gets the error message at the right place.
1470 if more is None:
1470 if more is None:
1471 break
1471 break
1472 # final newline in case the input didn't have it, so that the code
1472 # final newline in case the input didn't have it, so that the code
1473 # actually does get executed
1473 # actually does get executed
1474 if more:
1474 if more:
1475 self.push('\n')
1475 self.push('\n')
1476
1476
1477 def runsource(self, source, filename='<input>', symbol='single'):
1477 def runsource(self, source, filename='<input>', symbol='single'):
1478 """Compile and run some source in the interpreter.
1478 """Compile and run some source in the interpreter.
1479
1479
1480 Arguments are as for compile_command().
1480 Arguments are as for compile_command().
1481
1481
1482 One several things can happen:
1482 One several things can happen:
1483
1483
1484 1) The input is incorrect; compile_command() raised an
1484 1) The input is incorrect; compile_command() raised an
1485 exception (SyntaxError or OverflowError). A syntax traceback
1485 exception (SyntaxError or OverflowError). A syntax traceback
1486 will be printed by calling the showsyntaxerror() method.
1486 will be printed by calling the showsyntaxerror() method.
1487
1487
1488 2) The input is incomplete, and more input is required;
1488 2) The input is incomplete, and more input is required;
1489 compile_command() returned None. Nothing happens.
1489 compile_command() returned None. Nothing happens.
1490
1490
1491 3) The input is complete; compile_command() returned a code
1491 3) The input is complete; compile_command() returned a code
1492 object. The code is executed by calling self.runcode() (which
1492 object. The code is executed by calling self.runcode() (which
1493 also handles run-time exceptions, except for SystemExit).
1493 also handles run-time exceptions, except for SystemExit).
1494
1494
1495 The return value is:
1495 The return value is:
1496
1496
1497 - True in case 2
1497 - True in case 2
1498
1498
1499 - False in the other cases, unless an exception is raised, where
1499 - False in the other cases, unless an exception is raised, where
1500 None is returned instead. This can be used by external callers to
1500 None is returned instead. This can be used by external callers to
1501 know whether to continue feeding input or not.
1501 know whether to continue feeding input or not.
1502
1502
1503 The return value can be used to decide whether to use sys.ps1 or
1503 The return value can be used to decide whether to use sys.ps1 or
1504 sys.ps2 to prompt the next line."""
1504 sys.ps2 to prompt the next line."""
1505
1505
1506 try:
1506 try:
1507 code = self.compile(source,filename,symbol)
1507 code = self.compile(source,filename,symbol)
1508 except (OverflowError, SyntaxError, ValueError):
1508 except (OverflowError, SyntaxError, ValueError):
1509 # Case 1
1509 # Case 1
1510 self.showsyntaxerror(filename)
1510 self.showsyntaxerror(filename)
1511 return None
1511 return None
1512
1512
1513 if code is None:
1513 if code is None:
1514 # Case 2
1514 # Case 2
1515 return True
1515 return True
1516
1516
1517 # Case 3
1517 # Case 3
1518 # We store the code object so that threaded shells and
1518 # We store the code object so that threaded shells and
1519 # custom exception handlers can access all this info if needed.
1519 # custom exception handlers can access all this info if needed.
1520 # The source corresponding to this can be obtained from the
1520 # The source corresponding to this can be obtained from the
1521 # buffer attribute as '\n'.join(self.buffer).
1521 # buffer attribute as '\n'.join(self.buffer).
1522 self.code_to_run = code
1522 self.code_to_run = code
1523 # now actually execute the code object
1523 # now actually execute the code object
1524 if self.runcode(code) == 0:
1524 if self.runcode(code) == 0:
1525 return False
1525 return False
1526 else:
1526 else:
1527 return None
1527 return None
1528
1528
1529 def runcode(self,code_obj):
1529 def runcode(self,code_obj):
1530 """Execute a code object.
1530 """Execute a code object.
1531
1531
1532 When an exception occurs, self.showtraceback() is called to display a
1532 When an exception occurs, self.showtraceback() is called to display a
1533 traceback.
1533 traceback.
1534
1534
1535 Return value: a flag indicating whether the code to be run completed
1535 Return value: a flag indicating whether the code to be run completed
1536 successfully:
1536 successfully:
1537
1537
1538 - 0: successful execution.
1538 - 0: successful execution.
1539 - 1: an error occurred.
1539 - 1: an error occurred.
1540 """
1540 """
1541
1541
1542 # Set our own excepthook in case the user code tries to call it
1542 # Set our own excepthook in case the user code tries to call it
1543 # directly, so that the IPython crash handler doesn't get triggered
1543 # directly, so that the IPython crash handler doesn't get triggered
1544 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1544 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1545
1545
1546 # we save the original sys.excepthook in the instance, in case config
1546 # we save the original sys.excepthook in the instance, in case config
1547 # code (such as magics) needs access to it.
1547 # code (such as magics) needs access to it.
1548 self.sys_excepthook = old_excepthook
1548 self.sys_excepthook = old_excepthook
1549 outflag = 1 # happens in more places, so it's easier as default
1549 outflag = 1 # happens in more places, so it's easier as default
1550 try:
1550 try:
1551 try:
1551 try:
1552 # Embedded instances require separate global/local namespaces
1552 # Embedded instances require separate global/local namespaces
1553 # so they can see both the surrounding (local) namespace and
1553 # so they can see both the surrounding (local) namespace and
1554 # the module-level globals when called inside another function.
1554 # the module-level globals when called inside another function.
1555 if self.embedded:
1555 if self.embedded:
1556 exec code_obj in self.user_global_ns, self.user_ns
1556 exec code_obj in self.user_global_ns, self.user_ns
1557 # Normal (non-embedded) instances should only have a single
1557 # Normal (non-embedded) instances should only have a single
1558 # namespace for user code execution, otherwise functions won't
1558 # namespace for user code execution, otherwise functions won't
1559 # see interactive top-level globals.
1559 # see interactive top-level globals.
1560 else:
1560 else:
1561 exec code_obj in self.user_ns
1561 exec code_obj in self.user_ns
1562 finally:
1562 finally:
1563 # Reset our crash handler in place
1563 # Reset our crash handler in place
1564 sys.excepthook = old_excepthook
1564 sys.excepthook = old_excepthook
1565 except SystemExit:
1565 except SystemExit:
1566 self.resetbuffer()
1566 self.resetbuffer()
1567 self.showtraceback()
1567 self.showtraceback()
1568 warn("Type exit or quit to exit IPython "
1568 warn("Type exit or quit to exit IPython "
1569 "(%Exit or %Quit do so unconditionally).",level=1)
1569 "(%Exit or %Quit do so unconditionally).",level=1)
1570 except self.custom_exceptions:
1570 except self.custom_exceptions:
1571 etype,value,tb = sys.exc_info()
1571 etype,value,tb = sys.exc_info()
1572 self.CustomTB(etype,value,tb)
1572 self.CustomTB(etype,value,tb)
1573 except:
1573 except:
1574 self.showtraceback()
1574 self.showtraceback()
1575 else:
1575 else:
1576 outflag = 0
1576 outflag = 0
1577 if softspace(sys.stdout, 0):
1577 if softspace(sys.stdout, 0):
1578 print
1578 print
1579 # Flush out code object which has been run (and source)
1579 # Flush out code object which has been run (and source)
1580 self.code_to_run = None
1580 self.code_to_run = None
1581 return outflag
1581 return outflag
1582
1582
1583 def push(self, line):
1583 def push(self, line):
1584 """Push a line to the interpreter.
1584 """Push a line to the interpreter.
1585
1585
1586 The line should not have a trailing newline; it may have
1586 The line should not have a trailing newline; it may have
1587 internal newlines. The line is appended to a buffer and the
1587 internal newlines. The line is appended to a buffer and the
1588 interpreter's runsource() method is called with the
1588 interpreter's runsource() method is called with the
1589 concatenated contents of the buffer as source. If this
1589 concatenated contents of the buffer as source. If this
1590 indicates that the command was executed or invalid, the buffer
1590 indicates that the command was executed or invalid, the buffer
1591 is reset; otherwise, the command is incomplete, and the buffer
1591 is reset; otherwise, the command is incomplete, and the buffer
1592 is left as it was after the line was appended. The return
1592 is left as it was after the line was appended. The return
1593 value is 1 if more input is required, 0 if the line was dealt
1593 value is 1 if more input is required, 0 if the line was dealt
1594 with in some way (this is the same as runsource()).
1594 with in some way (this is the same as runsource()).
1595 """
1595 """
1596
1596
1597 # autoindent management should be done here, and not in the
1597 # autoindent management should be done here, and not in the
1598 # interactive loop, since that one is only seen by keyboard input. We
1598 # interactive loop, since that one is only seen by keyboard input. We
1599 # need this done correctly even for code run via runlines (which uses
1599 # need this done correctly even for code run via runlines (which uses
1600 # push).
1600 # push).
1601
1601
1602 print 'push line: <%s>' % line # dbg
1602 #print 'push line: <%s>' % line # dbg
1603 self.autoindent_update(line)
1603 self.autoindent_update(line)
1604
1604
1605 self.buffer.append(line)
1605 self.buffer.append(line)
1606 more = self.runsource('\n'.join(self.buffer), self.filename)
1606 more = self.runsource('\n'.join(self.buffer), self.filename)
1607 if not more:
1607 if not more:
1608 self.resetbuffer()
1608 self.resetbuffer()
1609 return more
1609 return more
1610
1610
1611 def resetbuffer(self):
1611 def resetbuffer(self):
1612 """Reset the input buffer."""
1612 """Reset the input buffer."""
1613 self.buffer[:] = []
1613 self.buffer[:] = []
1614
1614
1615 def raw_input(self,prompt='',continue_prompt=False):
1615 def raw_input(self,prompt='',continue_prompt=False):
1616 """Write a prompt and read a line.
1616 """Write a prompt and read a line.
1617
1617
1618 The returned line does not include the trailing newline.
1618 The returned line does not include the trailing newline.
1619 When the user enters the EOF key sequence, EOFError is raised.
1619 When the user enters the EOF key sequence, EOFError is raised.
1620
1620
1621 Optional inputs:
1621 Optional inputs:
1622
1622
1623 - prompt(''): a string to be printed to prompt the user.
1623 - prompt(''): a string to be printed to prompt the user.
1624
1624
1625 - continue_prompt(False): whether this line is the first one or a
1625 - continue_prompt(False): whether this line is the first one or a
1626 continuation in a sequence of inputs.
1626 continuation in a sequence of inputs.
1627 """
1627 """
1628
1628
1629 line = raw_input_original(prompt)
1629 line = raw_input_original(prompt)
1630 # Try to be reasonably smart about not re-indenting pasted input more
1630 # Try to be reasonably smart about not re-indenting pasted input more
1631 # than necessary. We do this by trimming out the auto-indent initial
1631 # than necessary. We do this by trimming out the auto-indent initial
1632 # spaces, if the user's actual input started itself with whitespace.
1632 # spaces, if the user's actual input started itself with whitespace.
1633 if self.autoindent:
1633 if self.autoindent:
1634 line2 = line[self.indent_current_nsp:]
1634 line2 = line[self.indent_current_nsp:]
1635 if line2[0:1] in (' ','\t'):
1635 if line2[0:1] in (' ','\t'):
1636 line = line2
1636 line = line2
1637 return self.prefilter(line,continue_prompt)
1637 return self.prefilter(line,continue_prompt)
1638
1638
1639 def split_user_input(self,line):
1639 def split_user_input(self,line):
1640 """Split user input into pre-char, function part and rest."""
1640 """Split user input into pre-char, function part and rest."""
1641
1641
1642 lsplit = self.line_split.match(line)
1642 lsplit = self.line_split.match(line)
1643 if lsplit is None: # no regexp match returns None
1643 if lsplit is None: # no regexp match returns None
1644 try:
1644 try:
1645 iFun,theRest = line.split(None,1)
1645 iFun,theRest = line.split(None,1)
1646 except ValueError:
1646 except ValueError:
1647 iFun,theRest = line,''
1647 iFun,theRest = line,''
1648 pre = re.match('^(\s*)(.*)',line).groups()[0]
1648 pre = re.match('^(\s*)(.*)',line).groups()[0]
1649 else:
1649 else:
1650 pre,iFun,theRest = lsplit.groups()
1650 pre,iFun,theRest = lsplit.groups()
1651
1651
1652 #print 'line:<%s>' % line # dbg
1652 #print 'line:<%s>' % line # dbg
1653 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1653 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1654 return pre,iFun.strip(),theRest
1654 return pre,iFun.strip(),theRest
1655
1655
1656 def _prefilter(self, line, continue_prompt):
1656 def _prefilter(self, line, continue_prompt):
1657 """Calls different preprocessors, depending on the form of line."""
1657 """Calls different preprocessors, depending on the form of line."""
1658
1658
1659 # All handlers *must* return a value, even if it's blank ('').
1659 # All handlers *must* return a value, even if it's blank ('').
1660
1660
1661 # Lines are NOT logged here. Handlers should process the line as
1661 # Lines are NOT logged here. Handlers should process the line as
1662 # needed, update the cache AND log it (so that the input cache array
1662 # needed, update the cache AND log it (so that the input cache array
1663 # stays synced).
1663 # stays synced).
1664
1664
1665 # This function is _very_ delicate, and since it's also the one which
1665 # This function is _very_ delicate, and since it's also the one which
1666 # determines IPython's response to user input, it must be as efficient
1666 # determines IPython's response to user input, it must be as efficient
1667 # as possible. For this reason it has _many_ returns in it, trying
1667 # as possible. For this reason it has _many_ returns in it, trying
1668 # always to exit as quickly as it can figure out what it needs to do.
1668 # always to exit as quickly as it can figure out what it needs to do.
1669
1669
1670 # This function is the main responsible for maintaining IPython's
1670 # This function is the main responsible for maintaining IPython's
1671 # behavior respectful of Python's semantics. So be _very_ careful if
1671 # behavior respectful of Python's semantics. So be _very_ careful if
1672 # making changes to anything here.
1672 # making changes to anything here.
1673
1673
1674 #.....................................................................
1674 #.....................................................................
1675 # Code begins
1675 # Code begins
1676
1676
1677 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1677 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1678
1678
1679 # save the line away in case we crash, so the post-mortem handler can
1679 # save the line away in case we crash, so the post-mortem handler can
1680 # record it
1680 # record it
1681 self._last_input_line = line
1681 self._last_input_line = line
1682
1682
1683 #print '***line: <%s>' % line # dbg
1683 #print '***line: <%s>' % line # dbg
1684
1684
1685 # the input history needs to track even empty lines
1685 # the input history needs to track even empty lines
1686 if not line.strip():
1686 if not line.strip():
1687 if not continue_prompt:
1687 if not continue_prompt:
1688 self.outputcache.prompt_count -= 1
1688 self.outputcache.prompt_count -= 1
1689 return self.handle_normal(line,continue_prompt)
1689 return self.handle_normal(line,continue_prompt)
1690 #return self.handle_normal('',continue_prompt)
1690 #return self.handle_normal('',continue_prompt)
1691
1691
1692 # print '***cont',continue_prompt # dbg
1692 # print '***cont',continue_prompt # dbg
1693 # special handlers are only allowed for single line statements
1693 # special handlers are only allowed for single line statements
1694 if continue_prompt and not self.rc.multi_line_specials:
1694 if continue_prompt and not self.rc.multi_line_specials:
1695 return self.handle_normal(line,continue_prompt)
1695 return self.handle_normal(line,continue_prompt)
1696
1696
1697 # For the rest, we need the structure of the input
1697 # For the rest, we need the structure of the input
1698 pre,iFun,theRest = self.split_user_input(line)
1698 pre,iFun,theRest = self.split_user_input(line)
1699 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1699 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1700
1700
1701 # First check for explicit escapes in the last/first character
1701 # First check for explicit escapes in the last/first character
1702 handler = None
1702 handler = None
1703 if line[-1] == self.ESC_HELP:
1703 if line[-1] == self.ESC_HELP:
1704 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1704 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1705 if handler is None:
1705 if handler is None:
1706 # look at the first character of iFun, NOT of line, so we skip
1706 # look at the first character of iFun, NOT of line, so we skip
1707 # leading whitespace in multiline input
1707 # leading whitespace in multiline input
1708 handler = self.esc_handlers.get(iFun[0:1])
1708 handler = self.esc_handlers.get(iFun[0:1])
1709 if handler is not None:
1709 if handler is not None:
1710 return handler(line,continue_prompt,pre,iFun,theRest)
1710 return handler(line,continue_prompt,pre,iFun,theRest)
1711 # Emacs ipython-mode tags certain input lines
1711 # Emacs ipython-mode tags certain input lines
1712 if line.endswith('# PYTHON-MODE'):
1712 if line.endswith('# PYTHON-MODE'):
1713 return self.handle_emacs(line,continue_prompt)
1713 return self.handle_emacs(line,continue_prompt)
1714
1714
1715 # Next, check if we can automatically execute this thing
1715 # Next, check if we can automatically execute this thing
1716
1716
1717 # Allow ! in multi-line statements if multi_line_specials is on:
1717 # Allow ! in multi-line statements if multi_line_specials is on:
1718 if continue_prompt and self.rc.multi_line_specials and \
1718 if continue_prompt and self.rc.multi_line_specials and \
1719 iFun.startswith(self.ESC_SHELL):
1719 iFun.startswith(self.ESC_SHELL):
1720 return self.handle_shell_escape(line,continue_prompt,
1720 return self.handle_shell_escape(line,continue_prompt,
1721 pre=pre,iFun=iFun,
1721 pre=pre,iFun=iFun,
1722 theRest=theRest)
1722 theRest=theRest)
1723
1723
1724 # Let's try to find if the input line is a magic fn
1724 # Let's try to find if the input line is a magic fn
1725 oinfo = None
1725 oinfo = None
1726 if hasattr(self,'magic_'+iFun):
1726 if hasattr(self,'magic_'+iFun):
1727 # WARNING: _ofind uses getattr(), so it can consume generators and
1727 # WARNING: _ofind uses getattr(), so it can consume generators and
1728 # cause other side effects.
1728 # cause other side effects.
1729 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1729 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1730 if oinfo['ismagic']:
1730 if oinfo['ismagic']:
1731 # Be careful not to call magics when a variable assignment is
1731 # Be careful not to call magics when a variable assignment is
1732 # being made (ls='hi', for example)
1732 # being made (ls='hi', for example)
1733 if self.rc.automagic and \
1733 if self.rc.automagic and \
1734 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1734 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1735 (self.rc.multi_line_specials or not continue_prompt):
1735 (self.rc.multi_line_specials or not continue_prompt):
1736 return self.handle_magic(line,continue_prompt,
1736 return self.handle_magic(line,continue_prompt,
1737 pre,iFun,theRest)
1737 pre,iFun,theRest)
1738 else:
1738 else:
1739 return self.handle_normal(line,continue_prompt)
1739 return self.handle_normal(line,continue_prompt)
1740
1740
1741 # If the rest of the line begins with an (in)equality, assginment or
1741 # If the rest of the line begins with an (in)equality, assginment or
1742 # function call, we should not call _ofind but simply execute it.
1742 # function call, we should not call _ofind but simply execute it.
1743 # This avoids spurious geattr() accesses on objects upon assignment.
1743 # This avoids spurious geattr() accesses on objects upon assignment.
1744 #
1744 #
1745 # It also allows users to assign to either alias or magic names true
1745 # It also allows users to assign to either alias or magic names true
1746 # python variables (the magic/alias systems always take second seat to
1746 # python variables (the magic/alias systems always take second seat to
1747 # true python code).
1747 # true python code).
1748 if theRest and theRest[0] in '!=()':
1748 if theRest and theRest[0] in '!=()':
1749 return self.handle_normal(line,continue_prompt)
1749 return self.handle_normal(line,continue_prompt)
1750
1750
1751 if oinfo is None:
1751 if oinfo is None:
1752 # let's try to ensure that _oinfo is ONLY called when autocall is
1752 # let's try to ensure that _oinfo is ONLY called when autocall is
1753 # on. Since it has inevitable potential side effects, at least
1753 # on. Since it has inevitable potential side effects, at least
1754 # having autocall off should be a guarantee to the user that no
1754 # having autocall off should be a guarantee to the user that no
1755 # weird things will happen.
1755 # weird things will happen.
1756
1756
1757 if self.rc.autocall:
1757 if self.rc.autocall:
1758 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1758 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1759 else:
1759 else:
1760 # in this case, all that's left is either an alias or
1760 # in this case, all that's left is either an alias or
1761 # processing the line normally.
1761 # processing the line normally.
1762 if iFun in self.alias_table:
1762 if iFun in self.alias_table:
1763 return self.handle_alias(line,continue_prompt,
1763 return self.handle_alias(line,continue_prompt,
1764 pre,iFun,theRest)
1764 pre,iFun,theRest)
1765 else:
1765 else:
1766 return self.handle_normal(line,continue_prompt)
1766 return self.handle_normal(line,continue_prompt)
1767
1767
1768 if not oinfo['found']:
1768 if not oinfo['found']:
1769 return self.handle_normal(line,continue_prompt)
1769 return self.handle_normal(line,continue_prompt)
1770 else:
1770 else:
1771 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1771 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1772 if oinfo['isalias']:
1772 if oinfo['isalias']:
1773 return self.handle_alias(line,continue_prompt,
1773 return self.handle_alias(line,continue_prompt,
1774 pre,iFun,theRest)
1774 pre,iFun,theRest)
1775
1775
1776 if self.rc.autocall and \
1776 if self.rc.autocall and \
1777 not self.re_exclude_auto.match(theRest) and \
1777 not self.re_exclude_auto.match(theRest) and \
1778 self.re_fun_name.match(iFun) and \
1778 self.re_fun_name.match(iFun) and \
1779 callable(oinfo['obj']) :
1779 callable(oinfo['obj']) :
1780 #print 'going auto' # dbg
1780 #print 'going auto' # dbg
1781 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1781 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1782 else:
1782 else:
1783 #print 'was callable?', callable(oinfo['obj']) # dbg
1783 #print 'was callable?', callable(oinfo['obj']) # dbg
1784 return self.handle_normal(line,continue_prompt)
1784 return self.handle_normal(line,continue_prompt)
1785
1785
1786 # If we get here, we have a normal Python line. Log and return.
1786 # If we get here, we have a normal Python line. Log and return.
1787 return self.handle_normal(line,continue_prompt)
1787 return self.handle_normal(line,continue_prompt)
1788
1788
1789 def _prefilter_dumb(self, line, continue_prompt):
1789 def _prefilter_dumb(self, line, continue_prompt):
1790 """simple prefilter function, for debugging"""
1790 """simple prefilter function, for debugging"""
1791 return self.handle_normal(line,continue_prompt)
1791 return self.handle_normal(line,continue_prompt)
1792
1792
1793 # Set the default prefilter() function (this can be user-overridden)
1793 # Set the default prefilter() function (this can be user-overridden)
1794 prefilter = _prefilter
1794 prefilter = _prefilter
1795
1795
1796 def handle_normal(self,line,continue_prompt=None,
1796 def handle_normal(self,line,continue_prompt=None,
1797 pre=None,iFun=None,theRest=None):
1797 pre=None,iFun=None,theRest=None):
1798 """Handle normal input lines. Use as a template for handlers."""
1798 """Handle normal input lines. Use as a template for handlers."""
1799
1799
1800 # With autoindent on, we need some way to exit the input loop, and I
1800 # With autoindent on, we need some way to exit the input loop, and I
1801 # don't want to force the user to have to backspace all the way to
1801 # don't want to force the user to have to backspace all the way to
1802 # clear the line. The rule will be in this case, that either two
1802 # clear the line. The rule will be in this case, that either two
1803 # lines of pure whitespace in a row, or a line of pure whitespace but
1803 # lines of pure whitespace in a row, or a line of pure whitespace but
1804 # of a size different to the indent level, will exit the input loop.
1804 # of a size different to the indent level, will exit the input loop.
1805
1805
1806 if (continue_prompt and self.autoindent and isspace(line) and
1806 if (continue_prompt and self.autoindent and isspace(line) and
1807 (line != self.indent_current or isspace(self.buffer[-1]))):
1807 (line != self.indent_current or isspace(self.buffer[-1]))):
1808 line = ''
1808 line = ''
1809
1809
1810 self.log(line,continue_prompt)
1810 self.log(line,continue_prompt)
1811 return line
1811 return line
1812
1812
1813 def handle_alias(self,line,continue_prompt=None,
1813 def handle_alias(self,line,continue_prompt=None,
1814 pre=None,iFun=None,theRest=None):
1814 pre=None,iFun=None,theRest=None):
1815 """Handle alias input lines. """
1815 """Handle alias input lines. """
1816
1816
1817 # pre is needed, because it carries the leading whitespace. Otherwise
1817 # pre is needed, because it carries the leading whitespace. Otherwise
1818 # aliases won't work in indented sections.
1818 # aliases won't work in indented sections.
1819 line_out = '%sipalias("%s %s")' % (pre,iFun,esc_quotes(theRest))
1819 line_out = '%sipalias("%s %s")' % (pre,iFun,esc_quotes(theRest))
1820 self.log(line_out,continue_prompt)
1820 self.log(line_out,continue_prompt)
1821 return line_out
1821 return line_out
1822
1822
1823 def handle_shell_escape(self, line, continue_prompt=None,
1823 def handle_shell_escape(self, line, continue_prompt=None,
1824 pre=None,iFun=None,theRest=None):
1824 pre=None,iFun=None,theRest=None):
1825 """Execute the line in a shell, empty return value"""
1825 """Execute the line in a shell, empty return value"""
1826
1826
1827 #print 'line in :', `line` # dbg
1827 #print 'line in :', `line` # dbg
1828 # Example of a special handler. Others follow a similar pattern.
1828 # Example of a special handler. Others follow a similar pattern.
1829 if continue_prompt: # multi-line statements
1829 if continue_prompt: # multi-line statements
1830 if iFun.startswith('!!'):
1830 if iFun.startswith('!!'):
1831 print 'SyntaxError: !! is not allowed in multiline statements'
1831 print 'SyntaxError: !! is not allowed in multiline statements'
1832 return pre
1832 return pre
1833 else:
1833 else:
1834 cmd = ("%s %s" % (iFun[1:],theRest))
1834 cmd = ("%s %s" % (iFun[1:],theRest))
1835 line_out = '%sipsystem(r"""%s"""[:-1])' % (pre,cmd + "_")
1835 line_out = '%sipsystem(r"""%s"""[:-1])' % (pre,cmd + "_")
1836 else: # single-line input
1836 else: # single-line input
1837 if line.startswith('!!'):
1837 if line.startswith('!!'):
1838 # rewrite iFun/theRest to properly hold the call to %sx and
1838 # rewrite iFun/theRest to properly hold the call to %sx and
1839 # the actual command to be executed, so handle_magic can work
1839 # the actual command to be executed, so handle_magic can work
1840 # correctly
1840 # correctly
1841 theRest = '%s %s' % (iFun[2:],theRest)
1841 theRest = '%s %s' % (iFun[2:],theRest)
1842 iFun = 'sx'
1842 iFun = 'sx'
1843 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1843 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1844 continue_prompt,pre,iFun,theRest)
1844 continue_prompt,pre,iFun,theRest)
1845 else:
1845 else:
1846 cmd=line[1:]
1846 cmd=line[1:]
1847 line_out = '%sipsystem(r"""%s"""[:-1])' % (pre,cmd +"_")
1847 line_out = '%sipsystem(r"""%s"""[:-1])' % (pre,cmd +"_")
1848 # update cache/log and return
1848 # update cache/log and return
1849 self.log(line_out,continue_prompt)
1849 self.log(line_out,continue_prompt)
1850 return line_out
1850 return line_out
1851
1851
1852 def handle_magic(self, line, continue_prompt=None,
1852 def handle_magic(self, line, continue_prompt=None,
1853 pre=None,iFun=None,theRest=None):
1853 pre=None,iFun=None,theRest=None):
1854 """Execute magic functions.
1854 """Execute magic functions.
1855
1855
1856 Also log them with a prepended # so the log is clean Python."""
1856 Also log them with a prepended # so the log is clean Python."""
1857
1857
1858 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1858 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1859 self.log(cmd,continue_prompt)
1859 self.log(cmd,continue_prompt)
1860 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1860 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1861 return cmd
1861 return cmd
1862
1862
1863 def handle_auto(self, line, continue_prompt=None,
1863 def handle_auto(self, line, continue_prompt=None,
1864 pre=None,iFun=None,theRest=None):
1864 pre=None,iFun=None,theRest=None):
1865 """Hande lines which can be auto-executed, quoting if requested."""
1865 """Hande lines which can be auto-executed, quoting if requested."""
1866
1866
1867 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1867 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1868
1868
1869 # This should only be active for single-line input!
1869 # This should only be active for single-line input!
1870 if continue_prompt:
1870 if continue_prompt:
1871 return line
1871 return line
1872
1872
1873 if pre == self.ESC_QUOTE:
1873 if pre == self.ESC_QUOTE:
1874 # Auto-quote splitting on whitespace
1874 # Auto-quote splitting on whitespace
1875 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1875 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1876 elif pre == self.ESC_QUOTE2:
1876 elif pre == self.ESC_QUOTE2:
1877 # Auto-quote whole string
1877 # Auto-quote whole string
1878 newcmd = '%s("%s")' % (iFun,theRest)
1878 newcmd = '%s("%s")' % (iFun,theRest)
1879 else:
1879 else:
1880 # Auto-paren
1880 # Auto-paren
1881 if theRest[0:1] in ('=','['):
1881 if theRest[0:1] in ('=','['):
1882 # Don't autocall in these cases. They can be either
1882 # Don't autocall in these cases. They can be either
1883 # rebindings of an existing callable's name, or item access
1883 # rebindings of an existing callable's name, or item access
1884 # for an object which is BOTH callable and implements
1884 # for an object which is BOTH callable and implements
1885 # __getitem__.
1885 # __getitem__.
1886 return '%s %s' % (iFun,theRest)
1886 return '%s %s' % (iFun,theRest)
1887 if theRest.endswith(';'):
1887 if theRest.endswith(';'):
1888 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1888 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1889 else:
1889 else:
1890 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1890 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1891
1891
1892 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1892 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1893 # log what is now valid Python, not the actual user input (without the
1893 # log what is now valid Python, not the actual user input (without the
1894 # final newline)
1894 # final newline)
1895 self.log(newcmd,continue_prompt)
1895 self.log(newcmd,continue_prompt)
1896 return newcmd
1896 return newcmd
1897
1897
1898 def handle_help(self, line, continue_prompt=None,
1898 def handle_help(self, line, continue_prompt=None,
1899 pre=None,iFun=None,theRest=None):
1899 pre=None,iFun=None,theRest=None):
1900 """Try to get some help for the object.
1900 """Try to get some help for the object.
1901
1901
1902 obj? or ?obj -> basic information.
1902 obj? or ?obj -> basic information.
1903 obj?? or ??obj -> more details.
1903 obj?? or ??obj -> more details.
1904 """
1904 """
1905
1905
1906 # We need to make sure that we don't process lines which would be
1906 # We need to make sure that we don't process lines which would be
1907 # otherwise valid python, such as "x=1 # what?"
1907 # otherwise valid python, such as "x=1 # what?"
1908 try:
1908 try:
1909 codeop.compile_command(line)
1909 codeop.compile_command(line)
1910 except SyntaxError:
1910 except SyntaxError:
1911 # We should only handle as help stuff which is NOT valid syntax
1911 # We should only handle as help stuff which is NOT valid syntax
1912 if line[0]==self.ESC_HELP:
1912 if line[0]==self.ESC_HELP:
1913 line = line[1:]
1913 line = line[1:]
1914 elif line[-1]==self.ESC_HELP:
1914 elif line[-1]==self.ESC_HELP:
1915 line = line[:-1]
1915 line = line[:-1]
1916 self.log('#?'+line)
1916 self.log('#?'+line)
1917 if line:
1917 if line:
1918 self.magic_pinfo(line)
1918 self.magic_pinfo(line)
1919 else:
1919 else:
1920 page(self.usage,screen_lines=self.rc.screen_length)
1920 page(self.usage,screen_lines=self.rc.screen_length)
1921 return '' # Empty string is needed here!
1921 return '' # Empty string is needed here!
1922 except:
1922 except:
1923 # Pass any other exceptions through to the normal handler
1923 # Pass any other exceptions through to the normal handler
1924 return self.handle_normal(line,continue_prompt)
1924 return self.handle_normal(line,continue_prompt)
1925 else:
1925 else:
1926 # If the code compiles ok, we should handle it normally
1926 # If the code compiles ok, we should handle it normally
1927 return self.handle_normal(line,continue_prompt)
1927 return self.handle_normal(line,continue_prompt)
1928
1928
1929 def handle_emacs(self,line,continue_prompt=None,
1929 def handle_emacs(self,line,continue_prompt=None,
1930 pre=None,iFun=None,theRest=None):
1930 pre=None,iFun=None,theRest=None):
1931 """Handle input lines marked by python-mode."""
1931 """Handle input lines marked by python-mode."""
1932
1932
1933 # Currently, nothing is done. Later more functionality can be added
1933 # Currently, nothing is done. Later more functionality can be added
1934 # here if needed.
1934 # here if needed.
1935
1935
1936 # The input cache shouldn't be updated
1936 # The input cache shouldn't be updated
1937
1937
1938 return line
1938 return line
1939
1939
1940 def write(self,data):
1940 def write(self,data):
1941 """Write a string to the default output"""
1941 """Write a string to the default output"""
1942 Term.cout.write(data)
1942 Term.cout.write(data)
1943
1943
1944 def write_err(self,data):
1944 def write_err(self,data):
1945 """Write a string to the default error output"""
1945 """Write a string to the default error output"""
1946 Term.cerr.write(data)
1946 Term.cerr.write(data)
1947
1947
1948 def exit(self):
1948 def exit(self):
1949 """Handle interactive exit.
1949 """Handle interactive exit.
1950
1950
1951 This method sets the exit_now attribute."""
1951 This method sets the exit_now attribute."""
1952
1952
1953 if self.rc.confirm_exit:
1953 if self.rc.confirm_exit:
1954 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1954 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1955 self.exit_now = True
1955 self.exit_now = True
1956 else:
1956 else:
1957 self.exit_now = True
1957 self.exit_now = True
1958 return self.exit_now
1958 return self.exit_now
1959
1959
1960 def safe_execfile(self,fname,*where,**kw):
1960 def safe_execfile(self,fname,*where,**kw):
1961 fname = os.path.expanduser(fname)
1961 fname = os.path.expanduser(fname)
1962
1962
1963 # find things also in current directory
1963 # find things also in current directory
1964 dname = os.path.dirname(fname)
1964 dname = os.path.dirname(fname)
1965 if not sys.path.count(dname):
1965 if not sys.path.count(dname):
1966 sys.path.append(dname)
1966 sys.path.append(dname)
1967
1967
1968 try:
1968 try:
1969 xfile = open(fname)
1969 xfile = open(fname)
1970 except:
1970 except:
1971 print >> Term.cerr, \
1971 print >> Term.cerr, \
1972 'Could not open file <%s> for safe execution.' % fname
1972 'Could not open file <%s> for safe execution.' % fname
1973 return None
1973 return None
1974
1974
1975 kw.setdefault('islog',0)
1975 kw.setdefault('islog',0)
1976 kw.setdefault('quiet',1)
1976 kw.setdefault('quiet',1)
1977 kw.setdefault('exit_ignore',0)
1977 kw.setdefault('exit_ignore',0)
1978 first = xfile.readline()
1978 first = xfile.readline()
1979 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
1979 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
1980 xfile.close()
1980 xfile.close()
1981 # line by line execution
1981 # line by line execution
1982 if first.startswith(loghead) or kw['islog']:
1982 if first.startswith(loghead) or kw['islog']:
1983 print 'Loading log file <%s> one line at a time...' % fname
1983 print 'Loading log file <%s> one line at a time...' % fname
1984 if kw['quiet']:
1984 if kw['quiet']:
1985 stdout_save = sys.stdout
1985 stdout_save = sys.stdout
1986 sys.stdout = StringIO.StringIO()
1986 sys.stdout = StringIO.StringIO()
1987 try:
1987 try:
1988 globs,locs = where[0:2]
1988 globs,locs = where[0:2]
1989 except:
1989 except:
1990 try:
1990 try:
1991 globs = locs = where[0]
1991 globs = locs = where[0]
1992 except:
1992 except:
1993 globs = locs = globals()
1993 globs = locs = globals()
1994 badblocks = []
1994 badblocks = []
1995
1995
1996 # we also need to identify indented blocks of code when replaying
1996 # we also need to identify indented blocks of code when replaying
1997 # logs and put them together before passing them to an exec
1997 # logs and put them together before passing them to an exec
1998 # statement. This takes a bit of regexp and look-ahead work in the
1998 # statement. This takes a bit of regexp and look-ahead work in the
1999 # file. It's easiest if we swallow the whole thing in memory
1999 # file. It's easiest if we swallow the whole thing in memory
2000 # first, and manually walk through the lines list moving the
2000 # first, and manually walk through the lines list moving the
2001 # counter ourselves.
2001 # counter ourselves.
2002 indent_re = re.compile('\s+\S')
2002 indent_re = re.compile('\s+\S')
2003 xfile = open(fname)
2003 xfile = open(fname)
2004 filelines = xfile.readlines()
2004 filelines = xfile.readlines()
2005 xfile.close()
2005 xfile.close()
2006 nlines = len(filelines)
2006 nlines = len(filelines)
2007 lnum = 0
2007 lnum = 0
2008 while lnum < nlines:
2008 while lnum < nlines:
2009 line = filelines[lnum]
2009 line = filelines[lnum]
2010 lnum += 1
2010 lnum += 1
2011 # don't re-insert logger status info into cache
2011 # don't re-insert logger status info into cache
2012 if line.startswith('#log#'):
2012 if line.startswith('#log#'):
2013 continue
2013 continue
2014 else:
2014 else:
2015 # build a block of code (maybe a single line) for execution
2015 # build a block of code (maybe a single line) for execution
2016 block = line
2016 block = line
2017 try:
2017 try:
2018 next = filelines[lnum] # lnum has already incremented
2018 next = filelines[lnum] # lnum has already incremented
2019 except:
2019 except:
2020 next = None
2020 next = None
2021 while next and indent_re.match(next):
2021 while next and indent_re.match(next):
2022 block += next
2022 block += next
2023 lnum += 1
2023 lnum += 1
2024 try:
2024 try:
2025 next = filelines[lnum]
2025 next = filelines[lnum]
2026 except:
2026 except:
2027 next = None
2027 next = None
2028 # now execute the block of one or more lines
2028 # now execute the block of one or more lines
2029 try:
2029 try:
2030 exec block in globs,locs
2030 exec block in globs,locs
2031 except SystemExit:
2031 except SystemExit:
2032 pass
2032 pass
2033 except:
2033 except:
2034 badblocks.append(block.rstrip())
2034 badblocks.append(block.rstrip())
2035 if kw['quiet']: # restore stdout
2035 if kw['quiet']: # restore stdout
2036 sys.stdout.close()
2036 sys.stdout.close()
2037 sys.stdout = stdout_save
2037 sys.stdout = stdout_save
2038 print 'Finished replaying log file <%s>' % fname
2038 print 'Finished replaying log file <%s>' % fname
2039 if badblocks:
2039 if badblocks:
2040 print >> sys.stderr, ('\nThe following lines/blocks in file '
2040 print >> sys.stderr, ('\nThe following lines/blocks in file '
2041 '<%s> reported errors:' % fname)
2041 '<%s> reported errors:' % fname)
2042
2042
2043 for badline in badblocks:
2043 for badline in badblocks:
2044 print >> sys.stderr, badline
2044 print >> sys.stderr, badline
2045 else: # regular file execution
2045 else: # regular file execution
2046 try:
2046 try:
2047 execfile(fname,*where)
2047 execfile(fname,*where)
2048 except SyntaxError:
2048 except SyntaxError:
2049 etype,evalue = sys.exc_info()[:2]
2049 etype,evalue = sys.exc_info()[:2]
2050 self.SyntaxTB(etype,evalue,[])
2050 self.SyntaxTB(etype,evalue,[])
2051 warn('Failure executing file: <%s>' % fname)
2051 warn('Failure executing file: <%s>' % fname)
2052 except SystemExit,status:
2052 except SystemExit,status:
2053 if not kw['exit_ignore']:
2053 if not kw['exit_ignore']:
2054 self.InteractiveTB()
2054 self.InteractiveTB()
2055 warn('Failure executing file: <%s>' % fname)
2055 warn('Failure executing file: <%s>' % fname)
2056 except:
2056 except:
2057 self.InteractiveTB()
2057 self.InteractiveTB()
2058 warn('Failure executing file: <%s>' % fname)
2058 warn('Failure executing file: <%s>' % fname)
2059
2059
2060 #************************* end of file <iplib.py> *****************************
2060 #************************* end of file <iplib.py> *****************************
General Comments 0
You need to be logged in to leave comments. Login now