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