##// END OF EJS Templates
add .meta namespace for extension writers.
fperez -
Show More

The requested changes are too big and content was truncated. Show full diff

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