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