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