##// END OF EJS Templates
- Made the internal crash handler very customizable for end-user apps based...
fptest -
Show More

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

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