##// END OF EJS Templates
Add support for simultaneous interactive and inline matplotlib plots....
Fernando Perez -
Show More
@@ -1,2463 +1,2489 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 __future__
22 22 import abc
23 23 import atexit
24 24 import codeop
25 25 import exceptions
26 26 import new
27 27 import os
28 28 import re
29 29 import string
30 30 import sys
31 31 import tempfile
32 32 from contextlib import nested
33 33
34 34 from IPython.config.configurable import Configurable
35 35 from IPython.core import debugger, oinspect
36 36 from IPython.core import history as ipcorehist
37 37 from IPython.core import page
38 38 from IPython.core import prefilter
39 39 from IPython.core import shadowns
40 40 from IPython.core import ultratb
41 41 from IPython.core.alias import AliasManager
42 42 from IPython.core.builtin_trap import BuiltinTrap
43 43 from IPython.core.display_trap import DisplayTrap
44 44 from IPython.core.displayhook import DisplayHook
45 45 from IPython.core.error import TryNext, UsageError
46 46 from IPython.core.extensions import ExtensionManager
47 47 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
48 48 from IPython.core.inputlist import InputList
49 49 from IPython.core.inputsplitter import IPythonInputSplitter
50 50 from IPython.core.logger import Logger
51 51 from IPython.core.magic import Magic
52 52 from IPython.core.payload import PayloadManager
53 53 from IPython.core.plugin import PluginManager
54 54 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
55 55 from IPython.external.Itpl import ItplNS
56 56 from IPython.utils import PyColorize
57 57 from IPython.utils import io
58 58 from IPython.utils import pickleshare
59 59 from IPython.utils.doctestreload import doctest_reload
60 60 from IPython.utils.io import ask_yes_no, rprint
61 61 from IPython.utils.ipstruct import Struct
62 62 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
63 63 from IPython.utils.process import system, getoutput
64 64 from IPython.utils.strdispatch import StrDispatch
65 65 from IPython.utils.syspathcontext import prepended_to_syspath
66 66 from IPython.utils.text import num_ini_spaces, format_screen
67 67 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
68 68 List, Unicode, Instance, Type)
69 69 from IPython.utils.warn import warn, error, fatal
70 70 import IPython.core.hooks
71 71
72 72 #-----------------------------------------------------------------------------
73 73 # Globals
74 74 #-----------------------------------------------------------------------------
75 75
76 76 # compiled regexps for autoindent management
77 77 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
78 78
79 79 #-----------------------------------------------------------------------------
80 80 # Utilities
81 81 #-----------------------------------------------------------------------------
82 82
83 83 # store the builtin raw_input globally, and use this always, in case user code
84 84 # overwrites it (like wx.py.PyShell does)
85 85 raw_input_original = raw_input
86 86
87 87 def softspace(file, newvalue):
88 88 """Copied from code.py, to remove the dependency"""
89 89
90 90 oldvalue = 0
91 91 try:
92 92 oldvalue = file.softspace
93 93 except AttributeError:
94 94 pass
95 95 try:
96 96 file.softspace = newvalue
97 97 except (AttributeError, TypeError):
98 98 # "attribute-less object" or "read-only attributes"
99 99 pass
100 100 return oldvalue
101 101
102 102
103 103 def no_op(*a, **kw): pass
104 104
105 105 class SpaceInInput(exceptions.Exception): pass
106 106
107 107 class Bunch: pass
108 108
109 109
110 110 def get_default_colors():
111 111 if sys.platform=='darwin':
112 112 return "LightBG"
113 113 elif os.name=='nt':
114 114 return 'Linux'
115 115 else:
116 116 return 'Linux'
117 117
118 118
119 119 class SeparateStr(Str):
120 120 """A Str subclass to validate separate_in, separate_out, etc.
121 121
122 122 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
123 123 """
124 124
125 125 def validate(self, obj, value):
126 126 if value == '0': value = ''
127 127 value = value.replace('\\n','\n')
128 128 return super(SeparateStr, self).validate(obj, value)
129 129
130 130 class MultipleInstanceError(Exception):
131 131 pass
132 132
133 133
134 134 #-----------------------------------------------------------------------------
135 135 # Main IPython class
136 136 #-----------------------------------------------------------------------------
137 137
138 138
139 139 class InteractiveShell(Configurable, Magic):
140 140 """An enhanced, interactive shell for Python."""
141 141
142 142 _instance = None
143 143 autocall = Enum((0,1,2), default_value=1, config=True)
144 144 # TODO: remove all autoindent logic and put into frontends.
145 145 # We can't do this yet because even runlines uses the autoindent.
146 146 autoindent = CBool(True, config=True)
147 147 automagic = CBool(True, config=True)
148 148 cache_size = Int(1000, config=True)
149 149 color_info = CBool(True, config=True)
150 150 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
151 151 default_value=get_default_colors(), config=True)
152 152 debug = CBool(False, config=True)
153 153 deep_reload = CBool(False, config=True)
154 154 displayhook_class = Type(DisplayHook)
155 155 exit_now = CBool(False)
156 156 filename = Str("<ipython console>")
157 157 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
158 158 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter')
159 159 logstart = CBool(False, config=True)
160 160 logfile = Str('', config=True)
161 161 logappend = Str('', config=True)
162 162 object_info_string_level = Enum((0,1,2), default_value=0,
163 163 config=True)
164 164 pdb = CBool(False, config=True)
165
165 166 pprint = CBool(True, config=True)
166 167 profile = Str('', config=True)
167 168 prompt_in1 = Str('In [\\#]: ', config=True)
168 169 prompt_in2 = Str(' .\\D.: ', config=True)
169 170 prompt_out = Str('Out[\\#]: ', config=True)
170 171 prompts_pad_left = CBool(True, config=True)
171 172 quiet = CBool(False, config=True)
172 173
173 174 # The readline stuff will eventually be moved to the terminal subclass
174 175 # but for now, we can't do that as readline is welded in everywhere.
175 176 readline_use = CBool(True, config=True)
176 177 readline_merge_completions = CBool(True, config=True)
177 178 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
178 179 readline_remove_delims = Str('-/~', config=True)
179 180 readline_parse_and_bind = List([
180 181 'tab: complete',
181 182 '"\C-l": clear-screen',
182 183 'set show-all-if-ambiguous on',
183 184 '"\C-o": tab-insert',
184 185 '"\M-i": " "',
185 186 '"\M-o": "\d\d\d\d"',
186 187 '"\M-I": "\d\d\d\d"',
187 188 '"\C-r": reverse-search-history',
188 189 '"\C-s": forward-search-history',
189 190 '"\C-p": history-search-backward',
190 191 '"\C-n": history-search-forward',
191 192 '"\e[A": history-search-backward',
192 193 '"\e[B": history-search-forward',
193 194 '"\C-k": kill-line',
194 195 '"\C-u": unix-line-discard',
195 196 ], allow_none=False, config=True)
196 197
197 198 # TODO: this part of prompt management should be moved to the frontends.
198 199 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
199 200 separate_in = SeparateStr('\n', config=True)
200 201 separate_out = SeparateStr('', config=True)
201 202 separate_out2 = SeparateStr('', config=True)
202 203 wildcards_case_sensitive = CBool(True, config=True)
203 204 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
204 205 default_value='Context', config=True)
205 206
206 207 # Subcomponents of InteractiveShell
207 208 alias_manager = Instance('IPython.core.alias.AliasManager')
208 209 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
209 210 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
210 211 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
211 212 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
212 213 plugin_manager = Instance('IPython.core.plugin.PluginManager')
213 214 payload_manager = Instance('IPython.core.payload.PayloadManager')
214 215
216 # Private interface
217 _post_execute = set()
218
215 219 def __init__(self, config=None, ipython_dir=None,
216 220 user_ns=None, user_global_ns=None,
217 221 custom_exceptions=((), None)):
218 222
219 223 # This is where traits with a config_key argument are updated
220 224 # from the values on config.
221 225 super(InteractiveShell, self).__init__(config=config)
222 226
223 227 # These are relatively independent and stateless
224 228 self.init_ipython_dir(ipython_dir)
225 229 self.init_instance_attrs()
226 230
227 231 # Create namespaces (user_ns, user_global_ns, etc.)
228 232 self.init_create_namespaces(user_ns, user_global_ns)
229 233 # This has to be done after init_create_namespaces because it uses
230 234 # something in self.user_ns, but before init_sys_modules, which
231 235 # is the first thing to modify sys.
232 236 # TODO: When we override sys.stdout and sys.stderr before this class
233 237 # is created, we are saving the overridden ones here. Not sure if this
234 238 # is what we want to do.
235 239 self.save_sys_module_state()
236 240 self.init_sys_modules()
237 241
238 242 self.init_history()
239 243 self.init_encoding()
240 244 self.init_prefilter()
241 245
242 246 Magic.__init__(self, self)
243 247
244 248 self.init_syntax_highlighting()
245 249 self.init_hooks()
246 250 self.init_pushd_popd_magic()
247 251 # self.init_traceback_handlers use to be here, but we moved it below
248 252 # because it and init_io have to come after init_readline.
249 253 self.init_user_ns()
250 254 self.init_logger()
251 255 self.init_alias()
252 256 self.init_builtins()
253 257
254 258 # pre_config_initialization
255 259 self.init_shadow_hist()
256 260
257 261 # The next section should contain everything that was in ipmaker.
258 262 self.init_logstart()
259 263
260 264 # The following was in post_config_initialization
261 265 self.init_inspector()
262 266 # init_readline() must come before init_io(), because init_io uses
263 267 # readline related things.
264 268 self.init_readline()
265 269 # init_completer must come after init_readline, because it needs to
266 270 # know whether readline is present or not system-wide to configure the
267 271 # completers, since the completion machinery can now operate
268 272 # independently of readline (e.g. over the network)
269 273 self.init_completer()
270 274 # TODO: init_io() needs to happen before init_traceback handlers
271 275 # because the traceback handlers hardcode the stdout/stderr streams.
272 276 # This logic in in debugger.Pdb and should eventually be changed.
273 277 self.init_io()
274 278 self.init_traceback_handlers(custom_exceptions)
275 279 self.init_prompts()
276 280 self.init_displayhook()
277 281 self.init_reload_doctest()
278 282 self.init_magics()
279 283 self.init_pdb()
280 284 self.init_extension_manager()
281 285 self.init_plugin_manager()
282 286 self.init_payload()
283 287 self.hooks.late_startup_hook()
284 288 atexit.register(self.atexit_operations)
285 289
286 290 @classmethod
287 291 def instance(cls, *args, **kwargs):
288 292 """Returns a global InteractiveShell instance."""
289 293 if cls._instance is None:
290 294 inst = cls(*args, **kwargs)
291 295 # Now make sure that the instance will also be returned by
292 296 # the subclasses instance attribute.
293 297 for subclass in cls.mro():
294 298 if issubclass(cls, subclass) and \
295 299 issubclass(subclass, InteractiveShell):
296 300 subclass._instance = inst
297 301 else:
298 302 break
299 303 if isinstance(cls._instance, cls):
300 304 return cls._instance
301 305 else:
302 306 raise MultipleInstanceError(
303 307 'Multiple incompatible subclass instances of '
304 308 'InteractiveShell are being created.'
305 309 )
306 310
307 311 @classmethod
308 312 def initialized(cls):
309 313 return hasattr(cls, "_instance")
310 314
311 315 def get_ipython(self):
312 316 """Return the currently running IPython instance."""
313 317 return self
314 318
315 319 #-------------------------------------------------------------------------
316 320 # Trait changed handlers
317 321 #-------------------------------------------------------------------------
318 322
319 323 def _ipython_dir_changed(self, name, new):
320 324 if not os.path.isdir(new):
321 325 os.makedirs(new, mode = 0777)
322 326
323 327 def set_autoindent(self,value=None):
324 328 """Set the autoindent flag, checking for readline support.
325 329
326 330 If called with no arguments, it acts as a toggle."""
327 331
328 332 if not self.has_readline:
329 333 if os.name == 'posix':
330 334 warn("The auto-indent feature requires the readline library")
331 335 self.autoindent = 0
332 336 return
333 337 if value is None:
334 338 self.autoindent = not self.autoindent
335 339 else:
336 340 self.autoindent = value
337 341
338 342 #-------------------------------------------------------------------------
339 343 # init_* methods called by __init__
340 344 #-------------------------------------------------------------------------
341 345
342 346 def init_ipython_dir(self, ipython_dir):
343 347 if ipython_dir is not None:
344 348 self.ipython_dir = ipython_dir
345 349 self.config.Global.ipython_dir = self.ipython_dir
346 350 return
347 351
348 352 if hasattr(self.config.Global, 'ipython_dir'):
349 353 self.ipython_dir = self.config.Global.ipython_dir
350 354 else:
351 355 self.ipython_dir = get_ipython_dir()
352 356
353 357 # All children can just read this
354 358 self.config.Global.ipython_dir = self.ipython_dir
355 359
356 360 def init_instance_attrs(self):
357 361 self.more = False
358 362
359 363 # command compiler
360 364 self.compile = codeop.CommandCompiler()
361 365
362 366 # User input buffer
363 367 self.buffer = []
364 368
365 369 # Make an empty namespace, which extension writers can rely on both
366 370 # existing and NEVER being used by ipython itself. This gives them a
367 371 # convenient location for storing additional information and state
368 372 # their extensions may require, without fear of collisions with other
369 373 # ipython names that may develop later.
370 374 self.meta = Struct()
371 375
372 376 # Object variable to store code object waiting execution. This is
373 377 # used mainly by the multithreaded shells, but it can come in handy in
374 378 # other situations. No need to use a Queue here, since it's a single
375 379 # item which gets cleared once run.
376 380 self.code_to_run = None
377 381
378 382 # Temporary files used for various purposes. Deleted at exit.
379 383 self.tempfiles = []
380 384
381 385 # Keep track of readline usage (later set by init_readline)
382 386 self.has_readline = False
383 387
384 388 # keep track of where we started running (mainly for crash post-mortem)
385 389 # This is not being used anywhere currently.
386 390 self.starting_dir = os.getcwd()
387 391
388 392 # Indentation management
389 393 self.indent_current_nsp = 0
390 394
391 395 # Input splitter, to split entire cells of input into either individual
392 396 # interactive statements or whole blocks.
393 397 self.input_splitter = IPythonInputSplitter()
394 398
395 399 def init_encoding(self):
396 400 # Get system encoding at startup time. Certain terminals (like Emacs
397 401 # under Win32 have it set to None, and we need to have a known valid
398 402 # encoding to use in the raw_input() method
399 403 try:
400 404 self.stdin_encoding = sys.stdin.encoding or 'ascii'
401 405 except AttributeError:
402 406 self.stdin_encoding = 'ascii'
403 407
404 408 def init_syntax_highlighting(self):
405 409 # Python source parser/formatter for syntax highlighting
406 410 pyformat = PyColorize.Parser().format
407 411 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
408 412
409 413 def init_pushd_popd_magic(self):
410 414 # for pushd/popd management
411 415 try:
412 416 self.home_dir = get_home_dir()
413 417 except HomeDirError, msg:
414 418 fatal(msg)
415 419
416 420 self.dir_stack = []
417 421
418 422 def init_logger(self):
419 423 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
420 424 # local shortcut, this is used a LOT
421 425 self.log = self.logger.log
422 426
423 427 def init_logstart(self):
424 428 if self.logappend:
425 429 self.magic_logstart(self.logappend + ' append')
426 430 elif self.logfile:
427 431 self.magic_logstart(self.logfile)
428 432 elif self.logstart:
429 433 self.magic_logstart()
430 434
431 435 def init_builtins(self):
432 436 self.builtin_trap = BuiltinTrap(shell=self)
433 437
434 438 def init_inspector(self):
435 439 # Object inspector
436 440 self.inspector = oinspect.Inspector(oinspect.InspectColors,
437 441 PyColorize.ANSICodeColors,
438 442 'NoColor',
439 443 self.object_info_string_level)
440 444
441 445 def init_io(self):
442 446 # This will just use sys.stdout and sys.stderr. If you want to
443 447 # override sys.stdout and sys.stderr themselves, you need to do that
444 448 # *before* instantiating this class, because Term holds onto
445 449 # references to the underlying streams.
446 450 if sys.platform == 'win32' and self.has_readline:
447 451 Term = io.IOTerm(cout=self.readline._outputfile,
448 452 cerr=self.readline._outputfile)
449 453 else:
450 454 Term = io.IOTerm()
451 455 io.Term = Term
452 456
453 457 def init_prompts(self):
454 458 # TODO: This is a pass for now because the prompts are managed inside
455 459 # the DisplayHook. Once there is a separate prompt manager, this
456 460 # will initialize that object and all prompt related information.
457 461 pass
458 462
459 463 def init_displayhook(self):
460 464 # Initialize displayhook, set in/out prompts and printing system
461 465 self.displayhook = self.displayhook_class(
462 466 shell=self,
463 467 cache_size=self.cache_size,
464 468 input_sep = self.separate_in,
465 469 output_sep = self.separate_out,
466 470 output_sep2 = self.separate_out2,
467 471 ps1 = self.prompt_in1,
468 472 ps2 = self.prompt_in2,
469 473 ps_out = self.prompt_out,
470 474 pad_left = self.prompts_pad_left
471 475 )
472 476 # This is a context manager that installs/revmoes the displayhook at
473 477 # the appropriate time.
474 478 self.display_trap = DisplayTrap(hook=self.displayhook)
475 479
476 480 def init_reload_doctest(self):
477 481 # Do a proper resetting of doctest, including the necessary displayhook
478 482 # monkeypatching
479 483 try:
480 484 doctest_reload()
481 485 except ImportError:
482 486 warn("doctest module does not exist.")
483 487
484 488 #-------------------------------------------------------------------------
485 489 # Things related to injections into the sys module
486 490 #-------------------------------------------------------------------------
487 491
488 492 def save_sys_module_state(self):
489 493 """Save the state of hooks in the sys module.
490 494
491 495 This has to be called after self.user_ns is created.
492 496 """
493 497 self._orig_sys_module_state = {}
494 498 self._orig_sys_module_state['stdin'] = sys.stdin
495 499 self._orig_sys_module_state['stdout'] = sys.stdout
496 500 self._orig_sys_module_state['stderr'] = sys.stderr
497 501 self._orig_sys_module_state['excepthook'] = sys.excepthook
498 502 try:
499 503 self._orig_sys_modules_main_name = self.user_ns['__name__']
500 504 except KeyError:
501 505 pass
502 506
503 507 def restore_sys_module_state(self):
504 508 """Restore the state of the sys module."""
505 509 try:
506 510 for k, v in self._orig_sys_module_state.items():
507 511 setattr(sys, k, v)
508 512 except AttributeError:
509 513 pass
510 514 # Reset what what done in self.init_sys_modules
511 515 try:
512 516 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
513 517 except (AttributeError, KeyError):
514 518 pass
515 519
516 520 #-------------------------------------------------------------------------
517 521 # Things related to hooks
518 522 #-------------------------------------------------------------------------
519 523
520 524 def init_hooks(self):
521 525 # hooks holds pointers used for user-side customizations
522 526 self.hooks = Struct()
523 527
524 528 self.strdispatchers = {}
525 529
526 530 # Set all default hooks, defined in the IPython.hooks module.
527 531 hooks = IPython.core.hooks
528 532 for hook_name in hooks.__all__:
529 533 # default hooks have priority 100, i.e. low; user hooks should have
530 534 # 0-100 priority
531 535 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
532 536
533 537 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
534 538 """set_hook(name,hook) -> sets an internal IPython hook.
535 539
536 540 IPython exposes some of its internal API as user-modifiable hooks. By
537 541 adding your function to one of these hooks, you can modify IPython's
538 542 behavior to call at runtime your own routines."""
539 543
540 544 # At some point in the future, this should validate the hook before it
541 545 # accepts it. Probably at least check that the hook takes the number
542 546 # of args it's supposed to.
543 547
544 548 f = new.instancemethod(hook,self,self.__class__)
545 549
546 550 # check if the hook is for strdispatcher first
547 551 if str_key is not None:
548 552 sdp = self.strdispatchers.get(name, StrDispatch())
549 553 sdp.add_s(str_key, f, priority )
550 554 self.strdispatchers[name] = sdp
551 555 return
552 556 if re_key is not None:
553 557 sdp = self.strdispatchers.get(name, StrDispatch())
554 558 sdp.add_re(re.compile(re_key), f, priority )
555 559 self.strdispatchers[name] = sdp
556 560 return
557 561
558 562 dp = getattr(self.hooks, name, None)
559 563 if name not in IPython.core.hooks.__all__:
560 564 print "Warning! Hook '%s' is not one of %s" % \
561 565 (name, IPython.core.hooks.__all__ )
562 566 if not dp:
563 567 dp = IPython.core.hooks.CommandChainDispatcher()
564 568
565 569 try:
566 570 dp.add(f,priority)
567 571 except AttributeError:
568 572 # it was not commandchain, plain old func - replace
569 573 dp = f
570 574
571 575 setattr(self.hooks,name, dp)
572 576
577 def register_post_execute(self, func):
578 """Register a function for calling after code execution.
579 """
580 if not callable(func):
581 raise ValueError('argument %s must be callable' % func)
582 self._post_execute.add(func)
583
573 584 #-------------------------------------------------------------------------
574 585 # Things related to the "main" module
575 586 #-------------------------------------------------------------------------
576 587
577 588 def new_main_mod(self,ns=None):
578 589 """Return a new 'main' module object for user code execution.
579 590 """
580 591 main_mod = self._user_main_module
581 592 init_fakemod_dict(main_mod,ns)
582 593 return main_mod
583 594
584 595 def cache_main_mod(self,ns,fname):
585 596 """Cache a main module's namespace.
586 597
587 598 When scripts are executed via %run, we must keep a reference to the
588 599 namespace of their __main__ module (a FakeModule instance) around so
589 600 that Python doesn't clear it, rendering objects defined therein
590 601 useless.
591 602
592 603 This method keeps said reference in a private dict, keyed by the
593 604 absolute path of the module object (which corresponds to the script
594 605 path). This way, for multiple executions of the same script we only
595 606 keep one copy of the namespace (the last one), thus preventing memory
596 607 leaks from old references while allowing the objects from the last
597 608 execution to be accessible.
598 609
599 610 Note: we can not allow the actual FakeModule instances to be deleted,
600 611 because of how Python tears down modules (it hard-sets all their
601 612 references to None without regard for reference counts). This method
602 613 must therefore make a *copy* of the given namespace, to allow the
603 614 original module's __dict__ to be cleared and reused.
604 615
605 616
606 617 Parameters
607 618 ----------
608 619 ns : a namespace (a dict, typically)
609 620
610 621 fname : str
611 622 Filename associated with the namespace.
612 623
613 624 Examples
614 625 --------
615 626
616 627 In [10]: import IPython
617 628
618 629 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
619 630
620 631 In [12]: IPython.__file__ in _ip._main_ns_cache
621 632 Out[12]: True
622 633 """
623 634 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
624 635
625 636 def clear_main_mod_cache(self):
626 637 """Clear the cache of main modules.
627 638
628 639 Mainly for use by utilities like %reset.
629 640
630 641 Examples
631 642 --------
632 643
633 644 In [15]: import IPython
634 645
635 646 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
636 647
637 648 In [17]: len(_ip._main_ns_cache) > 0
638 649 Out[17]: True
639 650
640 651 In [18]: _ip.clear_main_mod_cache()
641 652
642 653 In [19]: len(_ip._main_ns_cache) == 0
643 654 Out[19]: True
644 655 """
645 656 self._main_ns_cache.clear()
646 657
647 658 #-------------------------------------------------------------------------
648 659 # Things related to debugging
649 660 #-------------------------------------------------------------------------
650 661
651 662 def init_pdb(self):
652 663 # Set calling of pdb on exceptions
653 664 # self.call_pdb is a property
654 665 self.call_pdb = self.pdb
655 666
656 667 def _get_call_pdb(self):
657 668 return self._call_pdb
658 669
659 670 def _set_call_pdb(self,val):
660 671
661 672 if val not in (0,1,False,True):
662 673 raise ValueError,'new call_pdb value must be boolean'
663 674
664 675 # store value in instance
665 676 self._call_pdb = val
666 677
667 678 # notify the actual exception handlers
668 679 self.InteractiveTB.call_pdb = val
669 680
670 681 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
671 682 'Control auto-activation of pdb at exceptions')
672 683
673 684 def debugger(self,force=False):
674 685 """Call the pydb/pdb debugger.
675 686
676 687 Keywords:
677 688
678 689 - force(False): by default, this routine checks the instance call_pdb
679 690 flag and does not actually invoke the debugger if the flag is false.
680 691 The 'force' option forces the debugger to activate even if the flag
681 692 is false.
682 693 """
683 694
684 695 if not (force or self.call_pdb):
685 696 return
686 697
687 698 if not hasattr(sys,'last_traceback'):
688 699 error('No traceback has been produced, nothing to debug.')
689 700 return
690 701
691 702 # use pydb if available
692 703 if debugger.has_pydb:
693 704 from pydb import pm
694 705 else:
695 706 # fallback to our internal debugger
696 707 pm = lambda : self.InteractiveTB.debugger(force=True)
697 708 self.history_saving_wrapper(pm)()
698 709
699 710 #-------------------------------------------------------------------------
700 711 # Things related to IPython's various namespaces
701 712 #-------------------------------------------------------------------------
702 713
703 714 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
704 715 # Create the namespace where the user will operate. user_ns is
705 716 # normally the only one used, and it is passed to the exec calls as
706 717 # the locals argument. But we do carry a user_global_ns namespace
707 718 # given as the exec 'globals' argument, This is useful in embedding
708 719 # situations where the ipython shell opens in a context where the
709 720 # distinction between locals and globals is meaningful. For
710 721 # non-embedded contexts, it is just the same object as the user_ns dict.
711 722
712 723 # FIXME. For some strange reason, __builtins__ is showing up at user
713 724 # level as a dict instead of a module. This is a manual fix, but I
714 725 # should really track down where the problem is coming from. Alex
715 726 # Schmolck reported this problem first.
716 727
717 728 # A useful post by Alex Martelli on this topic:
718 729 # Re: inconsistent value from __builtins__
719 730 # Von: Alex Martelli <aleaxit@yahoo.com>
720 731 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
721 732 # Gruppen: comp.lang.python
722 733
723 734 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
724 735 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
725 736 # > <type 'dict'>
726 737 # > >>> print type(__builtins__)
727 738 # > <type 'module'>
728 739 # > Is this difference in return value intentional?
729 740
730 741 # Well, it's documented that '__builtins__' can be either a dictionary
731 742 # or a module, and it's been that way for a long time. Whether it's
732 743 # intentional (or sensible), I don't know. In any case, the idea is
733 744 # that if you need to access the built-in namespace directly, you
734 745 # should start with "import __builtin__" (note, no 's') which will
735 746 # definitely give you a module. Yeah, it's somewhat confusing:-(.
736 747
737 748 # These routines return properly built dicts as needed by the rest of
738 749 # the code, and can also be used by extension writers to generate
739 750 # properly initialized namespaces.
740 751 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
741 752 user_global_ns)
742 753
743 754 # Assign namespaces
744 755 # This is the namespace where all normal user variables live
745 756 self.user_ns = user_ns
746 757 self.user_global_ns = user_global_ns
747 758
748 759 # An auxiliary namespace that checks what parts of the user_ns were
749 760 # loaded at startup, so we can list later only variables defined in
750 761 # actual interactive use. Since it is always a subset of user_ns, it
751 762 # doesn't need to be separately tracked in the ns_table.
752 763 self.user_ns_hidden = {}
753 764
754 765 # A namespace to keep track of internal data structures to prevent
755 766 # them from cluttering user-visible stuff. Will be updated later
756 767 self.internal_ns = {}
757 768
758 769 # Now that FakeModule produces a real module, we've run into a nasty
759 770 # problem: after script execution (via %run), the module where the user
760 771 # code ran is deleted. Now that this object is a true module (needed
761 772 # so docetst and other tools work correctly), the Python module
762 773 # teardown mechanism runs over it, and sets to None every variable
763 774 # present in that module. Top-level references to objects from the
764 775 # script survive, because the user_ns is updated with them. However,
765 776 # calling functions defined in the script that use other things from
766 777 # the script will fail, because the function's closure had references
767 778 # to the original objects, which are now all None. So we must protect
768 779 # these modules from deletion by keeping a cache.
769 780 #
770 781 # To avoid keeping stale modules around (we only need the one from the
771 782 # last run), we use a dict keyed with the full path to the script, so
772 783 # only the last version of the module is held in the cache. Note,
773 784 # however, that we must cache the module *namespace contents* (their
774 785 # __dict__). Because if we try to cache the actual modules, old ones
775 786 # (uncached) could be destroyed while still holding references (such as
776 787 # those held by GUI objects that tend to be long-lived)>
777 788 #
778 789 # The %reset command will flush this cache. See the cache_main_mod()
779 790 # and clear_main_mod_cache() methods for details on use.
780 791
781 792 # This is the cache used for 'main' namespaces
782 793 self._main_ns_cache = {}
783 794 # And this is the single instance of FakeModule whose __dict__ we keep
784 795 # copying and clearing for reuse on each %run
785 796 self._user_main_module = FakeModule()
786 797
787 798 # A table holding all the namespaces IPython deals with, so that
788 799 # introspection facilities can search easily.
789 800 self.ns_table = {'user':user_ns,
790 801 'user_global':user_global_ns,
791 802 'internal':self.internal_ns,
792 803 'builtin':__builtin__.__dict__
793 804 }
794 805
795 806 # Similarly, track all namespaces where references can be held and that
796 807 # we can safely clear (so it can NOT include builtin). This one can be
797 808 # a simple list.
798 809 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
799 810 self.internal_ns, self._main_ns_cache ]
800 811
801 812 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
802 813 """Return a valid local and global user interactive namespaces.
803 814
804 815 This builds a dict with the minimal information needed to operate as a
805 816 valid IPython user namespace, which you can pass to the various
806 817 embedding classes in ipython. The default implementation returns the
807 818 same dict for both the locals and the globals to allow functions to
808 819 refer to variables in the namespace. Customized implementations can
809 820 return different dicts. The locals dictionary can actually be anything
810 821 following the basic mapping protocol of a dict, but the globals dict
811 822 must be a true dict, not even a subclass. It is recommended that any
812 823 custom object for the locals namespace synchronize with the globals
813 824 dict somehow.
814 825
815 826 Raises TypeError if the provided globals namespace is not a true dict.
816 827
817 828 Parameters
818 829 ----------
819 830 user_ns : dict-like, optional
820 831 The current user namespace. The items in this namespace should
821 832 be included in the output. If None, an appropriate blank
822 833 namespace should be created.
823 834 user_global_ns : dict, optional
824 835 The current user global namespace. The items in this namespace
825 836 should be included in the output. If None, an appropriate
826 837 blank namespace should be created.
827 838
828 839 Returns
829 840 -------
830 841 A pair of dictionary-like object to be used as the local namespace
831 842 of the interpreter and a dict to be used as the global namespace.
832 843 """
833 844
834 845
835 846 # We must ensure that __builtin__ (without the final 's') is always
836 847 # available and pointing to the __builtin__ *module*. For more details:
837 848 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
838 849
839 850 if user_ns is None:
840 851 # Set __name__ to __main__ to better match the behavior of the
841 852 # normal interpreter.
842 853 user_ns = {'__name__' :'__main__',
843 854 '__builtin__' : __builtin__,
844 855 '__builtins__' : __builtin__,
845 856 }
846 857 else:
847 858 user_ns.setdefault('__name__','__main__')
848 859 user_ns.setdefault('__builtin__',__builtin__)
849 860 user_ns.setdefault('__builtins__',__builtin__)
850 861
851 862 if user_global_ns is None:
852 863 user_global_ns = user_ns
853 864 if type(user_global_ns) is not dict:
854 865 raise TypeError("user_global_ns must be a true dict; got %r"
855 866 % type(user_global_ns))
856 867
857 868 return user_ns, user_global_ns
858 869
859 870 def init_sys_modules(self):
860 871 # We need to insert into sys.modules something that looks like a
861 872 # module but which accesses the IPython namespace, for shelve and
862 873 # pickle to work interactively. Normally they rely on getting
863 874 # everything out of __main__, but for embedding purposes each IPython
864 875 # instance has its own private namespace, so we can't go shoving
865 876 # everything into __main__.
866 877
867 878 # note, however, that we should only do this for non-embedded
868 879 # ipythons, which really mimic the __main__.__dict__ with their own
869 880 # namespace. Embedded instances, on the other hand, should not do
870 881 # this because they need to manage the user local/global namespaces
871 882 # only, but they live within a 'normal' __main__ (meaning, they
872 883 # shouldn't overtake the execution environment of the script they're
873 884 # embedded in).
874 885
875 886 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
876 887
877 888 try:
878 889 main_name = self.user_ns['__name__']
879 890 except KeyError:
880 891 raise KeyError('user_ns dictionary MUST have a "__name__" key')
881 892 else:
882 893 sys.modules[main_name] = FakeModule(self.user_ns)
883 894
884 895 def init_user_ns(self):
885 896 """Initialize all user-visible namespaces to their minimum defaults.
886 897
887 898 Certain history lists are also initialized here, as they effectively
888 899 act as user namespaces.
889 900
890 901 Notes
891 902 -----
892 903 All data structures here are only filled in, they are NOT reset by this
893 904 method. If they were not empty before, data will simply be added to
894 905 therm.
895 906 """
896 907 # This function works in two parts: first we put a few things in
897 908 # user_ns, and we sync that contents into user_ns_hidden so that these
898 909 # initial variables aren't shown by %who. After the sync, we add the
899 910 # rest of what we *do* want the user to see with %who even on a new
900 911 # session (probably nothing, so theye really only see their own stuff)
901 912
902 913 # The user dict must *always* have a __builtin__ reference to the
903 914 # Python standard __builtin__ namespace, which must be imported.
904 915 # This is so that certain operations in prompt evaluation can be
905 916 # reliably executed with builtins. Note that we can NOT use
906 917 # __builtins__ (note the 's'), because that can either be a dict or a
907 918 # module, and can even mutate at runtime, depending on the context
908 919 # (Python makes no guarantees on it). In contrast, __builtin__ is
909 920 # always a module object, though it must be explicitly imported.
910 921
911 922 # For more details:
912 923 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
913 924 ns = dict(__builtin__ = __builtin__)
914 925
915 926 # Put 'help' in the user namespace
916 927 try:
917 928 from site import _Helper
918 929 ns['help'] = _Helper()
919 930 except ImportError:
920 931 warn('help() not available - check site.py')
921 932
922 933 # make global variables for user access to the histories
923 934 ns['_ih'] = self.input_hist
924 935 ns['_oh'] = self.output_hist
925 936 ns['_dh'] = self.dir_hist
926 937
927 938 ns['_sh'] = shadowns
928 939
929 940 # user aliases to input and output histories. These shouldn't show up
930 941 # in %who, as they can have very large reprs.
931 942 ns['In'] = self.input_hist
932 943 ns['Out'] = self.output_hist
933 944
934 945 # Store myself as the public api!!!
935 946 ns['get_ipython'] = self.get_ipython
936 947
937 948 # Sync what we've added so far to user_ns_hidden so these aren't seen
938 949 # by %who
939 950 self.user_ns_hidden.update(ns)
940 951
941 952 # Anything put into ns now would show up in %who. Think twice before
942 953 # putting anything here, as we really want %who to show the user their
943 954 # stuff, not our variables.
944 955
945 956 # Finally, update the real user's namespace
946 957 self.user_ns.update(ns)
947 958
948 959
949 960 def reset(self):
950 961 """Clear all internal namespaces.
951 962
952 963 Note that this is much more aggressive than %reset, since it clears
953 964 fully all namespaces, as well as all input/output lists.
954 965 """
955 966 for ns in self.ns_refs_table:
956 967 ns.clear()
957 968
958 969 self.alias_manager.clear_aliases()
959 970
960 971 # Clear input and output histories
961 972 self.input_hist[:] = []
962 973 self.input_hist_raw[:] = []
963 974 self.output_hist.clear()
964 975
965 976 # Restore the user namespaces to minimal usability
966 977 self.init_user_ns()
967 978
968 979 # Restore the default and user aliases
969 980 self.alias_manager.init_aliases()
970 981
971 982 def reset_selective(self, regex=None):
972 983 """Clear selective variables from internal namespaces based on a
973 984 specified regular expression.
974 985
975 986 Parameters
976 987 ----------
977 988 regex : string or compiled pattern, optional
978 989 A regular expression pattern that will be used in searching
979 990 variable names in the users namespaces.
980 991 """
981 992 if regex is not None:
982 993 try:
983 994 m = re.compile(regex)
984 995 except TypeError:
985 996 raise TypeError('regex must be a string or compiled pattern')
986 997 # Search for keys in each namespace that match the given regex
987 998 # If a match is found, delete the key/value pair.
988 999 for ns in self.ns_refs_table:
989 1000 for var in ns:
990 1001 if m.search(var):
991 1002 del ns[var]
992 1003
993 1004 def push(self, variables, interactive=True):
994 1005 """Inject a group of variables into the IPython user namespace.
995 1006
996 1007 Parameters
997 1008 ----------
998 1009 variables : dict, str or list/tuple of str
999 1010 The variables to inject into the user's namespace. If a dict, a
1000 1011 simple update is done. If a str, the string is assumed to have
1001 1012 variable names separated by spaces. A list/tuple of str can also
1002 1013 be used to give the variable names. If just the variable names are
1003 1014 give (list/tuple/str) then the variable values looked up in the
1004 1015 callers frame.
1005 1016 interactive : bool
1006 1017 If True (default), the variables will be listed with the ``who``
1007 1018 magic.
1008 1019 """
1009 1020 vdict = None
1010 1021
1011 1022 # We need a dict of name/value pairs to do namespace updates.
1012 1023 if isinstance(variables, dict):
1013 1024 vdict = variables
1014 1025 elif isinstance(variables, (basestring, list, tuple)):
1015 1026 if isinstance(variables, basestring):
1016 1027 vlist = variables.split()
1017 1028 else:
1018 1029 vlist = variables
1019 1030 vdict = {}
1020 1031 cf = sys._getframe(1)
1021 1032 for name in vlist:
1022 1033 try:
1023 1034 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1024 1035 except:
1025 1036 print ('Could not get variable %s from %s' %
1026 1037 (name,cf.f_code.co_name))
1027 1038 else:
1028 1039 raise ValueError('variables must be a dict/str/list/tuple')
1029 1040
1030 1041 # Propagate variables to user namespace
1031 1042 self.user_ns.update(vdict)
1032 1043
1033 1044 # And configure interactive visibility
1034 1045 config_ns = self.user_ns_hidden
1035 1046 if interactive:
1036 1047 for name, val in vdict.iteritems():
1037 1048 config_ns.pop(name, None)
1038 1049 else:
1039 1050 for name,val in vdict.iteritems():
1040 1051 config_ns[name] = val
1041 1052
1042 1053 #-------------------------------------------------------------------------
1043 1054 # Things related to object introspection
1044 1055 #-------------------------------------------------------------------------
1045 1056 def _ofind(self, oname, namespaces=None):
1046 1057 """Find an object in the available namespaces.
1047 1058
1048 1059 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1049 1060
1050 1061 Has special code to detect magic functions.
1051 1062 """
1052 1063 #oname = oname.strip()
1053 1064 #print '1- oname: <%r>' % oname # dbg
1054 1065 try:
1055 1066 oname = oname.strip().encode('ascii')
1056 1067 #print '2- oname: <%r>' % oname # dbg
1057 1068 except UnicodeEncodeError:
1058 1069 print 'Python identifiers can only contain ascii characters.'
1059 1070 return dict(found=False)
1060 1071
1061 1072 alias_ns = None
1062 1073 if namespaces is None:
1063 1074 # Namespaces to search in:
1064 1075 # Put them in a list. The order is important so that we
1065 1076 # find things in the same order that Python finds them.
1066 1077 namespaces = [ ('Interactive', self.user_ns),
1067 1078 ('IPython internal', self.internal_ns),
1068 1079 ('Python builtin', __builtin__.__dict__),
1069 1080 ('Alias', self.alias_manager.alias_table),
1070 1081 ]
1071 1082 alias_ns = self.alias_manager.alias_table
1072 1083
1073 1084 # initialize results to 'null'
1074 1085 found = False; obj = None; ospace = None; ds = None;
1075 1086 ismagic = False; isalias = False; parent = None
1076 1087
1077 1088 # We need to special-case 'print', which as of python2.6 registers as a
1078 1089 # function but should only be treated as one if print_function was
1079 1090 # loaded with a future import. In this case, just bail.
1080 1091 if (oname == 'print' and not (self.compile.compiler.flags &
1081 1092 __future__.CO_FUTURE_PRINT_FUNCTION)):
1082 1093 return {'found':found, 'obj':obj, 'namespace':ospace,
1083 1094 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1084 1095
1085 1096 # Look for the given name by splitting it in parts. If the head is
1086 1097 # found, then we look for all the remaining parts as members, and only
1087 1098 # declare success if we can find them all.
1088 1099 oname_parts = oname.split('.')
1089 1100 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1090 1101 for nsname,ns in namespaces:
1091 1102 try:
1092 1103 obj = ns[oname_head]
1093 1104 except KeyError:
1094 1105 continue
1095 1106 else:
1096 1107 #print 'oname_rest:', oname_rest # dbg
1097 1108 for part in oname_rest:
1098 1109 try:
1099 1110 parent = obj
1100 1111 obj = getattr(obj,part)
1101 1112 except:
1102 1113 # Blanket except b/c some badly implemented objects
1103 1114 # allow __getattr__ to raise exceptions other than
1104 1115 # AttributeError, which then crashes IPython.
1105 1116 break
1106 1117 else:
1107 1118 # If we finish the for loop (no break), we got all members
1108 1119 found = True
1109 1120 ospace = nsname
1110 1121 if ns == alias_ns:
1111 1122 isalias = True
1112 1123 break # namespace loop
1113 1124
1114 1125 # Try to see if it's magic
1115 1126 if not found:
1116 1127 if oname.startswith(ESC_MAGIC):
1117 1128 oname = oname[1:]
1118 1129 obj = getattr(self,'magic_'+oname,None)
1119 1130 if obj is not None:
1120 1131 found = True
1121 1132 ospace = 'IPython internal'
1122 1133 ismagic = True
1123 1134
1124 1135 # Last try: special-case some literals like '', [], {}, etc:
1125 1136 if not found and oname_head in ["''",'""','[]','{}','()']:
1126 1137 obj = eval(oname_head)
1127 1138 found = True
1128 1139 ospace = 'Interactive'
1129 1140
1130 1141 return {'found':found, 'obj':obj, 'namespace':ospace,
1131 1142 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1132 1143
1133 1144 def _ofind_property(self, oname, info):
1134 1145 """Second part of object finding, to look for property details."""
1135 1146 if info.found:
1136 1147 # Get the docstring of the class property if it exists.
1137 1148 path = oname.split('.')
1138 1149 root = '.'.join(path[:-1])
1139 1150 if info.parent is not None:
1140 1151 try:
1141 1152 target = getattr(info.parent, '__class__')
1142 1153 # The object belongs to a class instance.
1143 1154 try:
1144 1155 target = getattr(target, path[-1])
1145 1156 # The class defines the object.
1146 1157 if isinstance(target, property):
1147 1158 oname = root + '.__class__.' + path[-1]
1148 1159 info = Struct(self._ofind(oname))
1149 1160 except AttributeError: pass
1150 1161 except AttributeError: pass
1151 1162
1152 1163 # We return either the new info or the unmodified input if the object
1153 1164 # hadn't been found
1154 1165 return info
1155 1166
1156 1167 def _object_find(self, oname, namespaces=None):
1157 1168 """Find an object and return a struct with info about it."""
1158 1169 inf = Struct(self._ofind(oname, namespaces))
1159 1170 return Struct(self._ofind_property(oname, inf))
1160 1171
1161 1172 def _inspect(self, meth, oname, namespaces=None, **kw):
1162 1173 """Generic interface to the inspector system.
1163 1174
1164 1175 This function is meant to be called by pdef, pdoc & friends."""
1165 1176 info = self._object_find(oname)
1166 1177 if info.found:
1167 1178 pmethod = getattr(self.inspector, meth)
1168 1179 formatter = format_screen if info.ismagic else None
1169 1180 if meth == 'pdoc':
1170 1181 pmethod(info.obj, oname, formatter)
1171 1182 elif meth == 'pinfo':
1172 1183 pmethod(info.obj, oname, formatter, info, **kw)
1173 1184 else:
1174 1185 pmethod(info.obj, oname)
1175 1186 else:
1176 1187 print 'Object `%s` not found.' % oname
1177 1188 return 'not found' # so callers can take other action
1178 1189
1179 1190 def object_inspect(self, oname):
1180 1191 info = self._object_find(oname)
1181 1192 if info.found:
1182 1193 return self.inspector.info(info.obj, info=info)
1183 1194 else:
1184 1195 return oinspect.mk_object_info({'found' : False})
1185 1196
1186 1197 #-------------------------------------------------------------------------
1187 1198 # Things related to history management
1188 1199 #-------------------------------------------------------------------------
1189 1200
1190 1201 def init_history(self):
1191 1202 # List of input with multi-line handling.
1192 1203 self.input_hist = InputList()
1193 1204 # This one will hold the 'raw' input history, without any
1194 1205 # pre-processing. This will allow users to retrieve the input just as
1195 1206 # it was exactly typed in by the user, with %hist -r.
1196 1207 self.input_hist_raw = InputList()
1197 1208
1198 1209 # list of visited directories
1199 1210 try:
1200 1211 self.dir_hist = [os.getcwd()]
1201 1212 except OSError:
1202 1213 self.dir_hist = []
1203 1214
1204 1215 # dict of output history
1205 1216 self.output_hist = {}
1206 1217
1207 1218 # Now the history file
1208 1219 if self.profile:
1209 1220 histfname = 'history-%s' % self.profile
1210 1221 else:
1211 1222 histfname = 'history'
1212 1223 self.histfile = os.path.join(self.ipython_dir, histfname)
1213 1224
1214 1225 # Fill the history zero entry, user counter starts at 1
1215 1226 self.input_hist.append('\n')
1216 1227 self.input_hist_raw.append('\n')
1217 1228
1218 1229 def init_shadow_hist(self):
1219 1230 try:
1220 1231 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1221 1232 except exceptions.UnicodeDecodeError:
1222 1233 print "Your ipython_dir can't be decoded to unicode!"
1223 1234 print "Please set HOME environment variable to something that"
1224 1235 print r"only has ASCII characters, e.g. c:\home"
1225 1236 print "Now it is", self.ipython_dir
1226 1237 sys.exit()
1227 1238 self.shadowhist = ipcorehist.ShadowHist(self.db)
1228 1239
1229 1240 def savehist(self):
1230 1241 """Save input history to a file (via readline library)."""
1231 1242
1232 1243 try:
1233 1244 self.readline.write_history_file(self.histfile)
1234 1245 except:
1235 1246 print 'Unable to save IPython command history to file: ' + \
1236 1247 `self.histfile`
1237 1248
1238 1249 def reloadhist(self):
1239 1250 """Reload the input history from disk file."""
1240 1251
1241 1252 try:
1242 1253 self.readline.clear_history()
1243 1254 self.readline.read_history_file(self.shell.histfile)
1244 1255 except AttributeError:
1245 1256 pass
1246 1257
1247 1258 def history_saving_wrapper(self, func):
1248 1259 """ Wrap func for readline history saving
1249 1260
1250 1261 Convert func into callable that saves & restores
1251 1262 history around the call """
1252 1263
1253 1264 if self.has_readline:
1254 1265 from IPython.utils import rlineimpl as readline
1255 1266 else:
1256 1267 return func
1257 1268
1258 1269 def wrapper():
1259 1270 self.savehist()
1260 1271 try:
1261 1272 func()
1262 1273 finally:
1263 1274 readline.read_history_file(self.histfile)
1264 1275 return wrapper
1265 1276
1266 1277 def get_history(self, index=None, raw=False, output=True):
1267 1278 """Get the history list.
1268 1279
1269 1280 Get the input and output history.
1270 1281
1271 1282 Parameters
1272 1283 ----------
1273 1284 index : n or (n1, n2) or None
1274 1285 If n, then the last entries. If a tuple, then all in
1275 1286 range(n1, n2). If None, then all entries. Raises IndexError if
1276 1287 the format of index is incorrect.
1277 1288 raw : bool
1278 1289 If True, return the raw input.
1279 1290 output : bool
1280 1291 If True, then return the output as well.
1281 1292
1282 1293 Returns
1283 1294 -------
1284 1295 If output is True, then return a dict of tuples, keyed by the prompt
1285 1296 numbers and with values of (input, output). If output is False, then
1286 1297 a dict, keyed by the prompt number with the values of input. Raises
1287 1298 IndexError if no history is found.
1288 1299 """
1289 1300 if raw:
1290 1301 input_hist = self.input_hist_raw
1291 1302 else:
1292 1303 input_hist = self.input_hist
1293 1304 if output:
1294 1305 output_hist = self.user_ns['Out']
1295 1306 n = len(input_hist)
1296 1307 if index is None:
1297 1308 start=0; stop=n
1298 1309 elif isinstance(index, int):
1299 1310 start=n-index; stop=n
1300 1311 elif isinstance(index, tuple) and len(index) == 2:
1301 1312 start=index[0]; stop=index[1]
1302 1313 else:
1303 1314 raise IndexError('Not a valid index for the input history: %r'
1304 1315 % index)
1305 1316 hist = {}
1306 1317 for i in range(start, stop):
1307 1318 if output:
1308 1319 hist[i] = (input_hist[i], output_hist.get(i))
1309 1320 else:
1310 1321 hist[i] = input_hist[i]
1311 1322 if len(hist)==0:
1312 1323 raise IndexError('No history for range of indices: %r' % index)
1313 1324 return hist
1314 1325
1315 1326 #-------------------------------------------------------------------------
1316 1327 # Things related to exception handling and tracebacks (not debugging)
1317 1328 #-------------------------------------------------------------------------
1318 1329
1319 1330 def init_traceback_handlers(self, custom_exceptions):
1320 1331 # Syntax error handler.
1321 1332 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1322 1333
1323 1334 # The interactive one is initialized with an offset, meaning we always
1324 1335 # want to remove the topmost item in the traceback, which is our own
1325 1336 # internal code. Valid modes: ['Plain','Context','Verbose']
1326 1337 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1327 1338 color_scheme='NoColor',
1328 1339 tb_offset = 1)
1329 1340
1330 1341 # The instance will store a pointer to the system-wide exception hook,
1331 1342 # so that runtime code (such as magics) can access it. This is because
1332 1343 # during the read-eval loop, it may get temporarily overwritten.
1333 1344 self.sys_excepthook = sys.excepthook
1334 1345
1335 1346 # and add any custom exception handlers the user may have specified
1336 1347 self.set_custom_exc(*custom_exceptions)
1337 1348
1338 1349 # Set the exception mode
1339 1350 self.InteractiveTB.set_mode(mode=self.xmode)
1340 1351
1341 1352 def set_custom_exc(self, exc_tuple, handler):
1342 1353 """set_custom_exc(exc_tuple,handler)
1343 1354
1344 1355 Set a custom exception handler, which will be called if any of the
1345 1356 exceptions in exc_tuple occur in the mainloop (specifically, in the
1346 1357 runcode() method.
1347 1358
1348 1359 Inputs:
1349 1360
1350 1361 - exc_tuple: a *tuple* of valid exceptions to call the defined
1351 1362 handler for. It is very important that you use a tuple, and NOT A
1352 1363 LIST here, because of the way Python's except statement works. If
1353 1364 you only want to trap a single exception, use a singleton tuple:
1354 1365
1355 1366 exc_tuple == (MyCustomException,)
1356 1367
1357 1368 - handler: this must be defined as a function with the following
1358 1369 basic interface::
1359 1370
1360 1371 def my_handler(self, etype, value, tb, tb_offset=None)
1361 1372 ...
1362 1373 # The return value must be
1363 1374 return structured_traceback
1364 1375
1365 1376 This will be made into an instance method (via new.instancemethod)
1366 1377 of IPython itself, and it will be called if any of the exceptions
1367 1378 listed in the exc_tuple are caught. If the handler is None, an
1368 1379 internal basic one is used, which just prints basic info.
1369 1380
1370 1381 WARNING: by putting in your own exception handler into IPython's main
1371 1382 execution loop, you run a very good chance of nasty crashes. This
1372 1383 facility should only be used if you really know what you are doing."""
1373 1384
1374 1385 assert type(exc_tuple)==type(()) , \
1375 1386 "The custom exceptions must be given AS A TUPLE."
1376 1387
1377 1388 def dummy_handler(self,etype,value,tb):
1378 1389 print '*** Simple custom exception handler ***'
1379 1390 print 'Exception type :',etype
1380 1391 print 'Exception value:',value
1381 1392 print 'Traceback :',tb
1382 1393 print 'Source code :','\n'.join(self.buffer)
1383 1394
1384 1395 if handler is None: handler = dummy_handler
1385 1396
1386 1397 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1387 1398 self.custom_exceptions = exc_tuple
1388 1399
1389 1400 def excepthook(self, etype, value, tb):
1390 1401 """One more defense for GUI apps that call sys.excepthook.
1391 1402
1392 1403 GUI frameworks like wxPython trap exceptions and call
1393 1404 sys.excepthook themselves. I guess this is a feature that
1394 1405 enables them to keep running after exceptions that would
1395 1406 otherwise kill their mainloop. This is a bother for IPython
1396 1407 which excepts to catch all of the program exceptions with a try:
1397 1408 except: statement.
1398 1409
1399 1410 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1400 1411 any app directly invokes sys.excepthook, it will look to the user like
1401 1412 IPython crashed. In order to work around this, we can disable the
1402 1413 CrashHandler and replace it with this excepthook instead, which prints a
1403 1414 regular traceback using our InteractiveTB. In this fashion, apps which
1404 1415 call sys.excepthook will generate a regular-looking exception from
1405 1416 IPython, and the CrashHandler will only be triggered by real IPython
1406 1417 crashes.
1407 1418
1408 1419 This hook should be used sparingly, only in places which are not likely
1409 1420 to be true IPython errors.
1410 1421 """
1411 1422 self.showtraceback((etype,value,tb),tb_offset=0)
1412 1423
1413 1424 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1414 1425 exception_only=False):
1415 1426 """Display the exception that just occurred.
1416 1427
1417 1428 If nothing is known about the exception, this is the method which
1418 1429 should be used throughout the code for presenting user tracebacks,
1419 1430 rather than directly invoking the InteractiveTB object.
1420 1431
1421 1432 A specific showsyntaxerror() also exists, but this method can take
1422 1433 care of calling it if needed, so unless you are explicitly catching a
1423 1434 SyntaxError exception, don't try to analyze the stack manually and
1424 1435 simply call this method."""
1425 1436
1426 1437 try:
1427 1438 if exc_tuple is None:
1428 1439 etype, value, tb = sys.exc_info()
1429 1440 else:
1430 1441 etype, value, tb = exc_tuple
1431 1442
1432 1443 if etype is None:
1433 1444 if hasattr(sys, 'last_type'):
1434 1445 etype, value, tb = sys.last_type, sys.last_value, \
1435 1446 sys.last_traceback
1436 1447 else:
1437 1448 self.write_err('No traceback available to show.\n')
1438 1449 return
1439 1450
1440 1451 if etype is SyntaxError:
1441 1452 # Though this won't be called by syntax errors in the input
1442 1453 # line, there may be SyntaxError cases whith imported code.
1443 1454 self.showsyntaxerror(filename)
1444 1455 elif etype is UsageError:
1445 1456 print "UsageError:", value
1446 1457 else:
1447 1458 # WARNING: these variables are somewhat deprecated and not
1448 1459 # necessarily safe to use in a threaded environment, but tools
1449 1460 # like pdb depend on their existence, so let's set them. If we
1450 1461 # find problems in the field, we'll need to revisit their use.
1451 1462 sys.last_type = etype
1452 1463 sys.last_value = value
1453 1464 sys.last_traceback = tb
1454 1465
1455 1466 if etype in self.custom_exceptions:
1456 1467 # FIXME: Old custom traceback objects may just return a
1457 1468 # string, in that case we just put it into a list
1458 1469 stb = self.CustomTB(etype, value, tb, tb_offset)
1459 1470 if isinstance(ctb, basestring):
1460 1471 stb = [stb]
1461 1472 else:
1462 1473 if exception_only:
1463 1474 stb = ['An exception has occurred, use %tb to see '
1464 1475 'the full traceback.\n']
1465 1476 stb.extend(self.InteractiveTB.get_exception_only(etype,
1466 1477 value))
1467 1478 else:
1468 1479 stb = self.InteractiveTB.structured_traceback(etype,
1469 1480 value, tb, tb_offset=tb_offset)
1470 1481 # FIXME: the pdb calling should be done by us, not by
1471 1482 # the code computing the traceback.
1472 1483 if self.InteractiveTB.call_pdb:
1473 1484 # pdb mucks up readline, fix it back
1474 1485 self.set_readline_completer()
1475 1486
1476 1487 # Actually show the traceback
1477 1488 self._showtraceback(etype, value, stb)
1478 1489
1479 1490 except KeyboardInterrupt:
1480 1491 self.write_err("\nKeyboardInterrupt\n")
1481 1492
1482 1493 def _showtraceback(self, etype, evalue, stb):
1483 1494 """Actually show a traceback.
1484 1495
1485 1496 Subclasses may override this method to put the traceback on a different
1486 1497 place, like a side channel.
1487 1498 """
1488 1499 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1489 1500
1490 1501 def showsyntaxerror(self, filename=None):
1491 1502 """Display the syntax error that just occurred.
1492 1503
1493 1504 This doesn't display a stack trace because there isn't one.
1494 1505
1495 1506 If a filename is given, it is stuffed in the exception instead
1496 1507 of what was there before (because Python's parser always uses
1497 1508 "<string>" when reading from a string).
1498 1509 """
1499 1510 etype, value, last_traceback = sys.exc_info()
1500 1511
1501 1512 # See note about these variables in showtraceback() above
1502 1513 sys.last_type = etype
1503 1514 sys.last_value = value
1504 1515 sys.last_traceback = last_traceback
1505 1516
1506 1517 if filename and etype is SyntaxError:
1507 1518 # Work hard to stuff the correct filename in the exception
1508 1519 try:
1509 1520 msg, (dummy_filename, lineno, offset, line) = value
1510 1521 except:
1511 1522 # Not the format we expect; leave it alone
1512 1523 pass
1513 1524 else:
1514 1525 # Stuff in the right filename
1515 1526 try:
1516 1527 # Assume SyntaxError is a class exception
1517 1528 value = SyntaxError(msg, (filename, lineno, offset, line))
1518 1529 except:
1519 1530 # If that failed, assume SyntaxError is a string
1520 1531 value = msg, (filename, lineno, offset, line)
1521 1532 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1522 1533 self._showtraceback(etype, value, stb)
1523 1534
1524 1535 #-------------------------------------------------------------------------
1525 1536 # Things related to readline
1526 1537 #-------------------------------------------------------------------------
1527 1538
1528 1539 def init_readline(self):
1529 1540 """Command history completion/saving/reloading."""
1530 1541
1531 1542 if self.readline_use:
1532 1543 import IPython.utils.rlineimpl as readline
1533 1544
1534 1545 self.rl_next_input = None
1535 1546 self.rl_do_indent = False
1536 1547
1537 1548 if not self.readline_use or not readline.have_readline:
1538 1549 self.has_readline = False
1539 1550 self.readline = None
1540 1551 # Set a number of methods that depend on readline to be no-op
1541 1552 self.savehist = no_op
1542 1553 self.reloadhist = no_op
1543 1554 self.set_readline_completer = no_op
1544 1555 self.set_custom_completer = no_op
1545 1556 self.set_completer_frame = no_op
1546 1557 warn('Readline services not available or not loaded.')
1547 1558 else:
1548 1559 self.has_readline = True
1549 1560 self.readline = readline
1550 1561 sys.modules['readline'] = readline
1551 1562
1552 1563 # Platform-specific configuration
1553 1564 if os.name == 'nt':
1554 1565 # FIXME - check with Frederick to see if we can harmonize
1555 1566 # naming conventions with pyreadline to avoid this
1556 1567 # platform-dependent check
1557 1568 self.readline_startup_hook = readline.set_pre_input_hook
1558 1569 else:
1559 1570 self.readline_startup_hook = readline.set_startup_hook
1560 1571
1561 1572 # Load user's initrc file (readline config)
1562 1573 # Or if libedit is used, load editrc.
1563 1574 inputrc_name = os.environ.get('INPUTRC')
1564 1575 if inputrc_name is None:
1565 1576 home_dir = get_home_dir()
1566 1577 if home_dir is not None:
1567 1578 inputrc_name = '.inputrc'
1568 1579 if readline.uses_libedit:
1569 1580 inputrc_name = '.editrc'
1570 1581 inputrc_name = os.path.join(home_dir, inputrc_name)
1571 1582 if os.path.isfile(inputrc_name):
1572 1583 try:
1573 1584 readline.read_init_file(inputrc_name)
1574 1585 except:
1575 1586 warn('Problems reading readline initialization file <%s>'
1576 1587 % inputrc_name)
1577 1588
1578 1589 # Configure readline according to user's prefs
1579 1590 # This is only done if GNU readline is being used. If libedit
1580 1591 # is being used (as on Leopard) the readline config is
1581 1592 # not run as the syntax for libedit is different.
1582 1593 if not readline.uses_libedit:
1583 1594 for rlcommand in self.readline_parse_and_bind:
1584 1595 #print "loading rl:",rlcommand # dbg
1585 1596 readline.parse_and_bind(rlcommand)
1586 1597
1587 1598 # Remove some chars from the delimiters list. If we encounter
1588 1599 # unicode chars, discard them.
1589 1600 delims = readline.get_completer_delims().encode("ascii", "ignore")
1590 1601 delims = delims.translate(string._idmap,
1591 1602 self.readline_remove_delims)
1592 1603 delims = delims.replace(ESC_MAGIC, '')
1593 1604 readline.set_completer_delims(delims)
1594 1605 # otherwise we end up with a monster history after a while:
1595 1606 readline.set_history_length(1000)
1596 1607 try:
1597 1608 #print '*** Reading readline history' # dbg
1598 1609 readline.read_history_file(self.histfile)
1599 1610 except IOError:
1600 1611 pass # It doesn't exist yet.
1601 1612
1602 1613 # If we have readline, we want our history saved upon ipython
1603 1614 # exiting.
1604 1615 atexit.register(self.savehist)
1605 1616
1606 1617 # Configure auto-indent for all platforms
1607 1618 self.set_autoindent(self.autoindent)
1608 1619
1609 1620 def set_next_input(self, s):
1610 1621 """ Sets the 'default' input string for the next command line.
1611 1622
1612 1623 Requires readline.
1613 1624
1614 1625 Example:
1615 1626
1616 1627 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1617 1628 [D:\ipython]|2> Hello Word_ # cursor is here
1618 1629 """
1619 1630
1620 1631 self.rl_next_input = s
1621 1632
1622 1633 # Maybe move this to the terminal subclass?
1623 1634 def pre_readline(self):
1624 1635 """readline hook to be used at the start of each line.
1625 1636
1626 1637 Currently it handles auto-indent only."""
1627 1638
1628 1639 if self.rl_do_indent:
1629 1640 self.readline.insert_text(self._indent_current_str())
1630 1641 if self.rl_next_input is not None:
1631 1642 self.readline.insert_text(self.rl_next_input)
1632 1643 self.rl_next_input = None
1633 1644
1634 1645 def _indent_current_str(self):
1635 1646 """return the current level of indentation as a string"""
1636 1647 return self.indent_current_nsp * ' '
1637 1648
1638 1649 #-------------------------------------------------------------------------
1639 1650 # Things related to text completion
1640 1651 #-------------------------------------------------------------------------
1641 1652
1642 1653 def init_completer(self):
1643 1654 """Initialize the completion machinery.
1644 1655
1645 1656 This creates completion machinery that can be used by client code,
1646 1657 either interactively in-process (typically triggered by the readline
1647 1658 library), programatically (such as in test suites) or out-of-prcess
1648 1659 (typically over the network by remote frontends).
1649 1660 """
1650 1661 from IPython.core.completer import IPCompleter
1651 1662 from IPython.core.completerlib import (module_completer,
1652 1663 magic_run_completer, cd_completer)
1653 1664
1654 1665 self.Completer = IPCompleter(self,
1655 1666 self.user_ns,
1656 1667 self.user_global_ns,
1657 1668 self.readline_omit__names,
1658 1669 self.alias_manager.alias_table,
1659 1670 self.has_readline)
1660 1671
1661 1672 # Add custom completers to the basic ones built into IPCompleter
1662 1673 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1663 1674 self.strdispatchers['complete_command'] = sdisp
1664 1675 self.Completer.custom_completers = sdisp
1665 1676
1666 1677 self.set_hook('complete_command', module_completer, str_key = 'import')
1667 1678 self.set_hook('complete_command', module_completer, str_key = 'from')
1668 1679 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1669 1680 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1670 1681
1671 1682 # Only configure readline if we truly are using readline. IPython can
1672 1683 # do tab-completion over the network, in GUIs, etc, where readline
1673 1684 # itself may be absent
1674 1685 if self.has_readline:
1675 1686 self.set_readline_completer()
1676 1687
1677 1688 def complete(self, text, line=None, cursor_pos=None):
1678 1689 """Return the completed text and a list of completions.
1679 1690
1680 1691 Parameters
1681 1692 ----------
1682 1693
1683 1694 text : string
1684 1695 A string of text to be completed on. It can be given as empty and
1685 1696 instead a line/position pair are given. In this case, the
1686 1697 completer itself will split the line like readline does.
1687 1698
1688 1699 line : string, optional
1689 1700 The complete line that text is part of.
1690 1701
1691 1702 cursor_pos : int, optional
1692 1703 The position of the cursor on the input line.
1693 1704
1694 1705 Returns
1695 1706 -------
1696 1707 text : string
1697 1708 The actual text that was completed.
1698 1709
1699 1710 matches : list
1700 1711 A sorted list with all possible completions.
1701 1712
1702 1713 The optional arguments allow the completion to take more context into
1703 1714 account, and are part of the low-level completion API.
1704 1715
1705 1716 This is a wrapper around the completion mechanism, similar to what
1706 1717 readline does at the command line when the TAB key is hit. By
1707 1718 exposing it as a method, it can be used by other non-readline
1708 1719 environments (such as GUIs) for text completion.
1709 1720
1710 1721 Simple usage example:
1711 1722
1712 1723 In [1]: x = 'hello'
1713 1724
1714 1725 In [2]: _ip.complete('x.l')
1715 1726 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1716 1727 """
1717 1728
1718 1729 # Inject names into __builtin__ so we can complete on the added names.
1719 1730 with self.builtin_trap:
1720 1731 return self.Completer.complete(text, line, cursor_pos)
1721 1732
1722 1733 def set_custom_completer(self, completer, pos=0):
1723 1734 """Adds a new custom completer function.
1724 1735
1725 1736 The position argument (defaults to 0) is the index in the completers
1726 1737 list where you want the completer to be inserted."""
1727 1738
1728 1739 newcomp = new.instancemethod(completer,self.Completer,
1729 1740 self.Completer.__class__)
1730 1741 self.Completer.matchers.insert(pos,newcomp)
1731 1742
1732 1743 def set_readline_completer(self):
1733 1744 """Reset readline's completer to be our own."""
1734 1745 self.readline.set_completer(self.Completer.rlcomplete)
1735 1746
1736 1747 def set_completer_frame(self, frame=None):
1737 1748 """Set the frame of the completer."""
1738 1749 if frame:
1739 1750 self.Completer.namespace = frame.f_locals
1740 1751 self.Completer.global_namespace = frame.f_globals
1741 1752 else:
1742 1753 self.Completer.namespace = self.user_ns
1743 1754 self.Completer.global_namespace = self.user_global_ns
1744 1755
1745 1756 #-------------------------------------------------------------------------
1746 1757 # Things related to magics
1747 1758 #-------------------------------------------------------------------------
1748 1759
1749 1760 def init_magics(self):
1750 1761 # FIXME: Move the color initialization to the DisplayHook, which
1751 1762 # should be split into a prompt manager and displayhook. We probably
1752 1763 # even need a centralize colors management object.
1753 1764 self.magic_colors(self.colors)
1754 1765 # History was moved to a separate module
1755 1766 from . import history
1756 1767 history.init_ipython(self)
1757 1768
1758 1769 def magic(self,arg_s):
1759 1770 """Call a magic function by name.
1760 1771
1761 1772 Input: a string containing the name of the magic function to call and
1762 1773 any additional arguments to be passed to the magic.
1763 1774
1764 1775 magic('name -opt foo bar') is equivalent to typing at the ipython
1765 1776 prompt:
1766 1777
1767 1778 In[1]: %name -opt foo bar
1768 1779
1769 1780 To call a magic without arguments, simply use magic('name').
1770 1781
1771 1782 This provides a proper Python function to call IPython's magics in any
1772 1783 valid Python code you can type at the interpreter, including loops and
1773 1784 compound statements.
1774 1785 """
1775 1786 args = arg_s.split(' ',1)
1776 1787 magic_name = args[0]
1777 1788 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1778 1789
1779 1790 try:
1780 1791 magic_args = args[1]
1781 1792 except IndexError:
1782 1793 magic_args = ''
1783 1794 fn = getattr(self,'magic_'+magic_name,None)
1784 1795 if fn is None:
1785 1796 error("Magic function `%s` not found." % magic_name)
1786 1797 else:
1787 1798 magic_args = self.var_expand(magic_args,1)
1788 1799 with nested(self.builtin_trap,):
1789 1800 result = fn(magic_args)
1790 1801 return result
1791 1802
1792 1803 def define_magic(self, magicname, func):
1793 1804 """Expose own function as magic function for ipython
1794 1805
1795 1806 def foo_impl(self,parameter_s=''):
1796 1807 'My very own magic!. (Use docstrings, IPython reads them).'
1797 1808 print 'Magic function. Passed parameter is between < >:'
1798 1809 print '<%s>' % parameter_s
1799 1810 print 'The self object is:',self
1800 1811
1801 1812 self.define_magic('foo',foo_impl)
1802 1813 """
1803 1814
1804 1815 import new
1805 1816 im = new.instancemethod(func,self, self.__class__)
1806 1817 old = getattr(self, "magic_" + magicname, None)
1807 1818 setattr(self, "magic_" + magicname, im)
1808 1819 return old
1809 1820
1810 1821 #-------------------------------------------------------------------------
1811 1822 # Things related to macros
1812 1823 #-------------------------------------------------------------------------
1813 1824
1814 1825 def define_macro(self, name, themacro):
1815 1826 """Define a new macro
1816 1827
1817 1828 Parameters
1818 1829 ----------
1819 1830 name : str
1820 1831 The name of the macro.
1821 1832 themacro : str or Macro
1822 1833 The action to do upon invoking the macro. If a string, a new
1823 1834 Macro object is created by passing the string to it.
1824 1835 """
1825 1836
1826 1837 from IPython.core import macro
1827 1838
1828 1839 if isinstance(themacro, basestring):
1829 1840 themacro = macro.Macro(themacro)
1830 1841 if not isinstance(themacro, macro.Macro):
1831 1842 raise ValueError('A macro must be a string or a Macro instance.')
1832 1843 self.user_ns[name] = themacro
1833 1844
1834 1845 #-------------------------------------------------------------------------
1835 1846 # Things related to the running of system commands
1836 1847 #-------------------------------------------------------------------------
1837 1848
1838 1849 def system(self, cmd):
1839 1850 """Call the given cmd in a subprocess."""
1840 1851 # We do not support backgrounding processes because we either use
1841 1852 # pexpect or pipes to read from. Users can always just call
1842 1853 # os.system() if they really want a background process.
1843 1854 if cmd.endswith('&'):
1844 1855 raise OSError("Background processes not supported.")
1845 1856
1846 1857 return system(self.var_expand(cmd, depth=2))
1847 1858
1848 1859 def getoutput(self, cmd):
1849 1860 """Get output (possibly including stderr) from a subprocess."""
1850 1861 if cmd.endswith('&'):
1851 1862 raise OSError("Background processes not supported.")
1852 1863 return getoutput(self.var_expand(cmd, depth=2))
1853 1864
1854 1865 #-------------------------------------------------------------------------
1855 1866 # Things related to aliases
1856 1867 #-------------------------------------------------------------------------
1857 1868
1858 1869 def init_alias(self):
1859 1870 self.alias_manager = AliasManager(shell=self, config=self.config)
1860 1871 self.ns_table['alias'] = self.alias_manager.alias_table,
1861 1872
1862 1873 #-------------------------------------------------------------------------
1863 1874 # Things related to extensions and plugins
1864 1875 #-------------------------------------------------------------------------
1865 1876
1866 1877 def init_extension_manager(self):
1867 1878 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1868 1879
1869 1880 def init_plugin_manager(self):
1870 1881 self.plugin_manager = PluginManager(config=self.config)
1871 1882
1872 1883 #-------------------------------------------------------------------------
1873 1884 # Things related to payloads
1874 1885 #-------------------------------------------------------------------------
1875 1886
1876 1887 def init_payload(self):
1877 1888 self.payload_manager = PayloadManager(config=self.config)
1878 1889
1879 1890 #-------------------------------------------------------------------------
1880 1891 # Things related to the prefilter
1881 1892 #-------------------------------------------------------------------------
1882 1893
1883 1894 def init_prefilter(self):
1884 1895 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1885 1896 # Ultimately this will be refactored in the new interpreter code, but
1886 1897 # for now, we should expose the main prefilter method (there's legacy
1887 1898 # code out there that may rely on this).
1888 1899 self.prefilter = self.prefilter_manager.prefilter_lines
1889 1900
1890 1901
1891 1902 def auto_rewrite_input(self, cmd):
1892 1903 """Print to the screen the rewritten form of the user's command.
1893 1904
1894 1905 This shows visual feedback by rewriting input lines that cause
1895 1906 automatic calling to kick in, like::
1896 1907
1897 1908 /f x
1898 1909
1899 1910 into::
1900 1911
1901 1912 ------> f(x)
1902 1913
1903 1914 after the user's input prompt. This helps the user understand that the
1904 1915 input line was transformed automatically by IPython.
1905 1916 """
1906 1917 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1907 1918
1908 1919 try:
1909 1920 # plain ascii works better w/ pyreadline, on some machines, so
1910 1921 # we use it and only print uncolored rewrite if we have unicode
1911 1922 rw = str(rw)
1912 1923 print >> IPython.utils.io.Term.cout, rw
1913 1924 except UnicodeEncodeError:
1914 1925 print "------> " + cmd
1915 1926
1916 1927 #-------------------------------------------------------------------------
1917 1928 # Things related to extracting values/expressions from kernel and user_ns
1918 1929 #-------------------------------------------------------------------------
1919 1930
1920 1931 def _simple_error(self):
1921 1932 etype, value = sys.exc_info()[:2]
1922 1933 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1923 1934
1924 1935 def get_user_variables(self, names):
1925 1936 """Get a list of variable names from the user's namespace.
1926 1937
1927 1938 The return value is a dict with the repr() of each value.
1928 1939 """
1929 1940 out = {}
1930 1941 user_ns = self.user_ns
1931 1942 for varname in names:
1932 1943 try:
1933 1944 value = repr(user_ns[varname])
1934 1945 except:
1935 1946 value = self._simple_error()
1936 1947 out[varname] = value
1937 1948 return out
1938 1949
1939 1950 def eval_expressions(self, expressions):
1940 1951 """Evaluate a dict of expressions in the user's namespace.
1941 1952
1942 1953 The return value is a dict with the repr() of each value.
1943 1954 """
1944 1955 out = {}
1945 1956 user_ns = self.user_ns
1946 1957 global_ns = self.user_global_ns
1947 1958 for key, expr in expressions.iteritems():
1948 1959 try:
1949 1960 value = repr(eval(expr, global_ns, user_ns))
1950 1961 except:
1951 1962 value = self._simple_error()
1952 1963 out[key] = value
1953 1964 return out
1954 1965
1955 1966 #-------------------------------------------------------------------------
1956 1967 # Things related to the running of code
1957 1968 #-------------------------------------------------------------------------
1958 1969
1959 1970 def ex(self, cmd):
1960 1971 """Execute a normal python statement in user namespace."""
1961 1972 with nested(self.builtin_trap,):
1962 1973 exec cmd in self.user_global_ns, self.user_ns
1963 1974
1964 1975 def ev(self, expr):
1965 1976 """Evaluate python expression expr in user namespace.
1966 1977
1967 1978 Returns the result of evaluation
1968 1979 """
1969 1980 with nested(self.builtin_trap,):
1970 1981 return eval(expr, self.user_global_ns, self.user_ns)
1971 1982
1972 1983 def safe_execfile(self, fname, *where, **kw):
1973 1984 """A safe version of the builtin execfile().
1974 1985
1975 1986 This version will never throw an exception, but instead print
1976 1987 helpful error messages to the screen. This only works on pure
1977 1988 Python files with the .py extension.
1978 1989
1979 1990 Parameters
1980 1991 ----------
1981 1992 fname : string
1982 1993 The name of the file to be executed.
1983 1994 where : tuple
1984 1995 One or two namespaces, passed to execfile() as (globals,locals).
1985 1996 If only one is given, it is passed as both.
1986 1997 exit_ignore : bool (False)
1987 1998 If True, then silence SystemExit for non-zero status (it is always
1988 1999 silenced for zero status, as it is so common).
1989 2000 """
1990 2001 kw.setdefault('exit_ignore', False)
1991 2002
1992 2003 fname = os.path.abspath(os.path.expanduser(fname))
1993 2004
1994 2005 # Make sure we have a .py file
1995 2006 if not fname.endswith('.py'):
1996 2007 warn('File must end with .py to be run using execfile: <%s>' % fname)
1997 2008
1998 2009 # Make sure we can open the file
1999 2010 try:
2000 2011 with open(fname) as thefile:
2001 2012 pass
2002 2013 except:
2003 2014 warn('Could not open file <%s> for safe execution.' % fname)
2004 2015 return
2005 2016
2006 2017 # Find things also in current directory. This is needed to mimic the
2007 2018 # behavior of running a script from the system command line, where
2008 2019 # Python inserts the script's directory into sys.path
2009 2020 dname = os.path.dirname(fname)
2010 2021
2011 2022 with prepended_to_syspath(dname):
2012 2023 try:
2013 2024 execfile(fname,*where)
2014 2025 except SystemExit, status:
2015 2026 # If the call was made with 0 or None exit status (sys.exit(0)
2016 2027 # or sys.exit() ), don't bother showing a traceback, as both of
2017 2028 # these are considered normal by the OS:
2018 2029 # > python -c'import sys;sys.exit(0)'; echo $?
2019 2030 # 0
2020 2031 # > python -c'import sys;sys.exit()'; echo $?
2021 2032 # 0
2022 2033 # For other exit status, we show the exception unless
2023 2034 # explicitly silenced, but only in short form.
2024 2035 if status.code not in (0, None) and not kw['exit_ignore']:
2025 2036 self.showtraceback(exception_only=True)
2026 2037 except:
2027 2038 self.showtraceback()
2028 2039
2029 2040 def safe_execfile_ipy(self, fname):
2030 2041 """Like safe_execfile, but for .ipy files with IPython syntax.
2031 2042
2032 2043 Parameters
2033 2044 ----------
2034 2045 fname : str
2035 2046 The name of the file to execute. The filename must have a
2036 2047 .ipy extension.
2037 2048 """
2038 2049 fname = os.path.abspath(os.path.expanduser(fname))
2039 2050
2040 2051 # Make sure we have a .py file
2041 2052 if not fname.endswith('.ipy'):
2042 2053 warn('File must end with .py to be run using execfile: <%s>' % fname)
2043 2054
2044 2055 # Make sure we can open the file
2045 2056 try:
2046 2057 with open(fname) as thefile:
2047 2058 pass
2048 2059 except:
2049 2060 warn('Could not open file <%s> for safe execution.' % fname)
2050 2061 return
2051 2062
2052 2063 # Find things also in current directory. This is needed to mimic the
2053 2064 # behavior of running a script from the system command line, where
2054 2065 # Python inserts the script's directory into sys.path
2055 2066 dname = os.path.dirname(fname)
2056 2067
2057 2068 with prepended_to_syspath(dname):
2058 2069 try:
2059 2070 with open(fname) as thefile:
2060 2071 script = thefile.read()
2061 2072 # self.runlines currently captures all exceptions
2062 2073 # raise in user code. It would be nice if there were
2063 2074 # versions of runlines, execfile that did raise, so
2064 2075 # we could catch the errors.
2065 2076 self.runlines(script, clean=True)
2066 2077 except:
2067 2078 self.showtraceback()
2068 2079 warn('Unknown failure executing file: <%s>' % fname)
2069 2080
2070 2081 def run_cell(self, cell):
2071 2082 """Run the contents of an entire multiline 'cell' of code.
2072 2083
2073 2084 The cell is split into separate blocks which can be executed
2074 2085 individually. Then, based on how many blocks there are, they are
2075 2086 executed as follows:
2076 2087
2077 2088 - A single block: 'single' mode.
2078 2089
2079 2090 If there's more than one block, it depends:
2080 2091
2081 2092 - if the last one is a single line long, run all but the last in
2082 2093 'exec' mode and the very last one in 'single' mode. This makes it
2083 2094 easy to type simple expressions at the end to see computed values.
2084 2095 - otherwise (last one is also multiline), run all in 'exec' mode
2085 2096
2086 2097 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2087 2098 results are displayed and output prompts are computed. In 'exec' mode,
2088 2099 no results are displayed unless :func:`print` is called explicitly;
2089 2100 this mode is more akin to running a script.
2090 2101
2091 2102 Parameters
2092 2103 ----------
2093 2104 cell : str
2094 2105 A single or multiline string.
2095 2106 """
2096 2107 # We need to break up the input into executable blocks that can be run
2097 2108 # in 'single' mode, to provide comfortable user behavior.
2098 2109 blocks = self.input_splitter.split_blocks(cell)
2099 2110
2100 2111 if not blocks:
2101 2112 return
2102 2113
2103 2114 # Single-block input should behave like an interactive prompt
2104 2115 if len(blocks) == 1:
2105 2116 self.runlines(blocks[0])
2106 2117 return
2107 2118
2108 2119 # In multi-block input, if the last block is a simple (one-two lines)
2109 2120 # expression, run it in single mode so it produces output. Otherwise
2110 2121 # just feed the whole thing to runcode.
2111 2122 # This seems like a reasonable usability design.
2112 2123 last = blocks[-1]
2113 2124 if len(last.splitlines()) < 2:
2114 2125 self.runcode('\n'.join(blocks[:-1]))
2115 2126 self.runlines(last)
2116 2127 else:
2117 2128 self.runcode(cell)
2118 2129
2119 2130 def runlines(self, lines, clean=False):
2120 2131 """Run a string of one or more lines of source.
2121 2132
2122 2133 This method is capable of running a string containing multiple source
2123 2134 lines, as if they had been entered at the IPython prompt. Since it
2124 2135 exposes IPython's processing machinery, the given strings can contain
2125 2136 magic calls (%magic), special shell access (!cmd), etc.
2126 2137 """
2127 2138
2128 2139 if isinstance(lines, (list, tuple)):
2129 2140 lines = '\n'.join(lines)
2130 2141
2131 2142 if clean:
2132 2143 lines = self._cleanup_ipy_script(lines)
2133 2144
2134 2145 # We must start with a clean buffer, in case this is run from an
2135 2146 # interactive IPython session (via a magic, for example).
2136 2147 self.resetbuffer()
2137 2148 lines = lines.splitlines()
2138 2149 more = 0
2139 2150 with nested(self.builtin_trap, self.display_trap):
2140 2151 for line in lines:
2141 2152 # skip blank lines so we don't mess up the prompt counter, but
2142 2153 # do NOT skip even a blank line if we are in a code block (more
2143 2154 # is true)
2144 2155
2145 2156 if line or more:
2146 2157 # push to raw history, so hist line numbers stay in sync
2147 2158 self.input_hist_raw.append(line + '\n')
2148 2159 prefiltered = self.prefilter_manager.prefilter_lines(line,
2149 2160 more)
2150 2161 more = self.push_line(prefiltered)
2151 2162 # IPython's runsource returns None if there was an error
2152 2163 # compiling the code. This allows us to stop processing
2153 2164 # right away, so the user gets the error message at the
2154 2165 # right place.
2155 2166 if more is None:
2156 2167 break
2157 2168 else:
2158 2169 self.input_hist_raw.append("\n")
2159 2170 # final newline in case the input didn't have it, so that the code
2160 2171 # actually does get executed
2161 2172 if more:
2162 2173 self.push_line('\n')
2163 2174
2164 2175 def runsource(self, source, filename='<input>', symbol='single'):
2165 2176 """Compile and run some source in the interpreter.
2166 2177
2167 2178 Arguments are as for compile_command().
2168 2179
2169 2180 One several things can happen:
2170 2181
2171 2182 1) The input is incorrect; compile_command() raised an
2172 2183 exception (SyntaxError or OverflowError). A syntax traceback
2173 2184 will be printed by calling the showsyntaxerror() method.
2174 2185
2175 2186 2) The input is incomplete, and more input is required;
2176 2187 compile_command() returned None. Nothing happens.
2177 2188
2178 2189 3) The input is complete; compile_command() returned a code
2179 2190 object. The code is executed by calling self.runcode() (which
2180 2191 also handles run-time exceptions, except for SystemExit).
2181 2192
2182 2193 The return value is:
2183 2194
2184 2195 - True in case 2
2185 2196
2186 2197 - False in the other cases, unless an exception is raised, where
2187 2198 None is returned instead. This can be used by external callers to
2188 2199 know whether to continue feeding input or not.
2189 2200
2190 2201 The return value can be used to decide whether to use sys.ps1 or
2191 2202 sys.ps2 to prompt the next line."""
2192 2203
2193 2204 # if the source code has leading blanks, add 'if 1:\n' to it
2194 2205 # this allows execution of indented pasted code. It is tempting
2195 2206 # to add '\n' at the end of source to run commands like ' a=1'
2196 2207 # directly, but this fails for more complicated scenarios
2197 2208 source=source.encode(self.stdin_encoding)
2198 2209 if source[:1] in [' ', '\t']:
2199 2210 source = 'if 1:\n%s' % source
2200 2211
2201 2212 try:
2202 2213 code = self.compile(source,filename,symbol)
2203 2214 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2204 2215 # Case 1
2205 2216 self.showsyntaxerror(filename)
2206 2217 return None
2207 2218
2208 2219 if code is None:
2209 2220 # Case 2
2210 2221 return True
2211 2222
2212 2223 # Case 3
2213 2224 # We store the code object so that threaded shells and
2214 2225 # custom exception handlers can access all this info if needed.
2215 2226 # The source corresponding to this can be obtained from the
2216 2227 # buffer attribute as '\n'.join(self.buffer).
2217 2228 self.code_to_run = code
2218 2229 # now actually execute the code object
2219 2230 if self.runcode(code) == 0:
2220 2231 return False
2221 2232 else:
2222 2233 return None
2223 2234
2224 2235 def runcode(self, code_obj):
2225 2236 """Execute a code object.
2226 2237
2227 2238 When an exception occurs, self.showtraceback() is called to display a
2228 2239 traceback.
2229 2240
2230 2241 Return value: a flag indicating whether the code to be run completed
2231 2242 successfully:
2232 2243
2233 2244 - 0: successful execution.
2234 2245 - 1: an error occurred.
2235 2246 """
2236 2247
2237 2248 # It's also possible that we've been fed a plain string. In that case,
2238 2249 # we must store it in the input history.
2239 2250 if isinstance(code_obj, basestring):
2240 2251 self.input_hist_raw.append(code_obj)
2241 2252
2242 2253 # Set our own excepthook in case the user code tries to call it
2243 2254 # directly, so that the IPython crash handler doesn't get triggered
2244 2255 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2245 2256
2246 2257 # we save the original sys.excepthook in the instance, in case config
2247 2258 # code (such as magics) needs access to it.
2248 2259 self.sys_excepthook = old_excepthook
2249 2260 outflag = 1 # happens in more places, so it's easier as default
2250 2261 try:
2251 2262 try:
2252 2263 self.hooks.pre_runcode_hook()
2253 2264 #rprint('Running code') # dbg
2254 2265 exec code_obj in self.user_global_ns, self.user_ns
2255 2266 finally:
2256 2267 # Reset our crash handler in place
2257 2268 sys.excepthook = old_excepthook
2258 2269 except SystemExit:
2259 2270 self.resetbuffer()
2260 2271 self.showtraceback(exception_only=True)
2261 2272 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2262 2273 except self.custom_exceptions:
2263 2274 etype,value,tb = sys.exc_info()
2264 2275 self.CustomTB(etype,value,tb)
2265 2276 except:
2266 2277 self.showtraceback()
2267 2278 else:
2268 2279 outflag = 0
2269 2280 if softspace(sys.stdout, 0):
2270 2281 print
2282
2283 # Execute any registered post-execution functions. Here, any errors
2284 # are reported only minimally and just on the terminal, because the
2285 # main exception channel may be occupied with a user traceback.
2286 # FIXME: we need to think this mechanism a little more carefully.
2287 for func in self._post_execute:
2288 try:
2289 func()
2290 except:
2291 head = '[ ERROR ] Evaluating post_execute function: %s' % func
2292 print >> io.Term.cout, head
2293 print >> io.Term.cout, self._simple_error()
2294 print >> io.Term.cout, 'Removing from post_execute'
2295 self._post_execute.remove(func)
2296
2271 2297 # Flush out code object which has been run (and source)
2272 2298 self.code_to_run = None
2273 2299 return outflag
2274 2300
2275 2301 def push_line(self, line):
2276 2302 """Push a line to the interpreter.
2277 2303
2278 2304 The line should not have a trailing newline; it may have
2279 2305 internal newlines. The line is appended to a buffer and the
2280 2306 interpreter's runsource() method is called with the
2281 2307 concatenated contents of the buffer as source. If this
2282 2308 indicates that the command was executed or invalid, the buffer
2283 2309 is reset; otherwise, the command is incomplete, and the buffer
2284 2310 is left as it was after the line was appended. The return
2285 2311 value is 1 if more input is required, 0 if the line was dealt
2286 2312 with in some way (this is the same as runsource()).
2287 2313 """
2288 2314
2289 2315 # autoindent management should be done here, and not in the
2290 2316 # interactive loop, since that one is only seen by keyboard input. We
2291 2317 # need this done correctly even for code run via runlines (which uses
2292 2318 # push).
2293 2319
2294 2320 #print 'push line: <%s>' % line # dbg
2295 2321 for subline in line.splitlines():
2296 2322 self._autoindent_update(subline)
2297 2323 self.buffer.append(line)
2298 2324 more = self.runsource('\n'.join(self.buffer), self.filename)
2299 2325 if not more:
2300 2326 self.resetbuffer()
2301 2327 return more
2302 2328
2303 2329 def resetbuffer(self):
2304 2330 """Reset the input buffer."""
2305 2331 self.buffer[:] = []
2306 2332
2307 2333 def _is_secondary_block_start(self, s):
2308 2334 if not s.endswith(':'):
2309 2335 return False
2310 2336 if (s.startswith('elif') or
2311 2337 s.startswith('else') or
2312 2338 s.startswith('except') or
2313 2339 s.startswith('finally')):
2314 2340 return True
2315 2341
2316 2342 def _cleanup_ipy_script(self, script):
2317 2343 """Make a script safe for self.runlines()
2318 2344
2319 2345 Currently, IPython is lines based, with blocks being detected by
2320 2346 empty lines. This is a problem for block based scripts that may
2321 2347 not have empty lines after blocks. This script adds those empty
2322 2348 lines to make scripts safe for running in the current line based
2323 2349 IPython.
2324 2350 """
2325 2351 res = []
2326 2352 lines = script.splitlines()
2327 2353 level = 0
2328 2354
2329 2355 for l in lines:
2330 2356 lstripped = l.lstrip()
2331 2357 stripped = l.strip()
2332 2358 if not stripped:
2333 2359 continue
2334 2360 newlevel = len(l) - len(lstripped)
2335 2361 if level > 0 and newlevel == 0 and \
2336 2362 not self._is_secondary_block_start(stripped):
2337 2363 # add empty line
2338 2364 res.append('')
2339 2365 res.append(l)
2340 2366 level = newlevel
2341 2367
2342 2368 return '\n'.join(res) + '\n'
2343 2369
2344 2370 def _autoindent_update(self,line):
2345 2371 """Keep track of the indent level."""
2346 2372
2347 2373 #debugx('line')
2348 2374 #debugx('self.indent_current_nsp')
2349 2375 if self.autoindent:
2350 2376 if line:
2351 2377 inisp = num_ini_spaces(line)
2352 2378 if inisp < self.indent_current_nsp:
2353 2379 self.indent_current_nsp = inisp
2354 2380
2355 2381 if line[-1] == ':':
2356 2382 self.indent_current_nsp += 4
2357 2383 elif dedent_re.match(line):
2358 2384 self.indent_current_nsp -= 4
2359 2385 else:
2360 2386 self.indent_current_nsp = 0
2361 2387
2362 2388 #-------------------------------------------------------------------------
2363 2389 # Things related to GUI support and pylab
2364 2390 #-------------------------------------------------------------------------
2365 2391
2366 2392 def enable_pylab(self, gui=None):
2367 2393 raise NotImplementedError('Implement enable_pylab in a subclass')
2368 2394
2369 2395 #-------------------------------------------------------------------------
2370 2396 # Utilities
2371 2397 #-------------------------------------------------------------------------
2372 2398
2373 2399 def var_expand(self,cmd,depth=0):
2374 2400 """Expand python variables in a string.
2375 2401
2376 2402 The depth argument indicates how many frames above the caller should
2377 2403 be walked to look for the local namespace where to expand variables.
2378 2404
2379 2405 The global namespace for expansion is always the user's interactive
2380 2406 namespace.
2381 2407 """
2382 2408
2383 2409 return str(ItplNS(cmd,
2384 2410 self.user_ns, # globals
2385 2411 # Skip our own frame in searching for locals:
2386 2412 sys._getframe(depth+1).f_locals # locals
2387 2413 ))
2388 2414
2389 2415 def mktempfile(self,data=None):
2390 2416 """Make a new tempfile and return its filename.
2391 2417
2392 2418 This makes a call to tempfile.mktemp, but it registers the created
2393 2419 filename internally so ipython cleans it up at exit time.
2394 2420
2395 2421 Optional inputs:
2396 2422
2397 2423 - data(None): if data is given, it gets written out to the temp file
2398 2424 immediately, and the file is closed again."""
2399 2425
2400 2426 filename = tempfile.mktemp('.py','ipython_edit_')
2401 2427 self.tempfiles.append(filename)
2402 2428
2403 2429 if data:
2404 2430 tmp_file = open(filename,'w')
2405 2431 tmp_file.write(data)
2406 2432 tmp_file.close()
2407 2433 return filename
2408 2434
2409 2435 # TODO: This should be removed when Term is refactored.
2410 2436 def write(self,data):
2411 2437 """Write a string to the default output"""
2412 2438 io.Term.cout.write(data)
2413 2439
2414 2440 # TODO: This should be removed when Term is refactored.
2415 2441 def write_err(self,data):
2416 2442 """Write a string to the default error output"""
2417 2443 io.Term.cerr.write(data)
2418 2444
2419 2445 def ask_yes_no(self,prompt,default=True):
2420 2446 if self.quiet:
2421 2447 return True
2422 2448 return ask_yes_no(prompt,default)
2423 2449
2424 2450 def show_usage(self):
2425 2451 """Show a usage message"""
2426 2452 page.page(IPython.core.usage.interactive_usage)
2427 2453
2428 2454 #-------------------------------------------------------------------------
2429 2455 # Things related to IPython exiting
2430 2456 #-------------------------------------------------------------------------
2431 2457 def atexit_operations(self):
2432 2458 """This will be executed at the time of exit.
2433 2459
2434 2460 Cleanup operations and saving of persistent data that is done
2435 2461 unconditionally by IPython should be performed here.
2436 2462
2437 2463 For things that may depend on startup flags or platform specifics (such
2438 2464 as having readline or not), register a separate atexit function in the
2439 2465 code that has the appropriate information, rather than trying to
2440 2466 clutter
2441 2467 """
2442 2468 # Cleanup all tempfiles left around
2443 2469 for tfile in self.tempfiles:
2444 2470 try:
2445 2471 os.unlink(tfile)
2446 2472 except OSError:
2447 2473 pass
2448 2474
2449 2475 # Clear all user namespaces to release all references cleanly.
2450 2476 self.reset()
2451 2477
2452 2478 # Run user hooks
2453 2479 self.hooks.shutdown_hook()
2454 2480
2455 2481 def cleanup(self):
2456 2482 self.restore_sys_module_state()
2457 2483
2458 2484
2459 2485 class InteractiveShellABC(object):
2460 2486 """An abstract base class for InteractiveShell."""
2461 2487 __metaclass__ = abc.ABCMeta
2462 2488
2463 2489 InteractiveShellABC.register(InteractiveShell)
@@ -1,147 +1,144 b''
1 1 """ A minimal application using the Qt console-style IPython frontend.
2 2 """
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Imports
6 6 #-----------------------------------------------------------------------------
7 7
8 8 # Systemm library imports
9 9 from PyQt4 import QtGui
10 10
11 11 # Local imports
12 12 from IPython.external.argparse import ArgumentParser
13 13 from IPython.frontend.qt.console.frontend_widget import FrontendWidget
14 14 from IPython.frontend.qt.console.ipython_widget import IPythonWidget
15 15 from IPython.frontend.qt.console.rich_ipython_widget import RichIPythonWidget
16 16 from IPython.frontend.qt.kernelmanager import QtKernelManager
17 17
18 18 #-----------------------------------------------------------------------------
19 19 # Constants
20 20 #-----------------------------------------------------------------------------
21 21
22 22 LOCALHOST = '127.0.0.1'
23 23
24 24 #-----------------------------------------------------------------------------
25 25 # Classes
26 26 #-----------------------------------------------------------------------------
27 27
28 28 class MainWindow(QtGui.QMainWindow):
29 29
30 30 #---------------------------------------------------------------------------
31 31 # 'object' interface
32 32 #---------------------------------------------------------------------------
33 33
34 34 def __init__(self, frontend):
35 35 """ Create a MainWindow for the specified FrontendWidget.
36 36 """
37 37 super(MainWindow, self).__init__()
38 38 self._frontend = frontend
39 39 self._frontend.exit_requested.connect(self.close)
40 40 self.setCentralWidget(frontend)
41 41
42 42 #---------------------------------------------------------------------------
43 43 # QWidget interface
44 44 #---------------------------------------------------------------------------
45 45
46 46 def closeEvent(self, event):
47 47 """ Reimplemented to prompt the user and close the kernel cleanly.
48 48 """
49 49 kernel_manager = self._frontend.kernel_manager
50 50 if kernel_manager and kernel_manager.channels_running:
51 51 title = self.window().windowTitle()
52 52 reply = QtGui.QMessageBox.question(self, title,
53 53 'Close console?', QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
54 54 if reply == QtGui.QMessageBox.Yes:
55 55 kernel_manager.shutdown_kernel()
56 56 #kernel_manager.stop_channels()
57 57 event.accept()
58 58 else:
59 59 event.ignore()
60 60
61 61 #-----------------------------------------------------------------------------
62 62 # Main entry point
63 63 #-----------------------------------------------------------------------------
64 64
65 65 def main():
66 66 """ Entry point for application.
67 67 """
68 68 # Parse command line arguments.
69 69 parser = ArgumentParser()
70 70 kgroup = parser.add_argument_group('kernel options')
71 71 kgroup.add_argument('-e', '--existing', action='store_true',
72 72 help='connect to an existing kernel')
73 73 kgroup.add_argument('--ip', type=str, default=LOCALHOST,
74 74 help='set the kernel\'s IP address [default localhost]')
75 75 kgroup.add_argument('--xreq', type=int, metavar='PORT', default=0,
76 76 help='set the XREQ channel port [default random]')
77 77 kgroup.add_argument('--sub', type=int, metavar='PORT', default=0,
78 78 help='set the SUB channel port [default random]')
79 79 kgroup.add_argument('--rep', type=int, metavar='PORT', default=0,
80 80 help='set the REP channel port [default random]')
81 81 kgroup.add_argument('--hb', type=int, metavar='PORT', default=0,
82 82 help='set the heartbeat port [default: random]')
83 83
84 84 egroup = kgroup.add_mutually_exclusive_group()
85 85 egroup.add_argument('--pure', action='store_true', help = \
86 86 'use a pure Python kernel instead of an IPython kernel')
87 87 egroup.add_argument('--pylab', type=str, metavar='GUI', nargs='?',
88 88 const='auto', help = \
89 89 "Pre-load matplotlib and numpy for interactive use. If GUI is not \
90 90 given, the GUI backend is matplotlib's, otherwise use one of: \
91 91 ['tk', 'gtk', 'qt', 'wx', 'payload-svg'].")
92 92
93 93 wgroup = parser.add_argument_group('widget options')
94 94 wgroup.add_argument('--paging', type=str, default='inside',
95 95 choices = ['inside', 'hsplit', 'vsplit', 'none'],
96 96 help='set the paging style [default inside]')
97 97 wgroup.add_argument('--rich', action='store_true',
98 98 help='enable rich text support')
99 99 wgroup.add_argument('--gui-completion', action='store_true',
100 100 help='use a GUI widget for tab completion')
101 101
102 102 args = parser.parse_args()
103 103
104 104 # Don't let Qt or ZMQ swallow KeyboardInterupts.
105 105 import signal
106 106 signal.signal(signal.SIGINT, signal.SIG_DFL)
107 107
108 108 # Create a KernelManager and start a kernel.
109 109 kernel_manager = QtKernelManager(xreq_address=(args.ip, args.xreq),
110 110 sub_address=(args.ip, args.sub),
111 111 rep_address=(args.ip, args.rep),
112 112 hb_address=(args.ip, args.hb))
113 113 if args.ip == LOCALHOST and not args.existing:
114 114 if args.pure:
115 115 kernel_manager.start_kernel(ipython=False)
116 116 elif args.pylab:
117 if args.rich:
118 kernel_manager.start_kernel(pylab='payload-svg')
119 else:
120 kernel_manager.start_kernel(pylab=args.pylab)
117 kernel_manager.start_kernel(pylab=args.pylab)
121 118 else:
122 119 kernel_manager.start_kernel()
123 120 kernel_manager.start_channels()
124 121
125 122 # Create the widget.
126 123 app = QtGui.QApplication([])
127 124 if args.pure:
128 125 kind = 'rich' if args.rich else 'plain'
129 126 widget = FrontendWidget(kind=kind, paging=args.paging)
130 elif args.rich:
127 elif args.rich or args.pylab:
131 128 widget = RichIPythonWidget(paging=args.paging)
132 129 else:
133 130 widget = IPythonWidget(paging=args.paging)
134 131 widget.gui_completion = args.gui_completion
135 132 widget.kernel_manager = kernel_manager
136 133
137 134 # Create the main window.
138 135 window = MainWindow(widget)
139 136 window.setWindowTitle('Python' if args.pure else 'IPython')
140 137 window.show()
141 138
142 139 # Start the application main loop.
143 140 app.exec_()
144 141
145 142
146 143 if __name__ == '__main__':
147 144 main()
@@ -1,182 +1,194 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Pylab (matplotlib) support utilities.
3 3
4 4 Authors
5 5 -------
6 6
7 7 * Fernando Perez.
8 8 * Brian Granger
9 9 """
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Copyright (C) 2009 The IPython Development Team
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #-----------------------------------------------------------------------------
17 17
18 18 #-----------------------------------------------------------------------------
19 19 # Imports
20 20 #-----------------------------------------------------------------------------
21 21
22 22 from IPython.utils.decorators import flag_calls
23 23
24 # If user specifies a GUI, that dictates the backend, otherwise we read the
25 # user's mpl default from the mpl rc structure
26 backends = {'tk': 'TkAgg',
27 'gtk': 'GTKAgg',
28 'wx': 'WXAgg',
29 'qt': 'Qt4Agg', # qt3 not supported
30 'qt4': 'Qt4Agg',
31 'payload-svg' : 'module://IPython.zmq.pylab.backend_payload_svg'}
32
24 33 #-----------------------------------------------------------------------------
25 34 # Main classes and functions
26 35 #-----------------------------------------------------------------------------
27 36
28 37
29 38 def find_gui_and_backend(gui=None):
30 39 """Given a gui string return the gui and mpl backend.
31 40
32 41 Parameters
33 42 ----------
34 43 gui : str
35 44 Can be one of ('tk','gtk','wx','qt','qt4','payload-svg').
36 45
37 46 Returns
38 47 -------
39 48 A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg',
40 49 'WXAgg','Qt4Agg','module://IPython.zmq.pylab.backend_payload_svg').
41 50 """
42 51
43 52 import matplotlib
44 53
45 # If user specifies a GUI, that dictates the backend, otherwise we read the
46 # user's mpl default from the mpl rc structure
47 g2b = {'tk': 'TkAgg',
48 'gtk': 'GTKAgg',
49 'wx': 'WXAgg',
50 'qt': 'Qt4Agg', # qt3 not supported
51 'qt4': 'Qt4Agg',
52 'payload-svg' : \
53 'module://IPython.zmq.pylab.backend_payload_svg'}
54
55 54 if gui:
56 55 # select backend based on requested gui
57 backend = g2b[gui]
56 backend = backends[gui]
58 57 else:
59 58 backend = matplotlib.rcParams['backend']
60 59 # In this case, we need to find what the appropriate gui selection call
61 60 # should be for IPython, so we can activate inputhook accordingly
62 b2g = dict(zip(g2b.values(),g2b.keys()))
61 g2b = backends # maps gui names to mpl backend names
62 b2g = dict(zip(g2b.values(), g2b.keys())) # reverse dict
63 63 gui = b2g.get(backend, None)
64 64 return gui, backend
65 65
66 66
67 67 def activate_matplotlib(backend):
68 68 """Activate the given backend and set interactive to True."""
69 69
70 70 import matplotlib
71 71 if backend.startswith('module://'):
72 72 # Work around bug in matplotlib: matplotlib.use converts the
73 73 # backend_id to lowercase even if a module name is specified!
74 74 matplotlib.rcParams['backend'] = backend
75 75 else:
76 76 matplotlib.use(backend)
77 77 matplotlib.interactive(True)
78 78
79 79 # This must be imported last in the matplotlib series, after
80 80 # backend/interactivity choices have been made
81 81 import matplotlib.pylab as pylab
82 82
83 83 # XXX For now leave this commented out, but depending on discussions with
84 84 # mpl-dev, we may be able to allow interactive switching...
85 85 #import matplotlib.pyplot
86 86 #matplotlib.pyplot.switch_backend(backend)
87 87
88 88 pylab.show._needmain = False
89 89 # We need to detect at runtime whether show() is called by the user.
90 90 # For this, we wrap it into a decorator which adds a 'called' flag.
91 91 pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive)
92 92
93 def import_pylab(user_ns, import_all=True):
93
94 def import_pylab(user_ns, backend, import_all=True, shell=None):
94 95 """Import the standard pylab symbols into user_ns."""
95 96
96 97 # Import numpy as np/pyplot as plt are conventions we're trying to
97 98 # somewhat standardize on. Making them available to users by default
98 99 # will greatly help this.
99 100 exec ("import numpy\n"
100 101 "import matplotlib\n"
101 102 "from matplotlib import pylab, mlab, pyplot\n"
102 103 "np = numpy\n"
103 104 "plt = pyplot\n"
104 105 ) in user_ns
105 106
107 if shell is not None:
108 # If using our svg payload backend, register the post-execution
109 # function that will pick up the results for display. This can only be
110 # done with access to the real shell object.
111 if backend == backends['payload-svg']:
112 from IPython.zmq.pylab.backend_payload_svg import flush_svg
113 shell.register_post_execute(flush_svg)
114 else:
115 from IPython.zmq.pylab.backend_payload_svg import paste
116 user_ns['paste'] = paste
117
106 118 if import_all:
107 119 exec("from matplotlib.pylab import *\n"
108 120 "from numpy import *\n") in user_ns
109 121
110 122
111 123 def pylab_activate(user_ns, gui=None, import_all=True):
112 124 """Activate pylab mode in the user's namespace.
113 125
114 126 Loads and initializes numpy, matplotlib and friends for interactive use.
115 127
116 128 Parameters
117 129 ----------
118 130 user_ns : dict
119 131 Namespace where the imports will occur.
120 132
121 133 gui : optional, string
122 134 A valid gui name following the conventions of the %gui magic.
123 135
124 136 import_all : optional, boolean
125 137 If true, an 'import *' is done from numpy and pylab.
126 138
127 139 Returns
128 140 -------
129 141 The actual gui used (if not given as input, it was obtained from matplotlib
130 142 itself, and will be needed next to configure IPython's gui integration.
131 143 """
132 144 gui, backend = find_gui_and_backend(gui)
133 145 activate_matplotlib(backend)
134 import_pylab(user_ns)
146 import_pylab(user_ns, backend)
135 147
136 148 print """
137 149 Welcome to pylab, a matplotlib-based Python environment [backend: %s].
138 150 For more information, type 'help(pylab)'.""" % backend
139 151
140 152 return gui
141 153
142 154 # We need a little factory function here to create the closure where
143 155 # safe_execfile can live.
144 156 def mpl_runner(safe_execfile):
145 157 """Factory to return a matplotlib-enabled runner for %run.
146 158
147 159 Parameters
148 160 ----------
149 161 safe_execfile : function
150 162 This must be a function with the same interface as the
151 163 :meth:`safe_execfile` method of IPython.
152 164
153 165 Returns
154 166 -------
155 167 A function suitable for use as the ``runner`` argument of the %run magic
156 168 function.
157 169 """
158 170
159 171 def mpl_execfile(fname,*where,**kw):
160 172 """matplotlib-aware wrapper around safe_execfile.
161 173
162 174 Its interface is identical to that of the :func:`execfile` builtin.
163 175
164 176 This is ultimately a call to execfile(), but wrapped in safeties to
165 177 properly handle interactive rendering."""
166 178
167 179 import matplotlib
168 180 import matplotlib.pylab as pylab
169 181
170 182 #print '*** Matplotlib runner ***' # dbg
171 183 # turn off rendering until end of script
172 184 is_interactive = matplotlib.rcParams['interactive']
173 185 matplotlib.interactive(False)
174 186 safe_execfile(fname,*where,**kw)
175 187 matplotlib.interactive(is_interactive)
176 188 # make rendering call now, if the user tried to do it
177 189 if pylab.draw_if_interactive.called:
178 190 pylab.draw()
179 191 pylab.draw_if_interactive.called = False
180 192
181 193 return mpl_execfile
182 194
@@ -1,580 +1,586 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 from __future__ import print_function
17 17
18 18 # Standard library imports.
19 19 import __builtin__
20 20 import atexit
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.utils import io
31 31 from IPython.utils.jsonutil import json_clean
32 32 from IPython.lib import pylabtools
33 33 from IPython.utils.traitlets import Instance, Float
34 34 from entry_point import (base_launch_kernel, make_argument_parser, make_kernel,
35 35 start_kernel)
36 36 from iostream import OutStream
37 37 from session import Session, Message
38 38 from zmqshell import ZMQInteractiveShell
39 39
40 40 #-----------------------------------------------------------------------------
41 41 # Main kernel class
42 42 #-----------------------------------------------------------------------------
43 43
44 44 class Kernel(Configurable):
45 45
46 46 #---------------------------------------------------------------------------
47 47 # Kernel interface
48 48 #---------------------------------------------------------------------------
49 49
50 50 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
51 51 session = Instance(Session)
52 52 reply_socket = Instance('zmq.Socket')
53 53 pub_socket = Instance('zmq.Socket')
54 54 req_socket = Instance('zmq.Socket')
55 55
56 56 # Private interface
57 57
58 58 # Time to sleep after flushing the stdout/err buffers in each execute
59 59 # cycle. While this introduces a hard limit on the minimal latency of the
60 60 # execute cycle, it helps prevent output synchronization problems for
61 61 # clients.
62 62 # Units are in seconds. The minimum zmq latency on local host is probably
63 63 # ~150 microseconds, set this to 500us for now. We may need to increase it
64 64 # a little if it's not enough after more interactive testing.
65 65 _execute_sleep = Float(0.0005, config=True)
66 66
67 67 # Frequency of the kernel's event loop.
68 68 # Units are in seconds, kernel subclasses for GUI toolkits may need to
69 69 # adapt to milliseconds.
70 70 _poll_interval = Float(0.05, config=True)
71 71
72 72 # If the shutdown was requested over the network, we leave here the
73 73 # necessary reply message so it can be sent by our registered atexit
74 74 # handler. This ensures that the reply is only sent to clients truly at
75 75 # the end of our shutdown process (which happens after the underlying
76 76 # IPython shell's own shutdown).
77 77 _shutdown_message = None
78 78
79 79 def __init__(self, **kwargs):
80 80 super(Kernel, self).__init__(**kwargs)
81 81
82 82 # Before we even start up the shell, register *first* our exit handlers
83 83 # so they come before the shell's
84 84 atexit.register(self._at_shutdown)
85 85
86 86 # Initialize the InteractiveShell subclass
87 87 self.shell = ZMQInteractiveShell.instance()
88 88 self.shell.displayhook.session = self.session
89 89 self.shell.displayhook.pub_socket = self.pub_socket
90 90
91 91 # TMP - hack while developing
92 92 self.shell._reply_content = None
93 93
94 94 # Build dict of handlers for message types
95 95 msg_types = [ 'execute_request', 'complete_request',
96 96 'object_info_request', 'history_request',
97 97 'shutdown_request']
98 98 self.handlers = {}
99 99 for msg_type in msg_types:
100 100 self.handlers[msg_type] = getattr(self, msg_type)
101 101
102 102 def do_one_iteration(self):
103 103 """Do one iteration of the kernel's evaluation loop.
104 104 """
105 105 try:
106 106 ident = self.reply_socket.recv(zmq.NOBLOCK)
107 107 except zmq.ZMQError, e:
108 108 if e.errno == zmq.EAGAIN:
109 109 return
110 110 else:
111 111 raise
112 112 # FIXME: Bug in pyzmq/zmq?
113 113 # assert self.reply_socket.rcvmore(), "Missing message part."
114 114 msg = self.reply_socket.recv_json()
115 115
116 116 # Print some info about this message and leave a '--->' marker, so it's
117 117 # easier to trace visually the message chain when debugging. Each
118 118 # handler prints its message at the end.
119 119 # Eventually we'll move these from stdout to a logger.
120 120 io.raw_print('\n*** MESSAGE TYPE:', msg['msg_type'], '***')
121 121 io.raw_print(' Content: ', msg['content'],
122 122 '\n --->\n ', sep='', end='')
123 123
124 124 # Find and call actual handler for message
125 125 handler = self.handlers.get(msg['msg_type'], None)
126 126 if handler is None:
127 127 io.raw_print_err("UNKNOWN MESSAGE TYPE:", msg)
128 128 else:
129 129 handler(ident, msg)
130 130
131 131 # Check whether we should exit, in case the incoming message set the
132 132 # exit flag on
133 133 if self.shell.exit_now:
134 134 io.raw_print('\nExiting IPython kernel...')
135 135 # We do a normal, clean exit, which allows any actions registered
136 136 # via atexit (such as history saving) to take place.
137 137 sys.exit(0)
138 138
139 139
140 140 def start(self):
141 141 """ Start the kernel main loop.
142 142 """
143 143 while True:
144 144 time.sleep(self._poll_interval)
145 145 self.do_one_iteration()
146 146
147 147 #---------------------------------------------------------------------------
148 148 # Kernel request handlers
149 149 #---------------------------------------------------------------------------
150 150
151 151 def _publish_pyin(self, code, parent):
152 152 """Publish the code request on the pyin stream."""
153 153
154 154 pyin_msg = self.session.msg(u'pyin',{u'code':code}, parent=parent)
155 155 self.pub_socket.send_json(pyin_msg)
156 156
157 157 def execute_request(self, ident, parent):
158 158 try:
159 159 content = parent[u'content']
160 160 code = content[u'code']
161 161 silent = content[u'silent']
162 162 except:
163 163 io.raw_print_err("Got bad msg: ")
164 164 io.raw_print_err(Message(parent))
165 165 return
166 166
167 167 shell = self.shell # we'll need this a lot here
168 168
169 169 # Replace raw_input. Note that is not sufficient to replace
170 170 # raw_input in the user namespace.
171 171 raw_input = lambda prompt='': self._raw_input(prompt, ident, parent)
172 172 __builtin__.raw_input = raw_input
173 173
174 174 # Set the parent message of the display hook and out streams.
175 175 shell.displayhook.set_parent(parent)
176 176 sys.stdout.set_parent(parent)
177 177 sys.stderr.set_parent(parent)
178 178
179 179 # Re-broadcast our input for the benefit of listening clients, and
180 180 # start computing output
181 181 if not silent:
182 182 self._publish_pyin(code, parent)
183 183
184 184 reply_content = {}
185 185 try:
186 186 if silent:
187 187 # runcode uses 'exec' mode, so no displayhook will fire, and it
188 188 # doesn't call logging or history manipulations. Print
189 189 # statements in that code will obviously still execute.
190 190 shell.runcode(code)
191 191 else:
192 192 # FIXME: runlines calls the exception handler itself.
193 193 shell._reply_content = None
194 194
195 # For now leave this here until we're sure we can stop using it
196 #shell.runlines(code)
197
195 198 # Experimental: cell mode! Test more before turning into
196 199 # default and removing the hacks around runlines.
197 200 shell.run_cell(code)
198 # For now leave this here until we're sure we can stop using it
199 #shell.runlines(code)
200 201 except:
201 202 status = u'error'
202 203 # FIXME: this code right now isn't being used yet by default,
203 204 # because the runlines() call above directly fires off exception
204 205 # reporting. This code, therefore, is only active in the scenario
205 206 # where runlines itself has an unhandled exception. We need to
206 207 # uniformize this, for all exception construction to come from a
207 208 # single location in the codbase.
208 209 etype, evalue, tb = sys.exc_info()
209 210 tb_list = traceback.format_exception(etype, evalue, tb)
210 211 reply_content.update(shell._showtraceback(etype, evalue, tb_list))
211 212 else:
212 213 status = u'ok'
213 reply_content[u'payload'] = shell.payload_manager.read_payload()
214 # Be agressive about clearing the payload because we don't want
215 # it to sit in memory until the next execute_request comes in.
216 shell.payload_manager.clear_payload()
217 214
218 215 reply_content[u'status'] = status
219 216 # Compute the execution counter so clients can display prompts
220 217 reply_content['execution_count'] = shell.displayhook.prompt_count
221 218
222 219 # FIXME - fish exception info out of shell, possibly left there by
223 220 # runlines. We'll need to clean up this logic later.
224 221 if shell._reply_content is not None:
225 222 reply_content.update(shell._reply_content)
226 223
227 224 # At this point, we can tell whether the main code execution succeeded
228 225 # or not. If it did, we proceed to evaluate user_variables/expressions
229 226 if reply_content['status'] == 'ok':
230 227 reply_content[u'user_variables'] = \
231 228 shell.get_user_variables(content[u'user_variables'])
232 229 reply_content[u'user_expressions'] = \
233 230 shell.eval_expressions(content[u'user_expressions'])
234 231 else:
235 232 # If there was an error, don't even try to compute variables or
236 233 # expressions
237 234 reply_content[u'user_variables'] = {}
238 235 reply_content[u'user_expressions'] = {}
239
236
237 # Payloads should be retrieved regardless of outcome, so we can both
238 # recover partial output (that could have been generated early in a
239 # block, before an error) and clear the payload system always.
240 reply_content[u'payload'] = shell.payload_manager.read_payload()
241 # Be agressive about clearing the payload because we don't want
242 # it to sit in memory until the next execute_request comes in.
243 shell.payload_manager.clear_payload()
244
240 245 # Send the reply.
241 246 reply_msg = self.session.msg(u'execute_reply', reply_content, parent)
242 247 io.raw_print(reply_msg)
243 248
244 249 # Flush output before sending the reply.
245 250 sys.stdout.flush()
246 251 sys.stderr.flush()
247 252 # FIXME: on rare occasions, the flush doesn't seem to make it to the
248 253 # clients... This seems to mitigate the problem, but we definitely need
249 254 # to better understand what's going on.
250 255 if self._execute_sleep:
251 256 time.sleep(self._execute_sleep)
252 257
253 258 self.reply_socket.send(ident, zmq.SNDMORE)
254 259 self.reply_socket.send_json(reply_msg)
255 260 if reply_msg['content']['status'] == u'error':
256 261 self._abort_queue()
257 262
258 263 def complete_request(self, ident, parent):
259 264 txt, matches = self._complete(parent)
260 265 matches = {'matches' : matches,
261 266 'matched_text' : txt,
262 267 'status' : 'ok'}
263 268 completion_msg = self.session.send(self.reply_socket, 'complete_reply',
264 269 matches, parent, ident)
265 270 io.raw_print(completion_msg)
266 271
267 272 def object_info_request(self, ident, parent):
268 273 object_info = self.shell.object_inspect(parent['content']['oname'])
269 274 # Before we send this object over, we turn it into a dict and we scrub
270 275 # it for JSON usage
271 276 oinfo = json_clean(object_info._asdict())
272 277 msg = self.session.send(self.reply_socket, 'object_info_reply',
273 278 oinfo, parent, ident)
274 279 io.raw_print(msg)
275 280
276 281 def history_request(self, ident, parent):
277 282 output = parent['content']['output']
278 283 index = parent['content']['index']
279 284 raw = parent['content']['raw']
280 285 hist = self.shell.get_history(index=index, raw=raw, output=output)
281 286 content = {'history' : hist}
282 287 msg = self.session.send(self.reply_socket, 'history_reply',
283 288 content, parent, ident)
284 289 io.raw_print(msg)
285 290
286 291 def shutdown_request(self, ident, parent):
287 292 self.shell.exit_now = True
288 293 self._shutdown_message = self.session.msg(u'shutdown_reply', {}, parent)
289 294 sys.exit(0)
290 295
291 296 #---------------------------------------------------------------------------
292 297 # Protected interface
293 298 #---------------------------------------------------------------------------
294 299
295 300 def _abort_queue(self):
296 301 while True:
297 302 try:
298 303 ident = self.reply_socket.recv(zmq.NOBLOCK)
299 304 except zmq.ZMQError, e:
300 305 if e.errno == zmq.EAGAIN:
301 306 break
302 307 else:
303 308 assert self.reply_socket.rcvmore(), \
304 309 "Unexpected missing message part."
305 310 msg = self.reply_socket.recv_json()
306 311 io.raw_print("Aborting:\n", Message(msg))
307 312 msg_type = msg['msg_type']
308 313 reply_type = msg_type.split('_')[0] + '_reply'
309 314 reply_msg = self.session.msg(reply_type, {'status' : 'aborted'}, msg)
310 315 io.raw_print(reply_msg)
311 316 self.reply_socket.send(ident,zmq.SNDMORE)
312 317 self.reply_socket.send_json(reply_msg)
313 318 # We need to wait a bit for requests to come in. This can probably
314 319 # be set shorter for true asynchronous clients.
315 320 time.sleep(0.1)
316 321
317 322 def _raw_input(self, prompt, ident, parent):
318 323 # Flush output before making the request.
319 324 sys.stderr.flush()
320 325 sys.stdout.flush()
321 326
322 327 # Send the input request.
323 328 content = dict(prompt=prompt)
324 329 msg = self.session.msg(u'input_request', content, parent)
325 330 self.req_socket.send_json(msg)
326 331
327 332 # Await a response.
328 333 reply = self.req_socket.recv_json()
329 334 try:
330 335 value = reply['content']['value']
331 336 except:
332 337 io.raw_print_err("Got bad raw_input reply: ")
333 338 io.raw_print_err(Message(parent))
334 339 value = ''
335 340 return value
336 341
337 342 def _complete(self, msg):
338 343 c = msg['content']
339 344 try:
340 345 cpos = int(c['cursor_pos'])
341 346 except:
342 347 # If we don't get something that we can convert to an integer, at
343 348 # least attempt the completion guessing the cursor is at the end of
344 349 # the text, if there's any, and otherwise of the line
345 350 cpos = len(c['text'])
346 351 if cpos==0:
347 352 cpos = len(c['line'])
348 353 return self.shell.complete(c['text'], c['line'], cpos)
349 354
350 355 def _object_info(self, context):
351 356 symbol, leftover = self._symbol_from_context(context)
352 357 if symbol is not None and not leftover:
353 358 doc = getattr(symbol, '__doc__', '')
354 359 else:
355 360 doc = ''
356 361 object_info = dict(docstring = doc)
357 362 return object_info
358 363
359 364 def _symbol_from_context(self, context):
360 365 if not context:
361 366 return None, context
362 367
363 368 base_symbol_string = context[0]
364 369 symbol = self.shell.user_ns.get(base_symbol_string, None)
365 370 if symbol is None:
366 371 symbol = __builtin__.__dict__.get(base_symbol_string, None)
367 372 if symbol is None:
368 373 return None, context
369 374
370 375 context = context[1:]
371 376 for i, name in enumerate(context):
372 377 new_symbol = getattr(symbol, name, None)
373 378 if new_symbol is None:
374 379 return symbol, context[i:]
375 380 else:
376 381 symbol = new_symbol
377 382
378 383 return symbol, []
379 384
380 385 def _at_shutdown(self):
381 386 """Actions taken at shutdown by the kernel, called by python's atexit.
382 387 """
383 388 # io.rprint("Kernel at_shutdown") # dbg
384 389 if self._shutdown_message is not None:
385 390 self.reply_socket.send_json(self._shutdown_message)
386 391 io.raw_print(self._shutdown_message)
387 392 # A very short sleep to give zmq time to flush its message buffers
388 393 # before Python truly shuts down.
389 394 time.sleep(0.01)
390 395
391 396
392 397 class QtKernel(Kernel):
393 398 """A Kernel subclass with Qt support."""
394 399
395 400 def start(self):
396 401 """Start a kernel with QtPy4 event loop integration."""
397 402
398 403 from PyQt4 import QtCore
399 404 from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4
400 405
401 406 self.app = get_app_qt4([" "])
402 407 self.app.setQuitOnLastWindowClosed(False)
403 408 self.timer = QtCore.QTimer()
404 409 self.timer.timeout.connect(self.do_one_iteration)
405 410 # Units for the timer are in milliseconds
406 411 self.timer.start(1000*self._poll_interval)
407 412 start_event_loop_qt4(self.app)
408 413
409 414
410 415 class WxKernel(Kernel):
411 416 """A Kernel subclass with Wx support."""
412 417
413 418 def start(self):
414 419 """Start a kernel with wx event loop support."""
415 420
416 421 import wx
417 422 from IPython.lib.guisupport import start_event_loop_wx
418 423
419 424 doi = self.do_one_iteration
420 425 # Wx uses milliseconds
421 426 poll_interval = int(1000*self._poll_interval)
422 427
423 428 # We have to put the wx.Timer in a wx.Frame for it to fire properly.
424 429 # We make the Frame hidden when we create it in the main app below.
425 430 class TimerFrame(wx.Frame):
426 431 def __init__(self, func):
427 432 wx.Frame.__init__(self, None, -1)
428 433 self.timer = wx.Timer(self)
429 434 # Units for the timer are in milliseconds
430 435 self.timer.Start(poll_interval)
431 436 self.Bind(wx.EVT_TIMER, self.on_timer)
432 437 self.func = func
433 438
434 439 def on_timer(self, event):
435 440 self.func()
436 441
437 442 # We need a custom wx.App to create our Frame subclass that has the
438 443 # wx.Timer to drive the ZMQ event loop.
439 444 class IPWxApp(wx.App):
440 445 def OnInit(self):
441 446 self.frame = TimerFrame(doi)
442 447 self.frame.Show(False)
443 448 return True
444 449
445 450 # The redirect=False here makes sure that wx doesn't replace
446 451 # sys.stdout/stderr with its own classes.
447 452 self.app = IPWxApp(redirect=False)
448 453 start_event_loop_wx(self.app)
449 454
450 455
451 456 class TkKernel(Kernel):
452 457 """A Kernel subclass with Tk support."""
453 458
454 459 def start(self):
455 460 """Start a Tk enabled event loop."""
456 461
457 462 import Tkinter
458 463 doi = self.do_one_iteration
459 464 # Tk uses milliseconds
460 465 poll_interval = int(1000*self._poll_interval)
461 466 # For Tkinter, we create a Tk object and call its withdraw method.
462 467 class Timer(object):
463 468 def __init__(self, func):
464 469 self.app = Tkinter.Tk()
465 470 self.app.withdraw()
466 471 self.func = func
467 472
468 473 def on_timer(self):
469 474 self.func()
470 475 self.app.after(poll_interval, self.on_timer)
471 476
472 477 def start(self):
473 478 self.on_timer() # Call it once to get things going.
474 479 self.app.mainloop()
475 480
476 481 self.timer = Timer(doi)
477 482 self.timer.start()
478 483
479 484
480 485 class GTKKernel(Kernel):
481 486 """A Kernel subclass with GTK support."""
482 487
483 488 def start(self):
484 489 """Start the kernel, coordinating with the GTK event loop"""
485 490 from .gui.gtkembed import GTKEmbed
486 491
487 492 gtk_kernel = GTKEmbed(self)
488 493 gtk_kernel.start()
489 494
490 495
491 496 #-----------------------------------------------------------------------------
492 497 # Kernel main and launch functions
493 498 #-----------------------------------------------------------------------------
494 499
495 500 def launch_kernel(xrep_port=0, pub_port=0, req_port=0, hb_port=0,
496 501 independent=False, pylab=False):
497 502 """Launches a localhost kernel, binding to the specified ports.
498 503
499 504 Parameters
500 505 ----------
501 506 xrep_port : int, optional
502 507 The port to use for XREP channel.
503 508
504 509 pub_port : int, optional
505 510 The port to use for the SUB channel.
506 511
507 512 req_port : int, optional
508 513 The port to use for the REQ (raw input) channel.
509 514
510 515 hb_port : int, optional
511 516 The port to use for the hearbeat REP channel.
512 517
513 518 independent : bool, optional (default False)
514 519 If set, the kernel process is guaranteed to survive if this process
515 520 dies. If not set, an effort is made to ensure that the kernel is killed
516 521 when this process dies. Note that in this case it is still good practice
517 522 to kill kernels manually before exiting.
518 523
519 524 pylab : bool or string, optional (default False)
520 525 If not False, the kernel will be launched with pylab enabled. If a
521 526 string is passed, matplotlib will use the specified backend. Otherwise,
522 527 matplotlib's default backend will be used.
523 528
524 529 Returns
525 530 -------
526 531 A tuple of form:
527 532 (kernel_process, xrep_port, pub_port, req_port)
528 533 where kernel_process is a Popen object and the ports are integers.
529 534 """
530 535 extra_arguments = []
531 536 if pylab:
532 537 extra_arguments.append('--pylab')
533 538 if isinstance(pylab, basestring):
534 539 extra_arguments.append(pylab)
535 540 return base_launch_kernel('from IPython.zmq.ipkernel import main; main()',
536 541 xrep_port, pub_port, req_port, hb_port,
537 542 independent, extra_arguments)
538 543
539 544
540 545 def main():
541 546 """ The IPython kernel main entry point.
542 547 """
543 548 parser = make_argument_parser()
544 549 parser.add_argument('--pylab', type=str, metavar='GUI', nargs='?',
545 550 const='auto', help = \
546 551 "Pre-load matplotlib and numpy for interactive use. If GUI is not \
547 552 given, the GUI backend is matplotlib's, otherwise use one of: \
548 553 ['tk', 'gtk', 'qt', 'wx', 'payload-svg'].")
549 554 namespace = parser.parse_args()
550 555
551 556 kernel_class = Kernel
552 557
553 558 kernel_classes = {
554 559 'qt' : QtKernel,
555 560 'qt4': QtKernel,
556 561 'payload-svg': Kernel,
557 562 'wx' : WxKernel,
558 563 'tk' : TkKernel,
559 564 'gtk': GTKKernel,
560 565 }
561 566 if namespace.pylab:
562 567 if namespace.pylab == 'auto':
563 568 gui, backend = pylabtools.find_gui_and_backend()
564 569 else:
565 570 gui, backend = pylabtools.find_gui_and_backend(namespace.pylab)
566 571 kernel_class = kernel_classes.get(gui)
567 572 if kernel_class is None:
568 573 raise ValueError('GUI is not supported: %r' % gui)
569 574 pylabtools.activate_matplotlib(backend)
570 575
571 576 kernel = make_kernel(namespace, kernel_class, OutStream)
572 577
573 578 if namespace.pylab:
574 pylabtools.import_pylab(kernel.shell.user_ns)
579 pylabtools.import_pylab(kernel.shell.user_ns, backend,
580 shell=kernel.shell)
575 581
576 582 start_kernel(namespace, kernel)
577 583
578 584
579 585 if __name__ == '__main__':
580 586 main()
@@ -1,39 +1,112 b''
1 1 """Produce SVG versions of active plots for display by the rich Qt frontend.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Imports
5 5 #-----------------------------------------------------------------------------
6 from __future__ import print_function
6 7
7 8 # Standard library imports
8 9 from cStringIO import StringIO
9 10
10 11 # System library imports.
12 import matplotlib
11 13 from matplotlib.backends.backend_svg import new_figure_manager
12 14 from matplotlib._pylab_helpers import Gcf
13 15
14 16 # Local imports.
15 17 from backend_payload import add_plot_payload
16 18
17 19 #-----------------------------------------------------------------------------
18 20 # Functions
19 21 #-----------------------------------------------------------------------------
20 22
21 def show():
22 """ Deliver a SVG payload.
23 def show(close=True):
24 """Show all figures as SVG payloads sent to the IPython clients.
25
26 Parameters
27 ----------
28 close : bool, optional
29 If true, a ``plt.close('all')`` call is automatically issued after
30 sending all the SVG figures.
23 31 """
24 32 for figure_manager in Gcf.get_all_fig_managers():
25 # Make the background transparent.
26 # figure_manager.canvas.figure.patch.set_alpha(0.0)
27 # Set the background to white instead so it looks good on black.
28 figure_manager.canvas.figure.set_facecolor('white')
29 figure_manager.canvas.figure.set_edgecolor('white')
30 data = svg_from_canvas(figure_manager.canvas)
31 add_plot_payload('svg', data)
33 send_svg_canvas(figure_manager.canvas)
34 if close:
35 matplotlib.pyplot.close('all')
36
37 # This flag will be reset by draw_if_interactive when called
38 show._draw_called = False
39
40
41 def paste(*figs):
42 """Paste figures into the console workspace.
43
44 If no arguments are given, all available figures are pasted. If the
45 argument list contains references to invalid figures, a warning is printed
46 but the function continues pasting further figures.
47
48 Parameters
49 ----------
50 figs : tuple
51 A tuple that can contain any mixture of integers and figure objects.
52 """
53 if not figs:
54 show(close=False)
55 else:
56 fig_managers = Gcf.get_all_fig_managers()
57 fig_index = dict( [(fm.canvas.figure, fm.canvas) for fm in fig_managers]
58 + [ (fm.canvas.figure.number, fm.canvas) for fm in fig_managers] )
59
60 for fig in figs:
61 canvas = fig_index.get(fig)
62 if canvas is None:
63 print('Warning: figure %s not available.' % fig)
64 else:
65 send_svg_canvas(canvas)
66
67
68 def send_svg_canvas(canvas):
69 """Draw the current canvas and send it as an SVG payload.
70 """
71 # Make the background transparent.
72 # figure_manager.canvas.figure.patch.set_alpha(0.0)
73
74 # Set the background to white instead so it looks good on black. We store
75 # the current values to restore them at the end.
76 fc = canvas.figure.get_facecolor()
77 ec = canvas.figure.get_edgecolor()
78 canvas.figure.set_facecolor('white')
79 canvas.figure.set_edgecolor('white')
80 try:
81 add_plot_payload('svg', svg_from_canvas(canvas))
82 finally:
83 canvas.figure.set_facecolor(fc)
84 canvas.figure.set_edgecolor(ec)
32 85
33 86
34 87 def svg_from_canvas(canvas):
35 88 """ Return a string containing the SVG representation of a FigureCanvasSvg.
36 89 """
37 90 string_io = StringIO()
38 91 canvas.print_svg(string_io)
39 92 return string_io.getvalue()
93
94
95 def draw_if_interactive():
96 """
97 Is called after every pylab drawing command
98 """
99 # We simply flag we were called and otherwise do nothing. At the end of
100 # the code execution, a separate call to show_close() will act upon this.
101 show._draw_called = True
102
103
104 def flush_svg():
105 """Call show, close all open figures, sending all SVG images.
106
107 This is meant to be called automatically and will call show() if, during
108 prior code execution, there had been any calls to draw_if_interactive.
109 """
110 if show._draw_called:
111 show(close=True)
112 show._draw_called = False
General Comments 0
You need to be logged in to leave comments. Login now