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