##// END OF EJS Templates
Added additional logic to InteractiveShell.instance()....
Brian Granger -
Show More
@@ -1,2094 +1,2102 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Main IPython class."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2010 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 from __future__ import with_statement
18 18 from __future__ import absolute_import
19 19
20 20 import __builtin__
21 21 import abc
22 22 import codeop
23 23 import exceptions
24 24 import new
25 25 import os
26 26 import re
27 27 import string
28 28 import sys
29 29 import tempfile
30 30 from contextlib import nested
31 31
32 32 from IPython.core import debugger, oinspect
33 33 from IPython.core import history as ipcorehist
34 34 from IPython.core import prefilter
35 35 from IPython.core import shadowns
36 36 from IPython.core import ultratb
37 37 from IPython.core.alias import AliasManager
38 38 from IPython.core.builtin_trap import BuiltinTrap
39 39 from IPython.config.configurable import Configurable
40 40 from IPython.core.display_trap import DisplayTrap
41 41 from IPython.core.error import UsageError
42 42 from IPython.core.extensions import ExtensionManager
43 43 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
44 44 from IPython.core.inputlist import InputList
45 45 from IPython.core.logger import Logger
46 46 from IPython.core.magic import Magic
47 47 from IPython.core.plugin import PluginManager
48 48 from IPython.core.prefilter import PrefilterManager
49 49 from IPython.core.displayhook import DisplayHook
50 50 import IPython.core.hooks
51 51 from IPython.external.Itpl import ItplNS
52 52 from IPython.utils import PyColorize
53 53 from IPython.utils import pickleshare
54 54 from IPython.utils.doctestreload import doctest_reload
55 55 from IPython.utils.ipstruct import Struct
56 56 import IPython.utils.io
57 57 from IPython.utils.io import ask_yes_no
58 58 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
59 59 from IPython.utils.process import getoutput, getoutputerror
60 60 from IPython.utils.strdispatch import StrDispatch
61 61 from IPython.utils.syspathcontext import prepended_to_syspath
62 62 from IPython.utils.text import num_ini_spaces
63 63 from IPython.utils.warn import warn, error, fatal
64 64 from IPython.utils.traitlets import (
65 65 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode, Instance, Type
66 66 )
67 67
68 68 # from IPython.utils import growl
69 69 # growl.start("IPython")
70 70
71 71 #-----------------------------------------------------------------------------
72 72 # Globals
73 73 #-----------------------------------------------------------------------------
74 74
75 75 # compiled regexps for autoindent management
76 76 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
77 77
78 78 #-----------------------------------------------------------------------------
79 79 # Utilities
80 80 #-----------------------------------------------------------------------------
81 81
82 82 # store the builtin raw_input globally, and use this always, in case user code
83 83 # overwrites it (like wx.py.PyShell does)
84 84 raw_input_original = raw_input
85 85
86 86 def softspace(file, newvalue):
87 87 """Copied from code.py, to remove the dependency"""
88 88
89 89 oldvalue = 0
90 90 try:
91 91 oldvalue = file.softspace
92 92 except AttributeError:
93 93 pass
94 94 try:
95 95 file.softspace = newvalue
96 96 except (AttributeError, TypeError):
97 97 # "attribute-less object" or "read-only attributes"
98 98 pass
99 99 return oldvalue
100 100
101 101
102 102 def no_op(*a, **kw): pass
103 103
104 104 class SpaceInInput(exceptions.Exception): pass
105 105
106 106 class Bunch: pass
107 107
108 108
109 109 def get_default_colors():
110 110 if sys.platform=='darwin':
111 111 return "LightBG"
112 112 elif os.name=='nt':
113 113 return 'Linux'
114 114 else:
115 115 return 'Linux'
116 116
117 117
118 118 class SeparateStr(Str):
119 119 """A Str subclass to validate separate_in, separate_out, etc.
120 120
121 121 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
122 122 """
123 123
124 124 def validate(self, obj, value):
125 125 if value == '0': value = ''
126 126 value = value.replace('\\n','\n')
127 127 return super(SeparateStr, self).validate(obj, value)
128 128
129 129
130 130 #-----------------------------------------------------------------------------
131 131 # Main IPython class
132 132 #-----------------------------------------------------------------------------
133 133
134 134
135 135 class InteractiveShell(Configurable, Magic):
136 136 """An enhanced, interactive shell for Python."""
137 137
138 138 autocall = Enum((0,1,2), default_value=1, config=True)
139 139 # TODO: remove all autoindent logic and put into frontends.
140 140 # We can't do this yet because even runlines uses the autoindent.
141 141 autoindent = CBool(True, config=True)
142 142 automagic = CBool(True, config=True)
143 143 cache_size = Int(1000, config=True)
144 144 color_info = CBool(True, config=True)
145 145 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
146 146 default_value=get_default_colors(), config=True)
147 147 debug = CBool(False, config=True)
148 148 deep_reload = CBool(False, config=True)
149 149 displayhook_class = Type(DisplayHook)
150 150 filename = Str("<ipython console>")
151 151 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
152 152 logstart = CBool(False, config=True)
153 153 logfile = Str('', config=True)
154 154 logappend = Str('', config=True)
155 155 object_info_string_level = Enum((0,1,2), default_value=0,
156 156 config=True)
157 157 pdb = CBool(False, config=True)
158 158 pprint = CBool(True, config=True)
159 159 profile = Str('', config=True)
160 160 prompt_in1 = Str('In [\\#]: ', config=True)
161 161 prompt_in2 = Str(' .\\D.: ', config=True)
162 162 prompt_out = Str('Out[\\#]: ', config=True)
163 163 prompts_pad_left = CBool(True, config=True)
164 164 quiet = CBool(False, config=True)
165 165
166 166 # The readline stuff will eventually be moved to the terminal subclass
167 167 # but for now, we can't do that as readline is welded in everywhere.
168 168 readline_use = CBool(True, config=True)
169 169 readline_merge_completions = CBool(True, config=True)
170 170 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
171 171 readline_remove_delims = Str('-/~', config=True)
172 172 readline_parse_and_bind = List([
173 173 'tab: complete',
174 174 '"\C-l": clear-screen',
175 175 'set show-all-if-ambiguous on',
176 176 '"\C-o": tab-insert',
177 177 '"\M-i": " "',
178 178 '"\M-o": "\d\d\d\d"',
179 179 '"\M-I": "\d\d\d\d"',
180 180 '"\C-r": reverse-search-history',
181 181 '"\C-s": forward-search-history',
182 182 '"\C-p": history-search-backward',
183 183 '"\C-n": history-search-forward',
184 184 '"\e[A": history-search-backward',
185 185 '"\e[B": history-search-forward',
186 186 '"\C-k": kill-line',
187 187 '"\C-u": unix-line-discard',
188 188 ], allow_none=False, config=True)
189 189
190 190 # TODO: this part of prompt management should be moved to the frontends.
191 191 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
192 192 separate_in = SeparateStr('\n', config=True)
193 193 separate_out = SeparateStr('\n', config=True)
194 194 separate_out2 = SeparateStr('\n', config=True)
195 195 system_header = Str('IPython system call: ', config=True)
196 196 system_verbose = CBool(False, config=True)
197 197 wildcards_case_sensitive = CBool(True, config=True)
198 198 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
199 199 default_value='Context', config=True)
200 200
201 201 # Subcomponents of InteractiveShell
202 202 alias_manager = Instance('IPython.core.alias.AliasManager')
203 203 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
204 204 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
205 205 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
206 206 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
207 207 plugin_manager = Instance('IPython.core.plugin.PluginManager')
208 208
209 209 def __init__(self, config=None, ipython_dir=None,
210 210 user_ns=None, user_global_ns=None,
211 211 custom_exceptions=((),None)):
212 212
213 213 # This is where traits with a config_key argument are updated
214 214 # from the values on config.
215 215 super(InteractiveShell, self).__init__(config=config)
216 216
217 217 # These are relatively independent and stateless
218 218 self.init_ipython_dir(ipython_dir)
219 219 self.init_instance_attrs()
220 220
221 221 # Create namespaces (user_ns, user_global_ns, etc.)
222 222 self.init_create_namespaces(user_ns, user_global_ns)
223 223 # This has to be done after init_create_namespaces because it uses
224 224 # something in self.user_ns, but before init_sys_modules, which
225 225 # is the first thing to modify sys.
226 226 self.save_sys_module_state()
227 227 self.init_sys_modules()
228 228
229 229 self.init_history()
230 230 self.init_encoding()
231 231 self.init_prefilter()
232 232
233 233 Magic.__init__(self, self)
234 234
235 235 self.init_syntax_highlighting()
236 236 self.init_hooks()
237 237 self.init_pushd_popd_magic()
238 238 # TODO: init_io() needs to happen before init_traceback handlers
239 239 # because the traceback handlers hardcode the stdout/stderr streams.
240 240 # This logic in in debugger.Pdb and should eventually be changed.
241 241 self.init_io()
242 242 self.init_traceback_handlers(custom_exceptions)
243 243 self.init_user_ns()
244 244 self.init_logger()
245 245 self.init_alias()
246 246 self.init_builtins()
247 247
248 248 # pre_config_initialization
249 249 self.init_shadow_hist()
250 250
251 251 # The next section should contain averything that was in ipmaker.
252 252 self.init_logstart()
253 253
254 254 # The following was in post_config_initialization
255 255 self.init_inspector()
256 256 self.init_readline()
257 257 self.init_prompts()
258 258 self.init_displayhook()
259 259 self.init_reload_doctest()
260 260 self.init_magics()
261 261 self.init_pdb()
262 262 self.init_extension_manager()
263 263 self.init_plugin_manager()
264 264 self.hooks.late_startup_hook()
265 265
266 266 @classmethod
267 267 def instance(cls, *args, **kwargs):
268 268 """Returns a global InteractiveShell instance."""
269 269 if not hasattr(cls, "_instance"):
270 270 cls._instance = cls(*args, **kwargs)
271 print cls
272 print cls._instance
273 # Now make sure that the instance will also be returned by
274 # the subclasses instance attribute.
275 for subclass in cls.mro():
276 if issubclass(subclass, InteractiveShell):
277 print subclass
278 subclass._instance = cls._instance
271 279 return cls._instance
272 280
273 281 @classmethod
274 282 def initialized(cls):
275 283 return hasattr(cls, "_instance")
276 284
277 285 def get_ipython(self):
278 286 """Return the currently running IPython instance."""
279 287 return self
280 288
281 289 #-------------------------------------------------------------------------
282 290 # Trait changed handlers
283 291 #-------------------------------------------------------------------------
284 292
285 293 def _ipython_dir_changed(self, name, new):
286 294 if not os.path.isdir(new):
287 295 os.makedirs(new, mode = 0777)
288 296
289 297 def set_autoindent(self,value=None):
290 298 """Set the autoindent flag, checking for readline support.
291 299
292 300 If called with no arguments, it acts as a toggle."""
293 301
294 302 if not self.has_readline:
295 303 if os.name == 'posix':
296 304 warn("The auto-indent feature requires the readline library")
297 305 self.autoindent = 0
298 306 return
299 307 if value is None:
300 308 self.autoindent = not self.autoindent
301 309 else:
302 310 self.autoindent = value
303 311
304 312 #-------------------------------------------------------------------------
305 313 # init_* methods called by __init__
306 314 #-------------------------------------------------------------------------
307 315
308 316 def init_ipython_dir(self, ipython_dir):
309 317 if ipython_dir is not None:
310 318 self.ipython_dir = ipython_dir
311 319 self.config.Global.ipython_dir = self.ipython_dir
312 320 return
313 321
314 322 if hasattr(self.config.Global, 'ipython_dir'):
315 323 self.ipython_dir = self.config.Global.ipython_dir
316 324 else:
317 325 self.ipython_dir = get_ipython_dir()
318 326
319 327 # All children can just read this
320 328 self.config.Global.ipython_dir = self.ipython_dir
321 329
322 330 def init_instance_attrs(self):
323 331 self.more = False
324 332
325 333 # command compiler
326 334 self.compile = codeop.CommandCompiler()
327 335
328 336 # User input buffer
329 337 self.buffer = []
330 338
331 339 # Make an empty namespace, which extension writers can rely on both
332 340 # existing and NEVER being used by ipython itself. This gives them a
333 341 # convenient location for storing additional information and state
334 342 # their extensions may require, without fear of collisions with other
335 343 # ipython names that may develop later.
336 344 self.meta = Struct()
337 345
338 346 # Object variable to store code object waiting execution. This is
339 347 # used mainly by the multithreaded shells, but it can come in handy in
340 348 # other situations. No need to use a Queue here, since it's a single
341 349 # item which gets cleared once run.
342 350 self.code_to_run = None
343 351
344 352 # Temporary files used for various purposes. Deleted at exit.
345 353 self.tempfiles = []
346 354
347 355 # Keep track of readline usage (later set by init_readline)
348 356 self.has_readline = False
349 357
350 358 # keep track of where we started running (mainly for crash post-mortem)
351 359 # This is not being used anywhere currently.
352 360 self.starting_dir = os.getcwd()
353 361
354 362 # Indentation management
355 363 self.indent_current_nsp = 0
356 364
357 365 def init_encoding(self):
358 366 # Get system encoding at startup time. Certain terminals (like Emacs
359 367 # under Win32 have it set to None, and we need to have a known valid
360 368 # encoding to use in the raw_input() method
361 369 try:
362 370 self.stdin_encoding = sys.stdin.encoding or 'ascii'
363 371 except AttributeError:
364 372 self.stdin_encoding = 'ascii'
365 373
366 374 def init_syntax_highlighting(self):
367 375 # Python source parser/formatter for syntax highlighting
368 376 pyformat = PyColorize.Parser().format
369 377 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
370 378
371 379 def init_pushd_popd_magic(self):
372 380 # for pushd/popd management
373 381 try:
374 382 self.home_dir = get_home_dir()
375 383 except HomeDirError, msg:
376 384 fatal(msg)
377 385
378 386 self.dir_stack = []
379 387
380 388 def init_logger(self):
381 389 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
382 390 # local shortcut, this is used a LOT
383 391 self.log = self.logger.log
384 392
385 393 def init_logstart(self):
386 394 if self.logappend:
387 395 self.magic_logstart(self.logappend + ' append')
388 396 elif self.logfile:
389 397 self.magic_logstart(self.logfile)
390 398 elif self.logstart:
391 399 self.magic_logstart()
392 400
393 401 def init_builtins(self):
394 402 self.builtin_trap = BuiltinTrap(shell=self)
395 403
396 404 def init_inspector(self):
397 405 # Object inspector
398 406 self.inspector = oinspect.Inspector(oinspect.InspectColors,
399 407 PyColorize.ANSICodeColors,
400 408 'NoColor',
401 409 self.object_info_string_level)
402 410
403 411 def init_io(self):
404 412 import IPython.utils.io
405 413 if sys.platform == 'win32' and readline.have_readline and \
406 414 self.readline_use:
407 415 Term = IPython.utils.io.IOTerm(
408 416 cout=readline._outputfile,cerr=readline._outputfile
409 417 )
410 418 else:
411 419 Term = IPython.utils.io.IOTerm()
412 420 IPython.utils.io.Term = Term
413 421
414 422 def init_prompts(self):
415 423 # TODO: This is a pass for now because the prompts are managed inside
416 424 # the DisplayHook. Once there is a separate prompt manager, this
417 425 # will initialize that object and all prompt related information.
418 426 pass
419 427
420 428 def init_displayhook(self):
421 429 # Initialize displayhook, set in/out prompts and printing system
422 430 self.displayhook = self.displayhook_class(
423 431 shell=self,
424 432 cache_size=self.cache_size,
425 433 input_sep = self.separate_in,
426 434 output_sep = self.separate_out,
427 435 output_sep2 = self.separate_out2,
428 436 ps1 = self.prompt_in1,
429 437 ps2 = self.prompt_in2,
430 438 ps_out = self.prompt_out,
431 439 pad_left = self.prompts_pad_left
432 440 )
433 441 # This is a context manager that installs/revmoes the displayhook at
434 442 # the appropriate time.
435 443 self.display_trap = DisplayTrap(hook=self.displayhook)
436 444
437 445 def init_reload_doctest(self):
438 446 # Do a proper resetting of doctest, including the necessary displayhook
439 447 # monkeypatching
440 448 try:
441 449 doctest_reload()
442 450 except ImportError:
443 451 warn("doctest module does not exist.")
444 452
445 453 #-------------------------------------------------------------------------
446 454 # Things related to injections into the sys module
447 455 #-------------------------------------------------------------------------
448 456
449 457 def save_sys_module_state(self):
450 458 """Save the state of hooks in the sys module.
451 459
452 460 This has to be called after self.user_ns is created.
453 461 """
454 462 self._orig_sys_module_state = {}
455 463 self._orig_sys_module_state['stdin'] = sys.stdin
456 464 self._orig_sys_module_state['stdout'] = sys.stdout
457 465 self._orig_sys_module_state['stderr'] = sys.stderr
458 466 self._orig_sys_module_state['excepthook'] = sys.excepthook
459 467 try:
460 468 self._orig_sys_modules_main_name = self.user_ns['__name__']
461 469 except KeyError:
462 470 pass
463 471
464 472 def restore_sys_module_state(self):
465 473 """Restore the state of the sys module."""
466 474 try:
467 475 for k, v in self._orig_sys_module_state.items():
468 476 setattr(sys, k, v)
469 477 except AttributeError:
470 478 pass
471 479 try:
472 480 delattr(sys, 'ipcompleter')
473 481 except AttributeError:
474 482 pass
475 483 # Reset what what done in self.init_sys_modules
476 484 try:
477 485 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
478 486 except (AttributeError, KeyError):
479 487 pass
480 488
481 489 #-------------------------------------------------------------------------
482 490 # Things related to hooks
483 491 #-------------------------------------------------------------------------
484 492
485 493 def init_hooks(self):
486 494 # hooks holds pointers used for user-side customizations
487 495 self.hooks = Struct()
488 496
489 497 self.strdispatchers = {}
490 498
491 499 # Set all default hooks, defined in the IPython.hooks module.
492 500 hooks = IPython.core.hooks
493 501 for hook_name in hooks.__all__:
494 502 # default hooks have priority 100, i.e. low; user hooks should have
495 503 # 0-100 priority
496 504 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
497 505
498 506 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
499 507 """set_hook(name,hook) -> sets an internal IPython hook.
500 508
501 509 IPython exposes some of its internal API as user-modifiable hooks. By
502 510 adding your function to one of these hooks, you can modify IPython's
503 511 behavior to call at runtime your own routines."""
504 512
505 513 # At some point in the future, this should validate the hook before it
506 514 # accepts it. Probably at least check that the hook takes the number
507 515 # of args it's supposed to.
508 516
509 517 f = new.instancemethod(hook,self,self.__class__)
510 518
511 519 # check if the hook is for strdispatcher first
512 520 if str_key is not None:
513 521 sdp = self.strdispatchers.get(name, StrDispatch())
514 522 sdp.add_s(str_key, f, priority )
515 523 self.strdispatchers[name] = sdp
516 524 return
517 525 if re_key is not None:
518 526 sdp = self.strdispatchers.get(name, StrDispatch())
519 527 sdp.add_re(re.compile(re_key), f, priority )
520 528 self.strdispatchers[name] = sdp
521 529 return
522 530
523 531 dp = getattr(self.hooks, name, None)
524 532 if name not in IPython.core.hooks.__all__:
525 533 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
526 534 if not dp:
527 535 dp = IPython.core.hooks.CommandChainDispatcher()
528 536
529 537 try:
530 538 dp.add(f,priority)
531 539 except AttributeError:
532 540 # it was not commandchain, plain old func - replace
533 541 dp = f
534 542
535 543 setattr(self.hooks,name, dp)
536 544
537 545 #-------------------------------------------------------------------------
538 546 # Things related to the "main" module
539 547 #-------------------------------------------------------------------------
540 548
541 549 def new_main_mod(self,ns=None):
542 550 """Return a new 'main' module object for user code execution.
543 551 """
544 552 main_mod = self._user_main_module
545 553 init_fakemod_dict(main_mod,ns)
546 554 return main_mod
547 555
548 556 def cache_main_mod(self,ns,fname):
549 557 """Cache a main module's namespace.
550 558
551 559 When scripts are executed via %run, we must keep a reference to the
552 560 namespace of their __main__ module (a FakeModule instance) around so
553 561 that Python doesn't clear it, rendering objects defined therein
554 562 useless.
555 563
556 564 This method keeps said reference in a private dict, keyed by the
557 565 absolute path of the module object (which corresponds to the script
558 566 path). This way, for multiple executions of the same script we only
559 567 keep one copy of the namespace (the last one), thus preventing memory
560 568 leaks from old references while allowing the objects from the last
561 569 execution to be accessible.
562 570
563 571 Note: we can not allow the actual FakeModule instances to be deleted,
564 572 because of how Python tears down modules (it hard-sets all their
565 573 references to None without regard for reference counts). This method
566 574 must therefore make a *copy* of the given namespace, to allow the
567 575 original module's __dict__ to be cleared and reused.
568 576
569 577
570 578 Parameters
571 579 ----------
572 580 ns : a namespace (a dict, typically)
573 581
574 582 fname : str
575 583 Filename associated with the namespace.
576 584
577 585 Examples
578 586 --------
579 587
580 588 In [10]: import IPython
581 589
582 590 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
583 591
584 592 In [12]: IPython.__file__ in _ip._main_ns_cache
585 593 Out[12]: True
586 594 """
587 595 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
588 596
589 597 def clear_main_mod_cache(self):
590 598 """Clear the cache of main modules.
591 599
592 600 Mainly for use by utilities like %reset.
593 601
594 602 Examples
595 603 --------
596 604
597 605 In [15]: import IPython
598 606
599 607 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
600 608
601 609 In [17]: len(_ip._main_ns_cache) > 0
602 610 Out[17]: True
603 611
604 612 In [18]: _ip.clear_main_mod_cache()
605 613
606 614 In [19]: len(_ip._main_ns_cache) == 0
607 615 Out[19]: True
608 616 """
609 617 self._main_ns_cache.clear()
610 618
611 619 #-------------------------------------------------------------------------
612 620 # Things related to debugging
613 621 #-------------------------------------------------------------------------
614 622
615 623 def init_pdb(self):
616 624 # Set calling of pdb on exceptions
617 625 # self.call_pdb is a property
618 626 self.call_pdb = self.pdb
619 627
620 628 def _get_call_pdb(self):
621 629 return self._call_pdb
622 630
623 631 def _set_call_pdb(self,val):
624 632
625 633 if val not in (0,1,False,True):
626 634 raise ValueError,'new call_pdb value must be boolean'
627 635
628 636 # store value in instance
629 637 self._call_pdb = val
630 638
631 639 # notify the actual exception handlers
632 640 self.InteractiveTB.call_pdb = val
633 641
634 642 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
635 643 'Control auto-activation of pdb at exceptions')
636 644
637 645 def debugger(self,force=False):
638 646 """Call the pydb/pdb debugger.
639 647
640 648 Keywords:
641 649
642 650 - force(False): by default, this routine checks the instance call_pdb
643 651 flag and does not actually invoke the debugger if the flag is false.
644 652 The 'force' option forces the debugger to activate even if the flag
645 653 is false.
646 654 """
647 655
648 656 if not (force or self.call_pdb):
649 657 return
650 658
651 659 if not hasattr(sys,'last_traceback'):
652 660 error('No traceback has been produced, nothing to debug.')
653 661 return
654 662
655 663 # use pydb if available
656 664 if debugger.has_pydb:
657 665 from pydb import pm
658 666 else:
659 667 # fallback to our internal debugger
660 668 pm = lambda : self.InteractiveTB.debugger(force=True)
661 669 self.history_saving_wrapper(pm)()
662 670
663 671 #-------------------------------------------------------------------------
664 672 # Things related to IPython's various namespaces
665 673 #-------------------------------------------------------------------------
666 674
667 675 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
668 676 # Create the namespace where the user will operate. user_ns is
669 677 # normally the only one used, and it is passed to the exec calls as
670 678 # the locals argument. But we do carry a user_global_ns namespace
671 679 # given as the exec 'globals' argument, This is useful in embedding
672 680 # situations where the ipython shell opens in a context where the
673 681 # distinction between locals and globals is meaningful. For
674 682 # non-embedded contexts, it is just the same object as the user_ns dict.
675 683
676 684 # FIXME. For some strange reason, __builtins__ is showing up at user
677 685 # level as a dict instead of a module. This is a manual fix, but I
678 686 # should really track down where the problem is coming from. Alex
679 687 # Schmolck reported this problem first.
680 688
681 689 # A useful post by Alex Martelli on this topic:
682 690 # Re: inconsistent value from __builtins__
683 691 # Von: Alex Martelli <aleaxit@yahoo.com>
684 692 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
685 693 # Gruppen: comp.lang.python
686 694
687 695 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
688 696 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
689 697 # > <type 'dict'>
690 698 # > >>> print type(__builtins__)
691 699 # > <type 'module'>
692 700 # > Is this difference in return value intentional?
693 701
694 702 # Well, it's documented that '__builtins__' can be either a dictionary
695 703 # or a module, and it's been that way for a long time. Whether it's
696 704 # intentional (or sensible), I don't know. In any case, the idea is
697 705 # that if you need to access the built-in namespace directly, you
698 706 # should start with "import __builtin__" (note, no 's') which will
699 707 # definitely give you a module. Yeah, it's somewhat confusing:-(.
700 708
701 709 # These routines return properly built dicts as needed by the rest of
702 710 # the code, and can also be used by extension writers to generate
703 711 # properly initialized namespaces.
704 712 user_ns, user_global_ns = self.make_user_namespaces(user_ns, user_global_ns)
705 713
706 714 # Assign namespaces
707 715 # This is the namespace where all normal user variables live
708 716 self.user_ns = user_ns
709 717 self.user_global_ns = user_global_ns
710 718
711 719 # An auxiliary namespace that checks what parts of the user_ns were
712 720 # loaded at startup, so we can list later only variables defined in
713 721 # actual interactive use. Since it is always a subset of user_ns, it
714 722 # doesn't need to be separately tracked in the ns_table.
715 723 self.user_ns_hidden = {}
716 724
717 725 # A namespace to keep track of internal data structures to prevent
718 726 # them from cluttering user-visible stuff. Will be updated later
719 727 self.internal_ns = {}
720 728
721 729 # Now that FakeModule produces a real module, we've run into a nasty
722 730 # problem: after script execution (via %run), the module where the user
723 731 # code ran is deleted. Now that this object is a true module (needed
724 732 # so docetst and other tools work correctly), the Python module
725 733 # teardown mechanism runs over it, and sets to None every variable
726 734 # present in that module. Top-level references to objects from the
727 735 # script survive, because the user_ns is updated with them. However,
728 736 # calling functions defined in the script that use other things from
729 737 # the script will fail, because the function's closure had references
730 738 # to the original objects, which are now all None. So we must protect
731 739 # these modules from deletion by keeping a cache.
732 740 #
733 741 # To avoid keeping stale modules around (we only need the one from the
734 742 # last run), we use a dict keyed with the full path to the script, so
735 743 # only the last version of the module is held in the cache. Note,
736 744 # however, that we must cache the module *namespace contents* (their
737 745 # __dict__). Because if we try to cache the actual modules, old ones
738 746 # (uncached) could be destroyed while still holding references (such as
739 747 # those held by GUI objects that tend to be long-lived)>
740 748 #
741 749 # The %reset command will flush this cache. See the cache_main_mod()
742 750 # and clear_main_mod_cache() methods for details on use.
743 751
744 752 # This is the cache used for 'main' namespaces
745 753 self._main_ns_cache = {}
746 754 # And this is the single instance of FakeModule whose __dict__ we keep
747 755 # copying and clearing for reuse on each %run
748 756 self._user_main_module = FakeModule()
749 757
750 758 # A table holding all the namespaces IPython deals with, so that
751 759 # introspection facilities can search easily.
752 760 self.ns_table = {'user':user_ns,
753 761 'user_global':user_global_ns,
754 762 'internal':self.internal_ns,
755 763 'builtin':__builtin__.__dict__
756 764 }
757 765
758 766 # Similarly, track all namespaces where references can be held and that
759 767 # we can safely clear (so it can NOT include builtin). This one can be
760 768 # a simple list.
761 769 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
762 770 self.internal_ns, self._main_ns_cache ]
763 771
764 772 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
765 773 """Return a valid local and global user interactive namespaces.
766 774
767 775 This builds a dict with the minimal information needed to operate as a
768 776 valid IPython user namespace, which you can pass to the various
769 777 embedding classes in ipython. The default implementation returns the
770 778 same dict for both the locals and the globals to allow functions to
771 779 refer to variables in the namespace. Customized implementations can
772 780 return different dicts. The locals dictionary can actually be anything
773 781 following the basic mapping protocol of a dict, but the globals dict
774 782 must be a true dict, not even a subclass. It is recommended that any
775 783 custom object for the locals namespace synchronize with the globals
776 784 dict somehow.
777 785
778 786 Raises TypeError if the provided globals namespace is not a true dict.
779 787
780 788 Parameters
781 789 ----------
782 790 user_ns : dict-like, optional
783 791 The current user namespace. The items in this namespace should
784 792 be included in the output. If None, an appropriate blank
785 793 namespace should be created.
786 794 user_global_ns : dict, optional
787 795 The current user global namespace. The items in this namespace
788 796 should be included in the output. If None, an appropriate
789 797 blank namespace should be created.
790 798
791 799 Returns
792 800 -------
793 801 A pair of dictionary-like object to be used as the local namespace
794 802 of the interpreter and a dict to be used as the global namespace.
795 803 """
796 804
797 805
798 806 # We must ensure that __builtin__ (without the final 's') is always
799 807 # available and pointing to the __builtin__ *module*. For more details:
800 808 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
801 809
802 810 if user_ns is None:
803 811 # Set __name__ to __main__ to better match the behavior of the
804 812 # normal interpreter.
805 813 user_ns = {'__name__' :'__main__',
806 814 '__builtin__' : __builtin__,
807 815 '__builtins__' : __builtin__,
808 816 }
809 817 else:
810 818 user_ns.setdefault('__name__','__main__')
811 819 user_ns.setdefault('__builtin__',__builtin__)
812 820 user_ns.setdefault('__builtins__',__builtin__)
813 821
814 822 if user_global_ns is None:
815 823 user_global_ns = user_ns
816 824 if type(user_global_ns) is not dict:
817 825 raise TypeError("user_global_ns must be a true dict; got %r"
818 826 % type(user_global_ns))
819 827
820 828 return user_ns, user_global_ns
821 829
822 830 def init_sys_modules(self):
823 831 # We need to insert into sys.modules something that looks like a
824 832 # module but which accesses the IPython namespace, for shelve and
825 833 # pickle to work interactively. Normally they rely on getting
826 834 # everything out of __main__, but for embedding purposes each IPython
827 835 # instance has its own private namespace, so we can't go shoving
828 836 # everything into __main__.
829 837
830 838 # note, however, that we should only do this for non-embedded
831 839 # ipythons, which really mimic the __main__.__dict__ with their own
832 840 # namespace. Embedded instances, on the other hand, should not do
833 841 # this because they need to manage the user local/global namespaces
834 842 # only, but they live within a 'normal' __main__ (meaning, they
835 843 # shouldn't overtake the execution environment of the script they're
836 844 # embedded in).
837 845
838 846 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
839 847
840 848 try:
841 849 main_name = self.user_ns['__name__']
842 850 except KeyError:
843 851 raise KeyError('user_ns dictionary MUST have a "__name__" key')
844 852 else:
845 853 sys.modules[main_name] = FakeModule(self.user_ns)
846 854
847 855 def init_user_ns(self):
848 856 """Initialize all user-visible namespaces to their minimum defaults.
849 857
850 858 Certain history lists are also initialized here, as they effectively
851 859 act as user namespaces.
852 860
853 861 Notes
854 862 -----
855 863 All data structures here are only filled in, they are NOT reset by this
856 864 method. If they were not empty before, data will simply be added to
857 865 therm.
858 866 """
859 867 # This function works in two parts: first we put a few things in
860 868 # user_ns, and we sync that contents into user_ns_hidden so that these
861 869 # initial variables aren't shown by %who. After the sync, we add the
862 870 # rest of what we *do* want the user to see with %who even on a new
863 871 # session (probably nothing, so theye really only see their own stuff)
864 872
865 873 # The user dict must *always* have a __builtin__ reference to the
866 874 # Python standard __builtin__ namespace, which must be imported.
867 875 # This is so that certain operations in prompt evaluation can be
868 876 # reliably executed with builtins. Note that we can NOT use
869 877 # __builtins__ (note the 's'), because that can either be a dict or a
870 878 # module, and can even mutate at runtime, depending on the context
871 879 # (Python makes no guarantees on it). In contrast, __builtin__ is
872 880 # always a module object, though it must be explicitly imported.
873 881
874 882 # For more details:
875 883 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
876 884 ns = dict(__builtin__ = __builtin__)
877 885
878 886 # Put 'help' in the user namespace
879 887 try:
880 888 from site import _Helper
881 889 ns['help'] = _Helper()
882 890 except ImportError:
883 891 warn('help() not available - check site.py')
884 892
885 893 # make global variables for user access to the histories
886 894 ns['_ih'] = self.input_hist
887 895 ns['_oh'] = self.output_hist
888 896 ns['_dh'] = self.dir_hist
889 897
890 898 ns['_sh'] = shadowns
891 899
892 900 # user aliases to input and output histories. These shouldn't show up
893 901 # in %who, as they can have very large reprs.
894 902 ns['In'] = self.input_hist
895 903 ns['Out'] = self.output_hist
896 904
897 905 # Store myself as the public api!!!
898 906 ns['get_ipython'] = self.get_ipython
899 907
900 908 # Sync what we've added so far to user_ns_hidden so these aren't seen
901 909 # by %who
902 910 self.user_ns_hidden.update(ns)
903 911
904 912 # Anything put into ns now would show up in %who. Think twice before
905 913 # putting anything here, as we really want %who to show the user their
906 914 # stuff, not our variables.
907 915
908 916 # Finally, update the real user's namespace
909 917 self.user_ns.update(ns)
910 918
911 919
912 920 def reset(self):
913 921 """Clear all internal namespaces.
914 922
915 923 Note that this is much more aggressive than %reset, since it clears
916 924 fully all namespaces, as well as all input/output lists.
917 925 """
918 926 for ns in self.ns_refs_table:
919 927 ns.clear()
920 928
921 929 self.alias_manager.clear_aliases()
922 930
923 931 # Clear input and output histories
924 932 self.input_hist[:] = []
925 933 self.input_hist_raw[:] = []
926 934 self.output_hist.clear()
927 935
928 936 # Restore the user namespaces to minimal usability
929 937 self.init_user_ns()
930 938
931 939 # Restore the default and user aliases
932 940 self.alias_manager.init_aliases()
933 941
934 942 def reset_selective(self, regex=None):
935 943 """Clear selective variables from internal namespaces based on a specified regular expression.
936 944
937 945 Parameters
938 946 ----------
939 947 regex : string or compiled pattern, optional
940 948 A regular expression pattern that will be used in searching variable names in the users
941 949 namespaces.
942 950 """
943 951 if regex is not None:
944 952 try:
945 953 m = re.compile(regex)
946 954 except TypeError:
947 955 raise TypeError('regex must be a string or compiled pattern')
948 956 # Search for keys in each namespace that match the given regex
949 957 # If a match is found, delete the key/value pair.
950 958 for ns in self.ns_refs_table:
951 959 for var in ns:
952 960 if m.search(var):
953 961 del ns[var]
954 962
955 963 def push(self, variables, interactive=True):
956 964 """Inject a group of variables into the IPython user namespace.
957 965
958 966 Parameters
959 967 ----------
960 968 variables : dict, str or list/tuple of str
961 969 The variables to inject into the user's namespace. If a dict,
962 970 a simple update is done. If a str, the string is assumed to
963 971 have variable names separated by spaces. A list/tuple of str
964 972 can also be used to give the variable names. If just the variable
965 973 names are give (list/tuple/str) then the variable values looked
966 974 up in the callers frame.
967 975 interactive : bool
968 976 If True (default), the variables will be listed with the ``who``
969 977 magic.
970 978 """
971 979 vdict = None
972 980
973 981 # We need a dict of name/value pairs to do namespace updates.
974 982 if isinstance(variables, dict):
975 983 vdict = variables
976 984 elif isinstance(variables, (basestring, list, tuple)):
977 985 if isinstance(variables, basestring):
978 986 vlist = variables.split()
979 987 else:
980 988 vlist = variables
981 989 vdict = {}
982 990 cf = sys._getframe(1)
983 991 for name in vlist:
984 992 try:
985 993 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
986 994 except:
987 995 print ('Could not get variable %s from %s' %
988 996 (name,cf.f_code.co_name))
989 997 else:
990 998 raise ValueError('variables must be a dict/str/list/tuple')
991 999
992 1000 # Propagate variables to user namespace
993 1001 self.user_ns.update(vdict)
994 1002
995 1003 # And configure interactive visibility
996 1004 config_ns = self.user_ns_hidden
997 1005 if interactive:
998 1006 for name, val in vdict.iteritems():
999 1007 config_ns.pop(name, None)
1000 1008 else:
1001 1009 for name,val in vdict.iteritems():
1002 1010 config_ns[name] = val
1003 1011
1004 1012 #-------------------------------------------------------------------------
1005 1013 # Things related to history management
1006 1014 #-------------------------------------------------------------------------
1007 1015
1008 1016 def init_history(self):
1009 1017 # List of input with multi-line handling.
1010 1018 self.input_hist = InputList()
1011 1019 # This one will hold the 'raw' input history, without any
1012 1020 # pre-processing. This will allow users to retrieve the input just as
1013 1021 # it was exactly typed in by the user, with %hist -r.
1014 1022 self.input_hist_raw = InputList()
1015 1023
1016 1024 # list of visited directories
1017 1025 try:
1018 1026 self.dir_hist = [os.getcwd()]
1019 1027 except OSError:
1020 1028 self.dir_hist = []
1021 1029
1022 1030 # dict of output history
1023 1031 self.output_hist = {}
1024 1032
1025 1033 # Now the history file
1026 1034 if self.profile:
1027 1035 histfname = 'history-%s' % self.profile
1028 1036 else:
1029 1037 histfname = 'history'
1030 1038 self.histfile = os.path.join(self.ipython_dir, histfname)
1031 1039
1032 1040 # Fill the history zero entry, user counter starts at 1
1033 1041 self.input_hist.append('\n')
1034 1042 self.input_hist_raw.append('\n')
1035 1043
1036 1044 def init_shadow_hist(self):
1037 1045 try:
1038 1046 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1039 1047 except exceptions.UnicodeDecodeError:
1040 1048 print "Your ipython_dir can't be decoded to unicode!"
1041 1049 print "Please set HOME environment variable to something that"
1042 1050 print r"only has ASCII characters, e.g. c:\home"
1043 1051 print "Now it is", self.ipython_dir
1044 1052 sys.exit()
1045 1053 self.shadowhist = ipcorehist.ShadowHist(self.db)
1046 1054
1047 1055 def savehist(self):
1048 1056 """Save input history to a file (via readline library)."""
1049 1057
1050 1058 try:
1051 1059 self.readline.write_history_file(self.histfile)
1052 1060 except:
1053 1061 print 'Unable to save IPython command history to file: ' + \
1054 1062 `self.histfile`
1055 1063
1056 1064 def reloadhist(self):
1057 1065 """Reload the input history from disk file."""
1058 1066
1059 1067 try:
1060 1068 self.readline.clear_history()
1061 1069 self.readline.read_history_file(self.shell.histfile)
1062 1070 except AttributeError:
1063 1071 pass
1064 1072
1065 1073 def history_saving_wrapper(self, func):
1066 1074 """ Wrap func for readline history saving
1067 1075
1068 1076 Convert func into callable that saves & restores
1069 1077 history around the call """
1070 1078
1071 1079 if self.has_readline:
1072 1080 from IPython.utils import rlineimpl as readline
1073 1081 else:
1074 1082 return func
1075 1083
1076 1084 def wrapper():
1077 1085 self.savehist()
1078 1086 try:
1079 1087 func()
1080 1088 finally:
1081 1089 readline.read_history_file(self.histfile)
1082 1090 return wrapper
1083 1091
1084 1092 def get_history(self, index=None, raw=False, output=True):
1085 1093 """Get the history list.
1086 1094
1087 1095 Get the input and output history.
1088 1096
1089 1097 Parameters
1090 1098 ----------
1091 1099 index : n or (n1, n2) or None
1092 1100 If n, then the last entries. If a tuple, then all in
1093 1101 range(n1, n2). If None, then all entries. Raises IndexError if
1094 1102 the format of index is incorrect.
1095 1103 raw : bool
1096 1104 If True, return the raw input.
1097 1105 output : bool
1098 1106 If True, then return the output as well.
1099 1107
1100 1108 Returns
1101 1109 -------
1102 1110 If output is True, then return a dict of tuples, keyed by the prompt
1103 1111 numbers and with values of (input, output). If output is False, then
1104 1112 a dict, keyed by the prompt number with the values of input. Raises
1105 1113 IndexError if no history is found.
1106 1114 """
1107 1115 if raw:
1108 1116 input_hist = self.input_hist_raw
1109 1117 else:
1110 1118 input_hist = self.input_hist
1111 1119 if output:
1112 1120 output_hist = self.user_ns['Out']
1113 1121 n = len(input_hist)
1114 1122 if index is None:
1115 1123 start=0; stop=n
1116 1124 elif isinstance(index, int):
1117 1125 start=n-index; stop=n
1118 1126 elif isinstance(index, tuple) and len(index) == 2:
1119 1127 start=index[0]; stop=index[1]
1120 1128 else:
1121 1129 raise IndexError('Not a valid index for the input history: %r' % index)
1122 1130 hist = {}
1123 1131 for i in range(start, stop):
1124 1132 if output:
1125 1133 hist[i] = (input_hist[i], output_hist.get(i))
1126 1134 else:
1127 1135 hist[i] = input_hist[i]
1128 1136 if len(hist)==0:
1129 1137 raise IndexError('No history for range of indices: %r' % index)
1130 1138 return hist
1131 1139
1132 1140 #-------------------------------------------------------------------------
1133 1141 # Things related to exception handling and tracebacks (not debugging)
1134 1142 #-------------------------------------------------------------------------
1135 1143
1136 1144 def init_traceback_handlers(self, custom_exceptions):
1137 1145 # Syntax error handler.
1138 1146 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1139 1147
1140 1148 # The interactive one is initialized with an offset, meaning we always
1141 1149 # want to remove the topmost item in the traceback, which is our own
1142 1150 # internal code. Valid modes: ['Plain','Context','Verbose']
1143 1151 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1144 1152 color_scheme='NoColor',
1145 1153 tb_offset = 1)
1146 1154
1147 1155 # The instance will store a pointer to the system-wide exception hook,
1148 1156 # so that runtime code (such as magics) can access it. This is because
1149 1157 # during the read-eval loop, it may get temporarily overwritten.
1150 1158 self.sys_excepthook = sys.excepthook
1151 1159
1152 1160 # and add any custom exception handlers the user may have specified
1153 1161 self.set_custom_exc(*custom_exceptions)
1154 1162
1155 1163 # Set the exception mode
1156 1164 self.InteractiveTB.set_mode(mode=self.xmode)
1157 1165
1158 1166 def set_custom_exc(self,exc_tuple,handler):
1159 1167 """set_custom_exc(exc_tuple,handler)
1160 1168
1161 1169 Set a custom exception handler, which will be called if any of the
1162 1170 exceptions in exc_tuple occur in the mainloop (specifically, in the
1163 1171 runcode() method.
1164 1172
1165 1173 Inputs:
1166 1174
1167 1175 - exc_tuple: a *tuple* of valid exceptions to call the defined
1168 1176 handler for. It is very important that you use a tuple, and NOT A
1169 1177 LIST here, because of the way Python's except statement works. If
1170 1178 you only want to trap a single exception, use a singleton tuple:
1171 1179
1172 1180 exc_tuple == (MyCustomException,)
1173 1181
1174 1182 - handler: this must be defined as a function with the following
1175 1183 basic interface: def my_handler(self,etype,value,tb).
1176 1184
1177 1185 This will be made into an instance method (via new.instancemethod)
1178 1186 of IPython itself, and it will be called if any of the exceptions
1179 1187 listed in the exc_tuple are caught. If the handler is None, an
1180 1188 internal basic one is used, which just prints basic info.
1181 1189
1182 1190 WARNING: by putting in your own exception handler into IPython's main
1183 1191 execution loop, you run a very good chance of nasty crashes. This
1184 1192 facility should only be used if you really know what you are doing."""
1185 1193
1186 1194 assert type(exc_tuple)==type(()) , \
1187 1195 "The custom exceptions must be given AS A TUPLE."
1188 1196
1189 1197 def dummy_handler(self,etype,value,tb):
1190 1198 print '*** Simple custom exception handler ***'
1191 1199 print 'Exception type :',etype
1192 1200 print 'Exception value:',value
1193 1201 print 'Traceback :',tb
1194 1202 print 'Source code :','\n'.join(self.buffer)
1195 1203
1196 1204 if handler is None: handler = dummy_handler
1197 1205
1198 1206 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1199 1207 self.custom_exceptions = exc_tuple
1200 1208
1201 1209 def excepthook(self, etype, value, tb):
1202 1210 """One more defense for GUI apps that call sys.excepthook.
1203 1211
1204 1212 GUI frameworks like wxPython trap exceptions and call
1205 1213 sys.excepthook themselves. I guess this is a feature that
1206 1214 enables them to keep running after exceptions that would
1207 1215 otherwise kill their mainloop. This is a bother for IPython
1208 1216 which excepts to catch all of the program exceptions with a try:
1209 1217 except: statement.
1210 1218
1211 1219 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1212 1220 any app directly invokes sys.excepthook, it will look to the user like
1213 1221 IPython crashed. In order to work around this, we can disable the
1214 1222 CrashHandler and replace it with this excepthook instead, which prints a
1215 1223 regular traceback using our InteractiveTB. In this fashion, apps which
1216 1224 call sys.excepthook will generate a regular-looking exception from
1217 1225 IPython, and the CrashHandler will only be triggered by real IPython
1218 1226 crashes.
1219 1227
1220 1228 This hook should be used sparingly, only in places which are not likely
1221 1229 to be true IPython errors.
1222 1230 """
1223 1231 self.showtraceback((etype,value,tb),tb_offset=0)
1224 1232
1225 1233 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1226 1234 exception_only=False):
1227 1235 """Display the exception that just occurred.
1228 1236
1229 1237 If nothing is known about the exception, this is the method which
1230 1238 should be used throughout the code for presenting user tracebacks,
1231 1239 rather than directly invoking the InteractiveTB object.
1232 1240
1233 1241 A specific showsyntaxerror() also exists, but this method can take
1234 1242 care of calling it if needed, so unless you are explicitly catching a
1235 1243 SyntaxError exception, don't try to analyze the stack manually and
1236 1244 simply call this method."""
1237 1245
1238 1246 try:
1239 1247 if exc_tuple is None:
1240 1248 etype, value, tb = sys.exc_info()
1241 1249 else:
1242 1250 etype, value, tb = exc_tuple
1243 1251
1244 1252 if etype is None:
1245 1253 if hasattr(sys, 'last_type'):
1246 1254 etype, value, tb = sys.last_type, sys.last_value, \
1247 1255 sys.last_traceback
1248 1256 else:
1249 1257 self.write('No traceback available to show.\n')
1250 1258 return
1251 1259
1252 1260 if etype is SyntaxError:
1253 1261 # Though this won't be called by syntax errors in the input
1254 1262 # line, there may be SyntaxError cases whith imported code.
1255 1263 self.showsyntaxerror(filename)
1256 1264 elif etype is UsageError:
1257 1265 print "UsageError:", value
1258 1266 else:
1259 1267 # WARNING: these variables are somewhat deprecated and not
1260 1268 # necessarily safe to use in a threaded environment, but tools
1261 1269 # like pdb depend on their existence, so let's set them. If we
1262 1270 # find problems in the field, we'll need to revisit their use.
1263 1271 sys.last_type = etype
1264 1272 sys.last_value = value
1265 1273 sys.last_traceback = tb
1266 1274
1267 1275 if etype in self.custom_exceptions:
1268 1276 self.CustomTB(etype,value,tb)
1269 1277 else:
1270 1278 if exception_only:
1271 1279 m = ('An exception has occurred, use %tb to see the '
1272 1280 'full traceback.')
1273 1281 print m
1274 1282 self.InteractiveTB.show_exception_only(etype, value)
1275 1283 else:
1276 1284 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1277 1285 if self.InteractiveTB.call_pdb:
1278 1286 # pdb mucks up readline, fix it back
1279 1287 self.set_completer()
1280 1288
1281 1289 except KeyboardInterrupt:
1282 1290 self.write("\nKeyboardInterrupt\n")
1283 1291
1284 1292
1285 1293 def showsyntaxerror(self, filename=None):
1286 1294 """Display the syntax error that just occurred.
1287 1295
1288 1296 This doesn't display a stack trace because there isn't one.
1289 1297
1290 1298 If a filename is given, it is stuffed in the exception instead
1291 1299 of what was there before (because Python's parser always uses
1292 1300 "<string>" when reading from a string).
1293 1301 """
1294 1302 etype, value, last_traceback = sys.exc_info()
1295 1303
1296 1304 # See note about these variables in showtraceback() above
1297 1305 sys.last_type = etype
1298 1306 sys.last_value = value
1299 1307 sys.last_traceback = last_traceback
1300 1308
1301 1309 if filename and etype is SyntaxError:
1302 1310 # Work hard to stuff the correct filename in the exception
1303 1311 try:
1304 1312 msg, (dummy_filename, lineno, offset, line) = value
1305 1313 except:
1306 1314 # Not the format we expect; leave it alone
1307 1315 pass
1308 1316 else:
1309 1317 # Stuff in the right filename
1310 1318 try:
1311 1319 # Assume SyntaxError is a class exception
1312 1320 value = SyntaxError(msg, (filename, lineno, offset, line))
1313 1321 except:
1314 1322 # If that failed, assume SyntaxError is a string
1315 1323 value = msg, (filename, lineno, offset, line)
1316 1324 self.SyntaxTB(etype,value,[])
1317 1325
1318 1326 #-------------------------------------------------------------------------
1319 1327 # Things related to tab completion
1320 1328 #-------------------------------------------------------------------------
1321 1329
1322 1330 def complete(self, text):
1323 1331 """Return a sorted list of all possible completions on text.
1324 1332
1325 1333 Inputs:
1326 1334
1327 1335 - text: a string of text to be completed on.
1328 1336
1329 1337 This is a wrapper around the completion mechanism, similar to what
1330 1338 readline does at the command line when the TAB key is hit. By
1331 1339 exposing it as a method, it can be used by other non-readline
1332 1340 environments (such as GUIs) for text completion.
1333 1341
1334 1342 Simple usage example:
1335 1343
1336 1344 In [7]: x = 'hello'
1337 1345
1338 1346 In [8]: x
1339 1347 Out[8]: 'hello'
1340 1348
1341 1349 In [9]: print x
1342 1350 hello
1343 1351
1344 1352 In [10]: _ip.complete('x.l')
1345 1353 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1346 1354 """
1347 1355
1348 1356 # Inject names into __builtin__ so we can complete on the added names.
1349 1357 with self.builtin_trap:
1350 1358 complete = self.Completer.complete
1351 1359 state = 0
1352 1360 # use a dict so we get unique keys, since ipyhton's multiple
1353 1361 # completers can return duplicates. When we make 2.4 a requirement,
1354 1362 # start using sets instead, which are faster.
1355 1363 comps = {}
1356 1364 while True:
1357 1365 newcomp = complete(text,state,line_buffer=text)
1358 1366 if newcomp is None:
1359 1367 break
1360 1368 comps[newcomp] = 1
1361 1369 state += 1
1362 1370 outcomps = comps.keys()
1363 1371 outcomps.sort()
1364 1372 #print "T:",text,"OC:",outcomps # dbg
1365 1373 #print "vars:",self.user_ns.keys()
1366 1374 return outcomps
1367 1375
1368 1376 def set_custom_completer(self,completer,pos=0):
1369 1377 """Adds a new custom completer function.
1370 1378
1371 1379 The position argument (defaults to 0) is the index in the completers
1372 1380 list where you want the completer to be inserted."""
1373 1381
1374 1382 newcomp = new.instancemethod(completer,self.Completer,
1375 1383 self.Completer.__class__)
1376 1384 self.Completer.matchers.insert(pos,newcomp)
1377 1385
1378 1386 def set_completer(self):
1379 1387 """Reset readline's completer to be our own."""
1380 1388 self.readline.set_completer(self.Completer.complete)
1381 1389
1382 1390 def set_completer_frame(self, frame=None):
1383 1391 """Set the frame of the completer."""
1384 1392 if frame:
1385 1393 self.Completer.namespace = frame.f_locals
1386 1394 self.Completer.global_namespace = frame.f_globals
1387 1395 else:
1388 1396 self.Completer.namespace = self.user_ns
1389 1397 self.Completer.global_namespace = self.user_global_ns
1390 1398
1391 1399 #-------------------------------------------------------------------------
1392 1400 # Things related to readline
1393 1401 #-------------------------------------------------------------------------
1394 1402
1395 1403 def init_readline(self):
1396 1404 """Command history completion/saving/reloading."""
1397 1405
1398 1406 if self.readline_use:
1399 1407 import IPython.utils.rlineimpl as readline
1400 1408
1401 1409 self.rl_next_input = None
1402 1410 self.rl_do_indent = False
1403 1411
1404 1412 if not self.readline_use or not readline.have_readline:
1405 1413 self.has_readline = False
1406 1414 self.readline = None
1407 1415 # Set a number of methods that depend on readline to be no-op
1408 1416 self.savehist = no_op
1409 1417 self.reloadhist = no_op
1410 1418 self.set_completer = no_op
1411 1419 self.set_custom_completer = no_op
1412 1420 self.set_completer_frame = no_op
1413 1421 warn('Readline services not available or not loaded.')
1414 1422 else:
1415 1423 self.has_readline = True
1416 1424 self.readline = readline
1417 1425 sys.modules['readline'] = readline
1418 1426 import atexit
1419 1427 from IPython.core.completer import IPCompleter
1420 1428 self.Completer = IPCompleter(self,
1421 1429 self.user_ns,
1422 1430 self.user_global_ns,
1423 1431 self.readline_omit__names,
1424 1432 self.alias_manager.alias_table)
1425 1433 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1426 1434 self.strdispatchers['complete_command'] = sdisp
1427 1435 self.Completer.custom_completers = sdisp
1428 1436 # Platform-specific configuration
1429 1437 if os.name == 'nt':
1430 1438 self.readline_startup_hook = readline.set_pre_input_hook
1431 1439 else:
1432 1440 self.readline_startup_hook = readline.set_startup_hook
1433 1441
1434 1442 # Load user's initrc file (readline config)
1435 1443 # Or if libedit is used, load editrc.
1436 1444 inputrc_name = os.environ.get('INPUTRC')
1437 1445 if inputrc_name is None:
1438 1446 home_dir = get_home_dir()
1439 1447 if home_dir is not None:
1440 1448 inputrc_name = '.inputrc'
1441 1449 if readline.uses_libedit:
1442 1450 inputrc_name = '.editrc'
1443 1451 inputrc_name = os.path.join(home_dir, inputrc_name)
1444 1452 if os.path.isfile(inputrc_name):
1445 1453 try:
1446 1454 readline.read_init_file(inputrc_name)
1447 1455 except:
1448 1456 warn('Problems reading readline initialization file <%s>'
1449 1457 % inputrc_name)
1450 1458
1451 1459 # save this in sys so embedded copies can restore it properly
1452 1460 sys.ipcompleter = self.Completer.complete
1453 1461 self.set_completer()
1454 1462
1455 1463 # Configure readline according to user's prefs
1456 1464 # This is only done if GNU readline is being used. If libedit
1457 1465 # is being used (as on Leopard) the readline config is
1458 1466 # not run as the syntax for libedit is different.
1459 1467 if not readline.uses_libedit:
1460 1468 for rlcommand in self.readline_parse_and_bind:
1461 1469 #print "loading rl:",rlcommand # dbg
1462 1470 readline.parse_and_bind(rlcommand)
1463 1471
1464 1472 # Remove some chars from the delimiters list. If we encounter
1465 1473 # unicode chars, discard them.
1466 1474 delims = readline.get_completer_delims().encode("ascii", "ignore")
1467 1475 delims = delims.translate(string._idmap,
1468 1476 self.readline_remove_delims)
1469 1477 readline.set_completer_delims(delims)
1470 1478 # otherwise we end up with a monster history after a while:
1471 1479 readline.set_history_length(1000)
1472 1480 try:
1473 1481 #print '*** Reading readline history' # dbg
1474 1482 readline.read_history_file(self.histfile)
1475 1483 except IOError:
1476 1484 pass # It doesn't exist yet.
1477 1485
1478 1486 atexit.register(self.atexit_operations)
1479 1487 del atexit
1480 1488
1481 1489 # Configure auto-indent for all platforms
1482 1490 self.set_autoindent(self.autoindent)
1483 1491
1484 1492 def set_next_input(self, s):
1485 1493 """ Sets the 'default' input string for the next command line.
1486 1494
1487 1495 Requires readline.
1488 1496
1489 1497 Example:
1490 1498
1491 1499 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1492 1500 [D:\ipython]|2> Hello Word_ # cursor is here
1493 1501 """
1494 1502
1495 1503 self.rl_next_input = s
1496 1504
1497 1505 # Maybe move this to the terminal subclass?
1498 1506 def pre_readline(self):
1499 1507 """readline hook to be used at the start of each line.
1500 1508
1501 1509 Currently it handles auto-indent only."""
1502 1510
1503 1511 if self.rl_do_indent:
1504 1512 self.readline.insert_text(self._indent_current_str())
1505 1513 if self.rl_next_input is not None:
1506 1514 self.readline.insert_text(self.rl_next_input)
1507 1515 self.rl_next_input = None
1508 1516
1509 1517 def _indent_current_str(self):
1510 1518 """return the current level of indentation as a string"""
1511 1519 return self.indent_current_nsp * ' '
1512 1520
1513 1521 #-------------------------------------------------------------------------
1514 1522 # Things related to magics
1515 1523 #-------------------------------------------------------------------------
1516 1524
1517 1525 def init_magics(self):
1518 1526 # FIXME: Move the color initialization to the DisplayHook, which
1519 1527 # should be split into a prompt manager and displayhook. We probably
1520 1528 # even need a centralize colors management object.
1521 1529 self.magic_colors(self.colors)
1522 1530 # History was moved to a separate module
1523 1531 from . import history
1524 1532 history.init_ipython(self)
1525 1533
1526 1534 def magic(self,arg_s):
1527 1535 """Call a magic function by name.
1528 1536
1529 1537 Input: a string containing the name of the magic function to call and any
1530 1538 additional arguments to be passed to the magic.
1531 1539
1532 1540 magic('name -opt foo bar') is equivalent to typing at the ipython
1533 1541 prompt:
1534 1542
1535 1543 In[1]: %name -opt foo bar
1536 1544
1537 1545 To call a magic without arguments, simply use magic('name').
1538 1546
1539 1547 This provides a proper Python function to call IPython's magics in any
1540 1548 valid Python code you can type at the interpreter, including loops and
1541 1549 compound statements.
1542 1550 """
1543 1551 args = arg_s.split(' ',1)
1544 1552 magic_name = args[0]
1545 1553 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1546 1554
1547 1555 try:
1548 1556 magic_args = args[1]
1549 1557 except IndexError:
1550 1558 magic_args = ''
1551 1559 fn = getattr(self,'magic_'+magic_name,None)
1552 1560 if fn is None:
1553 1561 error("Magic function `%s` not found." % magic_name)
1554 1562 else:
1555 1563 magic_args = self.var_expand(magic_args,1)
1556 1564 with nested(self.builtin_trap,):
1557 1565 result = fn(magic_args)
1558 1566 return result
1559 1567
1560 1568 def define_magic(self, magicname, func):
1561 1569 """Expose own function as magic function for ipython
1562 1570
1563 1571 def foo_impl(self,parameter_s=''):
1564 1572 'My very own magic!. (Use docstrings, IPython reads them).'
1565 1573 print 'Magic function. Passed parameter is between < >:'
1566 1574 print '<%s>' % parameter_s
1567 1575 print 'The self object is:',self
1568 1576
1569 1577 self.define_magic('foo',foo_impl)
1570 1578 """
1571 1579
1572 1580 import new
1573 1581 im = new.instancemethod(func,self, self.__class__)
1574 1582 old = getattr(self, "magic_" + magicname, None)
1575 1583 setattr(self, "magic_" + magicname, im)
1576 1584 return old
1577 1585
1578 1586 #-------------------------------------------------------------------------
1579 1587 # Things related to macros
1580 1588 #-------------------------------------------------------------------------
1581 1589
1582 1590 def define_macro(self, name, themacro):
1583 1591 """Define a new macro
1584 1592
1585 1593 Parameters
1586 1594 ----------
1587 1595 name : str
1588 1596 The name of the macro.
1589 1597 themacro : str or Macro
1590 1598 The action to do upon invoking the macro. If a string, a new
1591 1599 Macro object is created by passing the string to it.
1592 1600 """
1593 1601
1594 1602 from IPython.core import macro
1595 1603
1596 1604 if isinstance(themacro, basestring):
1597 1605 themacro = macro.Macro(themacro)
1598 1606 if not isinstance(themacro, macro.Macro):
1599 1607 raise ValueError('A macro must be a string or a Macro instance.')
1600 1608 self.user_ns[name] = themacro
1601 1609
1602 1610 #-------------------------------------------------------------------------
1603 1611 # Things related to the running of system commands
1604 1612 #-------------------------------------------------------------------------
1605 1613
1606 1614 def system(self, cmd):
1607 1615 """Make a system call, using IPython."""
1608 1616 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1609 1617
1610 1618 #-------------------------------------------------------------------------
1611 1619 # Things related to aliases
1612 1620 #-------------------------------------------------------------------------
1613 1621
1614 1622 def init_alias(self):
1615 1623 self.alias_manager = AliasManager(shell=self, config=self.config)
1616 1624 self.ns_table['alias'] = self.alias_manager.alias_table,
1617 1625
1618 1626 #-------------------------------------------------------------------------
1619 1627 # Things related to extensions and plugins
1620 1628 #-------------------------------------------------------------------------
1621 1629
1622 1630 def init_extension_manager(self):
1623 1631 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1624 1632
1625 1633 def init_plugin_manager(self):
1626 1634 self.plugin_manager = PluginManager(config=self.config)
1627 1635
1628 1636 #-------------------------------------------------------------------------
1629 1637 # Things related to the prefilter
1630 1638 #-------------------------------------------------------------------------
1631 1639
1632 1640 def init_prefilter(self):
1633 1641 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1634 1642 # Ultimately this will be refactored in the new interpreter code, but
1635 1643 # for now, we should expose the main prefilter method (there's legacy
1636 1644 # code out there that may rely on this).
1637 1645 self.prefilter = self.prefilter_manager.prefilter_lines
1638 1646
1639 1647 #-------------------------------------------------------------------------
1640 1648 # Things related to the running of code
1641 1649 #-------------------------------------------------------------------------
1642 1650
1643 1651 def ex(self, cmd):
1644 1652 """Execute a normal python statement in user namespace."""
1645 1653 with nested(self.builtin_trap,):
1646 1654 exec cmd in self.user_global_ns, self.user_ns
1647 1655
1648 1656 def ev(self, expr):
1649 1657 """Evaluate python expression expr in user namespace.
1650 1658
1651 1659 Returns the result of evaluation
1652 1660 """
1653 1661 with nested(self.builtin_trap,):
1654 1662 return eval(expr, self.user_global_ns, self.user_ns)
1655 1663
1656 1664 def safe_execfile(self, fname, *where, **kw):
1657 1665 """A safe version of the builtin execfile().
1658 1666
1659 1667 This version will never throw an exception, but instead print
1660 1668 helpful error messages to the screen. This only works on pure
1661 1669 Python files with the .py extension.
1662 1670
1663 1671 Parameters
1664 1672 ----------
1665 1673 fname : string
1666 1674 The name of the file to be executed.
1667 1675 where : tuple
1668 1676 One or two namespaces, passed to execfile() as (globals,locals).
1669 1677 If only one is given, it is passed as both.
1670 1678 exit_ignore : bool (False)
1671 1679 If True, then silence SystemExit for non-zero status (it is always
1672 1680 silenced for zero status, as it is so common).
1673 1681 """
1674 1682 kw.setdefault('exit_ignore', False)
1675 1683
1676 1684 fname = os.path.abspath(os.path.expanduser(fname))
1677 1685
1678 1686 # Make sure we have a .py file
1679 1687 if not fname.endswith('.py'):
1680 1688 warn('File must end with .py to be run using execfile: <%s>' % fname)
1681 1689
1682 1690 # Make sure we can open the file
1683 1691 try:
1684 1692 with open(fname) as thefile:
1685 1693 pass
1686 1694 except:
1687 1695 warn('Could not open file <%s> for safe execution.' % fname)
1688 1696 return
1689 1697
1690 1698 # Find things also in current directory. This is needed to mimic the
1691 1699 # behavior of running a script from the system command line, where
1692 1700 # Python inserts the script's directory into sys.path
1693 1701 dname = os.path.dirname(fname)
1694 1702
1695 1703 with prepended_to_syspath(dname):
1696 1704 try:
1697 1705 execfile(fname,*where)
1698 1706 except SystemExit, status:
1699 1707 # If the call was made with 0 or None exit status (sys.exit(0)
1700 1708 # or sys.exit() ), don't bother showing a traceback, as both of
1701 1709 # these are considered normal by the OS:
1702 1710 # > python -c'import sys;sys.exit(0)'; echo $?
1703 1711 # 0
1704 1712 # > python -c'import sys;sys.exit()'; echo $?
1705 1713 # 0
1706 1714 # For other exit status, we show the exception unless
1707 1715 # explicitly silenced, but only in short form.
1708 1716 if status.code not in (0, None) and not kw['exit_ignore']:
1709 1717 self.showtraceback(exception_only=True)
1710 1718 except:
1711 1719 self.showtraceback()
1712 1720
1713 1721 def safe_execfile_ipy(self, fname):
1714 1722 """Like safe_execfile, but for .ipy files with IPython syntax.
1715 1723
1716 1724 Parameters
1717 1725 ----------
1718 1726 fname : str
1719 1727 The name of the file to execute. The filename must have a
1720 1728 .ipy extension.
1721 1729 """
1722 1730 fname = os.path.abspath(os.path.expanduser(fname))
1723 1731
1724 1732 # Make sure we have a .py file
1725 1733 if not fname.endswith('.ipy'):
1726 1734 warn('File must end with .py to be run using execfile: <%s>' % fname)
1727 1735
1728 1736 # Make sure we can open the file
1729 1737 try:
1730 1738 with open(fname) as thefile:
1731 1739 pass
1732 1740 except:
1733 1741 warn('Could not open file <%s> for safe execution.' % fname)
1734 1742 return
1735 1743
1736 1744 # Find things also in current directory. This is needed to mimic the
1737 1745 # behavior of running a script from the system command line, where
1738 1746 # Python inserts the script's directory into sys.path
1739 1747 dname = os.path.dirname(fname)
1740 1748
1741 1749 with prepended_to_syspath(dname):
1742 1750 try:
1743 1751 with open(fname) as thefile:
1744 1752 script = thefile.read()
1745 1753 # self.runlines currently captures all exceptions
1746 1754 # raise in user code. It would be nice if there were
1747 1755 # versions of runlines, execfile that did raise, so
1748 1756 # we could catch the errors.
1749 1757 self.runlines(script, clean=True)
1750 1758 except:
1751 1759 self.showtraceback()
1752 1760 warn('Unknown failure executing file: <%s>' % fname)
1753 1761
1754 1762 def runlines(self, lines, clean=False):
1755 1763 """Run a string of one or more lines of source.
1756 1764
1757 1765 This method is capable of running a string containing multiple source
1758 1766 lines, as if they had been entered at the IPython prompt. Since it
1759 1767 exposes IPython's processing machinery, the given strings can contain
1760 1768 magic calls (%magic), special shell access (!cmd), etc.
1761 1769 """
1762 1770
1763 1771 if isinstance(lines, (list, tuple)):
1764 1772 lines = '\n'.join(lines)
1765 1773
1766 1774 if clean:
1767 1775 lines = self._cleanup_ipy_script(lines)
1768 1776
1769 1777 # We must start with a clean buffer, in case this is run from an
1770 1778 # interactive IPython session (via a magic, for example).
1771 1779 self.resetbuffer()
1772 1780 lines = lines.splitlines()
1773 1781 more = 0
1774 1782
1775 1783 with nested(self.builtin_trap, self.display_trap):
1776 1784 for line in lines:
1777 1785 # skip blank lines so we don't mess up the prompt counter, but do
1778 1786 # NOT skip even a blank line if we are in a code block (more is
1779 1787 # true)
1780 1788
1781 1789 if line or more:
1782 1790 # push to raw history, so hist line numbers stay in sync
1783 1791 self.input_hist_raw.append("# " + line + "\n")
1784 1792 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
1785 1793 more = self.push_line(prefiltered)
1786 1794 # IPython's runsource returns None if there was an error
1787 1795 # compiling the code. This allows us to stop processing right
1788 1796 # away, so the user gets the error message at the right place.
1789 1797 if more is None:
1790 1798 break
1791 1799 else:
1792 1800 self.input_hist_raw.append("\n")
1793 1801 # final newline in case the input didn't have it, so that the code
1794 1802 # actually does get executed
1795 1803 if more:
1796 1804 self.push_line('\n')
1797 1805
1798 1806 def runsource(self, source, filename='<input>', symbol='single'):
1799 1807 """Compile and run some source in the interpreter.
1800 1808
1801 1809 Arguments are as for compile_command().
1802 1810
1803 1811 One several things can happen:
1804 1812
1805 1813 1) The input is incorrect; compile_command() raised an
1806 1814 exception (SyntaxError or OverflowError). A syntax traceback
1807 1815 will be printed by calling the showsyntaxerror() method.
1808 1816
1809 1817 2) The input is incomplete, and more input is required;
1810 1818 compile_command() returned None. Nothing happens.
1811 1819
1812 1820 3) The input is complete; compile_command() returned a code
1813 1821 object. The code is executed by calling self.runcode() (which
1814 1822 also handles run-time exceptions, except for SystemExit).
1815 1823
1816 1824 The return value is:
1817 1825
1818 1826 - True in case 2
1819 1827
1820 1828 - False in the other cases, unless an exception is raised, where
1821 1829 None is returned instead. This can be used by external callers to
1822 1830 know whether to continue feeding input or not.
1823 1831
1824 1832 The return value can be used to decide whether to use sys.ps1 or
1825 1833 sys.ps2 to prompt the next line."""
1826 1834
1827 1835 # if the source code has leading blanks, add 'if 1:\n' to it
1828 1836 # this allows execution of indented pasted code. It is tempting
1829 1837 # to add '\n' at the end of source to run commands like ' a=1'
1830 1838 # directly, but this fails for more complicated scenarios
1831 1839 source=source.encode(self.stdin_encoding)
1832 1840 if source[:1] in [' ', '\t']:
1833 1841 source = 'if 1:\n%s' % source
1834 1842
1835 1843 try:
1836 1844 code = self.compile(source,filename,symbol)
1837 1845 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
1838 1846 # Case 1
1839 1847 self.showsyntaxerror(filename)
1840 1848 return None
1841 1849
1842 1850 if code is None:
1843 1851 # Case 2
1844 1852 return True
1845 1853
1846 1854 # Case 3
1847 1855 # We store the code object so that threaded shells and
1848 1856 # custom exception handlers can access all this info if needed.
1849 1857 # The source corresponding to this can be obtained from the
1850 1858 # buffer attribute as '\n'.join(self.buffer).
1851 1859 self.code_to_run = code
1852 1860 # now actually execute the code object
1853 1861 if self.runcode(code) == 0:
1854 1862 return False
1855 1863 else:
1856 1864 return None
1857 1865
1858 1866 def runcode(self,code_obj):
1859 1867 """Execute a code object.
1860 1868
1861 1869 When an exception occurs, self.showtraceback() is called to display a
1862 1870 traceback.
1863 1871
1864 1872 Return value: a flag indicating whether the code to be run completed
1865 1873 successfully:
1866 1874
1867 1875 - 0: successful execution.
1868 1876 - 1: an error occurred.
1869 1877 """
1870 1878
1871 1879 # Set our own excepthook in case the user code tries to call it
1872 1880 # directly, so that the IPython crash handler doesn't get triggered
1873 1881 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1874 1882
1875 1883 # we save the original sys.excepthook in the instance, in case config
1876 1884 # code (such as magics) needs access to it.
1877 1885 self.sys_excepthook = old_excepthook
1878 1886 outflag = 1 # happens in more places, so it's easier as default
1879 1887 try:
1880 1888 try:
1881 1889 self.hooks.pre_runcode_hook()
1882 1890 exec code_obj in self.user_global_ns, self.user_ns
1883 1891 finally:
1884 1892 # Reset our crash handler in place
1885 1893 sys.excepthook = old_excepthook
1886 1894 except SystemExit:
1887 1895 self.resetbuffer()
1888 1896 self.showtraceback(exception_only=True)
1889 1897 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
1890 1898 except self.custom_exceptions:
1891 1899 etype,value,tb = sys.exc_info()
1892 1900 self.CustomTB(etype,value,tb)
1893 1901 except:
1894 1902 self.showtraceback()
1895 1903 else:
1896 1904 outflag = 0
1897 1905 if softspace(sys.stdout, 0):
1898 1906 print
1899 1907 # Flush out code object which has been run (and source)
1900 1908 self.code_to_run = None
1901 1909 return outflag
1902 1910
1903 1911 def push_line(self, line):
1904 1912 """Push a line to the interpreter.
1905 1913
1906 1914 The line should not have a trailing newline; it may have
1907 1915 internal newlines. The line is appended to a buffer and the
1908 1916 interpreter's runsource() method is called with the
1909 1917 concatenated contents of the buffer as source. If this
1910 1918 indicates that the command was executed or invalid, the buffer
1911 1919 is reset; otherwise, the command is incomplete, and the buffer
1912 1920 is left as it was after the line was appended. The return
1913 1921 value is 1 if more input is required, 0 if the line was dealt
1914 1922 with in some way (this is the same as runsource()).
1915 1923 """
1916 1924
1917 1925 # autoindent management should be done here, and not in the
1918 1926 # interactive loop, since that one is only seen by keyboard input. We
1919 1927 # need this done correctly even for code run via runlines (which uses
1920 1928 # push).
1921 1929
1922 1930 #print 'push line: <%s>' % line # dbg
1923 1931 for subline in line.splitlines():
1924 1932 self._autoindent_update(subline)
1925 1933 self.buffer.append(line)
1926 1934 more = self.runsource('\n'.join(self.buffer), self.filename)
1927 1935 if not more:
1928 1936 self.resetbuffer()
1929 1937 return more
1930 1938
1931 1939 def resetbuffer(self):
1932 1940 """Reset the input buffer."""
1933 1941 self.buffer[:] = []
1934 1942
1935 1943 def _is_secondary_block_start(self, s):
1936 1944 if not s.endswith(':'):
1937 1945 return False
1938 1946 if (s.startswith('elif') or
1939 1947 s.startswith('else') or
1940 1948 s.startswith('except') or
1941 1949 s.startswith('finally')):
1942 1950 return True
1943 1951
1944 1952 def _cleanup_ipy_script(self, script):
1945 1953 """Make a script safe for self.runlines()
1946 1954
1947 1955 Currently, IPython is lines based, with blocks being detected by
1948 1956 empty lines. This is a problem for block based scripts that may
1949 1957 not have empty lines after blocks. This script adds those empty
1950 1958 lines to make scripts safe for running in the current line based
1951 1959 IPython.
1952 1960 """
1953 1961 res = []
1954 1962 lines = script.splitlines()
1955 1963 level = 0
1956 1964
1957 1965 for l in lines:
1958 1966 lstripped = l.lstrip()
1959 1967 stripped = l.strip()
1960 1968 if not stripped:
1961 1969 continue
1962 1970 newlevel = len(l) - len(lstripped)
1963 1971 if level > 0 and newlevel == 0 and \
1964 1972 not self._is_secondary_block_start(stripped):
1965 1973 # add empty line
1966 1974 res.append('')
1967 1975 res.append(l)
1968 1976 level = newlevel
1969 1977
1970 1978 return '\n'.join(res) + '\n'
1971 1979
1972 1980 def _autoindent_update(self,line):
1973 1981 """Keep track of the indent level."""
1974 1982
1975 1983 #debugx('line')
1976 1984 #debugx('self.indent_current_nsp')
1977 1985 if self.autoindent:
1978 1986 if line:
1979 1987 inisp = num_ini_spaces(line)
1980 1988 if inisp < self.indent_current_nsp:
1981 1989 self.indent_current_nsp = inisp
1982 1990
1983 1991 if line[-1] == ':':
1984 1992 self.indent_current_nsp += 4
1985 1993 elif dedent_re.match(line):
1986 1994 self.indent_current_nsp -= 4
1987 1995 else:
1988 1996 self.indent_current_nsp = 0
1989 1997
1990 1998 #-------------------------------------------------------------------------
1991 1999 # Things related to GUI support and pylab
1992 2000 #-------------------------------------------------------------------------
1993 2001
1994 2002 def enable_pylab(self, gui=None):
1995 2003 raise NotImplementedError('Implement enable_pylab in a subclass')
1996 2004
1997 2005 #-------------------------------------------------------------------------
1998 2006 # Utilities
1999 2007 #-------------------------------------------------------------------------
2000 2008
2001 2009 def getoutput(self, cmd):
2002 2010 return getoutput(self.var_expand(cmd,depth=2),
2003 2011 header=self.system_header,
2004 2012 verbose=self.system_verbose)
2005 2013
2006 2014 def getoutputerror(self, cmd):
2007 2015 return getoutputerror(self.var_expand(cmd,depth=2),
2008 2016 header=self.system_header,
2009 2017 verbose=self.system_verbose)
2010 2018
2011 2019 def var_expand(self,cmd,depth=0):
2012 2020 """Expand python variables in a string.
2013 2021
2014 2022 The depth argument indicates how many frames above the caller should
2015 2023 be walked to look for the local namespace where to expand variables.
2016 2024
2017 2025 The global namespace for expansion is always the user's interactive
2018 2026 namespace.
2019 2027 """
2020 2028
2021 2029 return str(ItplNS(cmd,
2022 2030 self.user_ns, # globals
2023 2031 # Skip our own frame in searching for locals:
2024 2032 sys._getframe(depth+1).f_locals # locals
2025 2033 ))
2026 2034
2027 2035 def mktempfile(self,data=None):
2028 2036 """Make a new tempfile and return its filename.
2029 2037
2030 2038 This makes a call to tempfile.mktemp, but it registers the created
2031 2039 filename internally so ipython cleans it up at exit time.
2032 2040
2033 2041 Optional inputs:
2034 2042
2035 2043 - data(None): if data is given, it gets written out to the temp file
2036 2044 immediately, and the file is closed again."""
2037 2045
2038 2046 filename = tempfile.mktemp('.py','ipython_edit_')
2039 2047 self.tempfiles.append(filename)
2040 2048
2041 2049 if data:
2042 2050 tmp_file = open(filename,'w')
2043 2051 tmp_file.write(data)
2044 2052 tmp_file.close()
2045 2053 return filename
2046 2054
2047 2055 # TODO: This should be removed when Term is refactored.
2048 2056 def write(self,data):
2049 2057 """Write a string to the default output"""
2050 2058 IPython.utils.io.Term.cout.write(data)
2051 2059
2052 2060 # TODO: This should be removed when Term is refactored.
2053 2061 def write_err(self,data):
2054 2062 """Write a string to the default error output"""
2055 2063 IPython.utils.io.Term.cerr.write(data)
2056 2064
2057 2065 def ask_yes_no(self,prompt,default=True):
2058 2066 if self.quiet:
2059 2067 return True
2060 2068 return ask_yes_no(prompt,default)
2061 2069
2062 2070 #-------------------------------------------------------------------------
2063 2071 # Things related to IPython exiting
2064 2072 #-------------------------------------------------------------------------
2065 2073
2066 2074 def atexit_operations(self):
2067 2075 """This will be executed at the time of exit.
2068 2076
2069 2077 Saving of persistent data should be performed here.
2070 2078 """
2071 2079 self.savehist()
2072 2080
2073 2081 # Cleanup all tempfiles left around
2074 2082 for tfile in self.tempfiles:
2075 2083 try:
2076 2084 os.unlink(tfile)
2077 2085 except OSError:
2078 2086 pass
2079 2087
2080 2088 # Clear all user namespaces to release all references cleanly.
2081 2089 self.reset()
2082 2090
2083 2091 # Run user hooks
2084 2092 self.hooks.shutdown_hook()
2085 2093
2086 2094 def cleanup(self):
2087 2095 self.restore_sys_module_state()
2088 2096
2089 2097
2090 2098 class InteractiveShellABC(object):
2091 2099 """An abstract base class for InteractiveShell."""
2092 2100 __metaclass__ = abc.ABCMeta
2093 2101
2094 2102 InteractiveShellABC.register(InteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now