##// END OF EJS Templates
Fixing small bug in activate....
Brian Granger -
Show More
@@ -1,2486 +1,2488 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Main IPython Component
4 4 """
5 5
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
8 8 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
9 9 # Copyright (C) 2008-2009 The IPython Development Team
10 10 #
11 11 # Distributed under the terms of the BSD License. The full license is in
12 12 # the file COPYING, distributed as part of this software.
13 13 #-----------------------------------------------------------------------------
14 14
15 15 #-----------------------------------------------------------------------------
16 16 # Imports
17 17 #-----------------------------------------------------------------------------
18 18
19 19 from __future__ import with_statement
20 20
21 21 import __builtin__
22 22 import StringIO
23 23 import bdb
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.core import ultratb
35 35 from IPython.core import debugger, oinspect
36 36 from IPython.core import shadowns
37 37 from IPython.core import history as ipcorehist
38 38 from IPython.core import prefilter
39 39 from IPython.core.alias import AliasManager
40 40 from IPython.core.builtin_trap import BuiltinTrap
41 41 from IPython.core.display_trap import DisplayTrap
42 42 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
43 43 from IPython.core.logger import Logger
44 44 from IPython.core.magic import Magic
45 45 from IPython.core.prompts import CachedOutput
46 46 from IPython.core.prefilter import PrefilterManager
47 47 from IPython.core.component import Component
48 48 from IPython.core.usage import interactive_usage, default_banner
49 49 from IPython.core.error import TryNext, UsageError
50 50
51 51 from IPython.utils import pickleshare
52 52 from IPython.external.Itpl import ItplNS
53 53 from IPython.lib.backgroundjobs import BackgroundJobManager
54 54 from IPython.utils.ipstruct import Struct
55 55 from IPython.utils import PyColorize
56 56 from IPython.utils.genutils import *
57 57 from IPython.utils.genutils import get_ipython_dir
58 58 from IPython.utils.platutils import toggle_set_term_title, set_term_title
59 59 from IPython.utils.strdispatch import StrDispatch
60 60 from IPython.utils.syspathcontext import prepended_to_syspath
61 61
62 62 # from IPython.utils import growl
63 63 # growl.start("IPython")
64 64
65 65 from IPython.utils.traitlets import (
66 66 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode
67 67 )
68 68
69 69 #-----------------------------------------------------------------------------
70 70 # Globals
71 71 #-----------------------------------------------------------------------------
72 72
73 73
74 74 # store the builtin raw_input globally, and use this always, in case user code
75 75 # overwrites it (like wx.py.PyShell does)
76 76 raw_input_original = raw_input
77 77
78 78 # compiled regexps for autoindent management
79 79 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
80 80
81 81
82 82 #-----------------------------------------------------------------------------
83 83 # Utilities
84 84 #-----------------------------------------------------------------------------
85 85
86 86
87 87 ini_spaces_re = re.compile(r'^(\s+)')
88 88
89 89
90 90 def num_ini_spaces(strng):
91 91 """Return the number of initial spaces in a string"""
92 92
93 93 ini_spaces = ini_spaces_re.match(strng)
94 94 if ini_spaces:
95 95 return ini_spaces.end()
96 96 else:
97 97 return 0
98 98
99 99
100 100 def softspace(file, newvalue):
101 101 """Copied from code.py, to remove the dependency"""
102 102
103 103 oldvalue = 0
104 104 try:
105 105 oldvalue = file.softspace
106 106 except AttributeError:
107 107 pass
108 108 try:
109 109 file.softspace = newvalue
110 110 except (AttributeError, TypeError):
111 111 # "attribute-less object" or "read-only attributes"
112 112 pass
113 113 return oldvalue
114 114
115 115
116 116 class SpaceInInput(exceptions.Exception): pass
117 117
118 118 class Bunch: pass
119 119
120 120 class InputList(list):
121 121 """Class to store user input.
122 122
123 123 It's basically a list, but slices return a string instead of a list, thus
124 124 allowing things like (assuming 'In' is an instance):
125 125
126 126 exec In[4:7]
127 127
128 128 or
129 129
130 130 exec In[5:9] + In[14] + In[21:25]"""
131 131
132 132 def __getslice__(self,i,j):
133 133 return ''.join(list.__getslice__(self,i,j))
134 134
135 135
136 136 class SyntaxTB(ultratb.ListTB):
137 137 """Extension which holds some state: the last exception value"""
138 138
139 139 def __init__(self,color_scheme = 'NoColor'):
140 140 ultratb.ListTB.__init__(self,color_scheme)
141 141 self.last_syntax_error = None
142 142
143 143 def __call__(self, etype, value, elist):
144 144 self.last_syntax_error = value
145 145 ultratb.ListTB.__call__(self,etype,value,elist)
146 146
147 147 def clear_err_state(self):
148 148 """Return the current error state and clear it"""
149 149 e = self.last_syntax_error
150 150 self.last_syntax_error = None
151 151 return e
152 152
153 153
154 154 def get_default_editor():
155 155 try:
156 156 ed = os.environ['EDITOR']
157 157 except KeyError:
158 158 if os.name == 'posix':
159 159 ed = 'vi' # the only one guaranteed to be there!
160 160 else:
161 161 ed = 'notepad' # same in Windows!
162 162 return ed
163 163
164 164
165 165 def get_default_colors():
166 166 if sys.platform=='darwin':
167 167 return "LightBG"
168 168 elif os.name=='nt':
169 169 return 'Linux'
170 170 else:
171 171 return 'Linux'
172 172
173 173
174 174 class SeparateStr(Str):
175 175 """A Str subclass to validate separate_in, separate_out, etc.
176 176
177 177 This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'.
178 178 """
179 179
180 180 def validate(self, obj, value):
181 181 if value == '0': value = ''
182 182 value = value.replace('\\n','\n')
183 183 return super(SeparateStr, self).validate(obj, value)
184 184
185 185
186 186 #-----------------------------------------------------------------------------
187 187 # Main IPython class
188 188 #-----------------------------------------------------------------------------
189 189
190 190
191 191 class InteractiveShell(Component, Magic):
192 192 """An enhanced, interactive shell for Python."""
193 193
194 194 autocall = Enum((0,1,2), default_value=1, config=True)
195 195 autoedit_syntax = CBool(False, config=True)
196 196 autoindent = CBool(True, config=True)
197 197 automagic = CBool(True, config=True)
198 198 banner = Str('')
199 199 banner1 = Str(default_banner, config=True)
200 200 banner2 = Str('', config=True)
201 201 cache_size = Int(1000, config=True)
202 202 color_info = CBool(True, config=True)
203 203 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
204 204 default_value=get_default_colors(), config=True)
205 205 confirm_exit = CBool(True, config=True)
206 206 debug = CBool(False, config=True)
207 207 deep_reload = CBool(False, config=True)
208 208 # This display_banner only controls whether or not self.show_banner()
209 209 # is called when mainloop/interact are called. The default is False
210 210 # because for the terminal based application, the banner behavior
211 211 # is controlled by Global.display_banner, which IPythonApp looks at
212 212 # to determine if *it* should call show_banner() by hand or not.
213 213 display_banner = CBool(False) # This isn't configurable!
214 214 embedded = CBool(False)
215 215 embedded_active = CBool(False)
216 216 editor = Str(get_default_editor(), config=True)
217 217 filename = Str("<ipython console>")
218 218 ipythondir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
219 219 logstart = CBool(False, config=True)
220 220 logfile = Str('', config=True)
221 221 logappend = Str('', config=True)
222 222 object_info_string_level = Enum((0,1,2), default_value=0,
223 223 config=True)
224 224 pager = Str('less', config=True)
225 225 pdb = CBool(False, config=True)
226 226 pprint = CBool(True, config=True)
227 227 profile = Str('', config=True)
228 228 prompt_in1 = Str('In [\\#]: ', config=True)
229 229 prompt_in2 = Str(' .\\D.: ', config=True)
230 230 prompt_out = Str('Out[\\#]: ', config=True)
231 231 prompts_pad_left = CBool(True, config=True)
232 232 quiet = CBool(False, config=True)
233 233
234 234 readline_use = CBool(True, config=True)
235 235 readline_merge_completions = CBool(True, config=True)
236 236 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
237 237 readline_remove_delims = Str('-/~', config=True)
238 238 readline_parse_and_bind = List([
239 239 'tab: complete',
240 240 '"\C-l": possible-completions',
241 241 'set show-all-if-ambiguous on',
242 242 '"\C-o": tab-insert',
243 243 '"\M-i": " "',
244 244 '"\M-o": "\d\d\d\d"',
245 245 '"\M-I": "\d\d\d\d"',
246 246 '"\C-r": reverse-search-history',
247 247 '"\C-s": forward-search-history',
248 248 '"\C-p": history-search-backward',
249 249 '"\C-n": history-search-forward',
250 250 '"\e[A": history-search-backward',
251 251 '"\e[B": history-search-forward',
252 252 '"\C-k": kill-line',
253 253 '"\C-u": unix-line-discard',
254 254 ], allow_none=False, config=True)
255 255
256 256 screen_length = Int(0, config=True)
257 257
258 258 # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n'
259 259 separate_in = SeparateStr('\n', config=True)
260 260 separate_out = SeparateStr('', config=True)
261 261 separate_out2 = SeparateStr('', config=True)
262 262
263 263 system_header = Str('IPython system call: ', config=True)
264 264 system_verbose = CBool(False, config=True)
265 265 term_title = CBool(False, config=True)
266 266 wildcards_case_sensitive = CBool(True, config=True)
267 267 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
268 268 default_value='Context', config=True)
269 269
270 270 autoexec = List(allow_none=False)
271 271
272 272 # class attribute to indicate whether the class supports threads or not.
273 273 # Subclasses with thread support should override this as needed.
274 274 isthreaded = False
275 275
276 276 def __init__(self, parent=None, config=None, ipythondir=None, usage=None,
277 277 user_ns=None, user_global_ns=None,
278 278 banner1=None, banner2=None, display_banner=None,
279 279 custom_exceptions=((),None)):
280 280
281 281 # This is where traitlets with a config_key argument are updated
282 282 # from the values on config.
283 283 super(InteractiveShell, self).__init__(parent, config=config)
284 284
285 285 # These are relatively independent and stateless
286 286 self.init_ipythondir(ipythondir)
287 287 self.init_instance_attrs()
288 288 self.init_term_title()
289 289 self.init_usage(usage)
290 290 self.init_banner(banner1, banner2, display_banner)
291 291
292 292 # Create namespaces (user_ns, user_global_ns, etc.)
293 293 self.init_create_namespaces(user_ns, user_global_ns)
294 294 # This has to be done after init_create_namespaces because it uses
295 295 # something in self.user_ns, but before init_sys_modules, which
296 296 # is the first thing to modify sys.
297 297 self.save_sys_module_state()
298 298 self.init_sys_modules()
299 299
300 300 self.init_history()
301 301 self.init_encoding()
302 302 self.init_prefilter()
303 303
304 304 Magic.__init__(self, self)
305 305
306 306 self.init_syntax_highlighting()
307 307 self.init_hooks()
308 308 self.init_pushd_popd_magic()
309 309 self.init_traceback_handlers(custom_exceptions)
310 310 self.init_user_ns()
311 311 self.init_logger()
312 312 self.init_alias()
313 313 self.init_builtins()
314 314
315 315 # pre_config_initialization
316 316 self.init_shadow_hist()
317 317
318 318 # The next section should contain averything that was in ipmaker.
319 319 self.init_logstart()
320 320
321 321 # The following was in post_config_initialization
322 322 self.init_inspector()
323 323 self.init_readline()
324 324 self.init_prompts()
325 325 self.init_displayhook()
326 326 self.init_reload_doctest()
327 327 self.init_magics()
328 328 self.init_pdb()
329 329 self.hooks.late_startup_hook()
330 330
331 331 def get_ipython(self):
332 332 return self
333 333
334 334 #-------------------------------------------------------------------------
335 335 # Traitlet changed handlers
336 336 #-------------------------------------------------------------------------
337 337
338 338 def _banner1_changed(self):
339 339 self.compute_banner()
340 340
341 341 def _banner2_changed(self):
342 342 self.compute_banner()
343 343
344 344 def _ipythondir_changed(self, name, new):
345 345 if not os.path.isdir(new):
346 346 os.makedirs(new, mode = 0777)
347 347 if not os.path.isdir(self.ipython_extension_dir):
348 348 os.makedirs(self.ipython_extension_dir, mode = 0777)
349 349
350 350 @property
351 351 def ipython_extension_dir(self):
352 352 return os.path.join(self.ipythondir, 'extensions')
353 353
354 354 @property
355 355 def usable_screen_length(self):
356 356 if self.screen_length == 0:
357 357 return 0
358 358 else:
359 359 num_lines_bot = self.separate_in.count('\n')+1
360 360 return self.screen_length - num_lines_bot
361 361
362 362 def _term_title_changed(self, name, new_value):
363 363 self.init_term_title()
364 364
365 365 def set_autoindent(self,value=None):
366 366 """Set the autoindent flag, checking for readline support.
367 367
368 368 If called with no arguments, it acts as a toggle."""
369 369
370 370 if not self.has_readline:
371 371 if os.name == 'posix':
372 372 warn("The auto-indent feature requires the readline library")
373 373 self.autoindent = 0
374 374 return
375 375 if value is None:
376 376 self.autoindent = not self.autoindent
377 377 else:
378 378 self.autoindent = value
379 379
380 380 #-------------------------------------------------------------------------
381 381 # init_* methods called by __init__
382 382 #-------------------------------------------------------------------------
383 383
384 384 def init_ipythondir(self, ipythondir):
385 385 if ipythondir is not None:
386 386 self.ipythondir = ipythondir
387 387 self.config.Global.ipythondir = self.ipythondir
388 388 return
389 389
390 390 if hasattr(self.config.Global, 'ipythondir'):
391 391 self.ipythondir = self.config.Global.ipythondir
392 392 else:
393 393 self.ipythondir = get_ipython_dir()
394 394
395 395 # All children can just read this
396 396 self.config.Global.ipythondir = self.ipythondir
397 397
398 398 def init_instance_attrs(self):
399 399 self.jobs = BackgroundJobManager()
400 400 self.more = False
401 401
402 402 # command compiler
403 403 self.compile = codeop.CommandCompiler()
404 404
405 405 # User input buffer
406 406 self.buffer = []
407 407
408 408 # Make an empty namespace, which extension writers can rely on both
409 409 # existing and NEVER being used by ipython itself. This gives them a
410 410 # convenient location for storing additional information and state
411 411 # their extensions may require, without fear of collisions with other
412 412 # ipython names that may develop later.
413 413 self.meta = Struct()
414 414
415 415 # Object variable to store code object waiting execution. This is
416 416 # used mainly by the multithreaded shells, but it can come in handy in
417 417 # other situations. No need to use a Queue here, since it's a single
418 418 # item which gets cleared once run.
419 419 self.code_to_run = None
420 420
421 421 # Flag to mark unconditional exit
422 422 self.exit_now = False
423 423
424 424 # Temporary files used for various purposes. Deleted at exit.
425 425 self.tempfiles = []
426 426
427 427 # Keep track of readline usage (later set by init_readline)
428 428 self.has_readline = False
429 429
430 430 # keep track of where we started running (mainly for crash post-mortem)
431 431 # This is not being used anywhere currently.
432 432 self.starting_dir = os.getcwd()
433 433
434 434 # Indentation management
435 435 self.indent_current_nsp = 0
436 436
437 437 def init_term_title(self):
438 438 # Enable or disable the terminal title.
439 439 if self.term_title:
440 440 toggle_set_term_title(True)
441 441 set_term_title('IPython: ' + abbrev_cwd())
442 442 else:
443 443 toggle_set_term_title(False)
444 444
445 445 def init_usage(self, usage=None):
446 446 if usage is None:
447 447 self.usage = interactive_usage
448 448 else:
449 449 self.usage = usage
450 450
451 451 def init_encoding(self):
452 452 # Get system encoding at startup time. Certain terminals (like Emacs
453 453 # under Win32 have it set to None, and we need to have a known valid
454 454 # encoding to use in the raw_input() method
455 455 try:
456 456 self.stdin_encoding = sys.stdin.encoding or 'ascii'
457 457 except AttributeError:
458 458 self.stdin_encoding = 'ascii'
459 459
460 460 def init_syntax_highlighting(self):
461 461 # Python source parser/formatter for syntax highlighting
462 462 pyformat = PyColorize.Parser().format
463 463 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
464 464
465 465 def init_pushd_popd_magic(self):
466 466 # for pushd/popd management
467 467 try:
468 468 self.home_dir = get_home_dir()
469 469 except HomeDirError, msg:
470 470 fatal(msg)
471 471
472 472 self.dir_stack = []
473 473
474 474 def init_logger(self):
475 475 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
476 476 # local shortcut, this is used a LOT
477 477 self.log = self.logger.log
478 478
479 479 def init_logstart(self):
480 480 if self.logappend:
481 481 self.magic_logstart(self.logappend + ' append')
482 482 elif self.logfile:
483 483 self.magic_logstart(self.logfile)
484 484 elif self.logstart:
485 485 self.magic_logstart()
486 486
487 487 def init_builtins(self):
488 488 self.builtin_trap = BuiltinTrap(self)
489 489
490 490 def init_inspector(self):
491 491 # Object inspector
492 492 self.inspector = oinspect.Inspector(oinspect.InspectColors,
493 493 PyColorize.ANSICodeColors,
494 494 'NoColor',
495 495 self.object_info_string_level)
496 496
497 497 def init_prompts(self):
498 498 # Initialize cache, set in/out prompts and printing system
499 499 self.outputcache = CachedOutput(self,
500 500 self.cache_size,
501 501 self.pprint,
502 502 input_sep = self.separate_in,
503 503 output_sep = self.separate_out,
504 504 output_sep2 = self.separate_out2,
505 505 ps1 = self.prompt_in1,
506 506 ps2 = self.prompt_in2,
507 507 ps_out = self.prompt_out,
508 508 pad_left = self.prompts_pad_left)
509 509
510 510 # user may have over-ridden the default print hook:
511 511 try:
512 512 self.outputcache.__class__.display = self.hooks.display
513 513 except AttributeError:
514 514 pass
515 515
516 516 def init_displayhook(self):
517 517 self.display_trap = DisplayTrap(self, self.outputcache)
518 518
519 519 def init_reload_doctest(self):
520 520 # Do a proper resetting of doctest, including the necessary displayhook
521 521 # monkeypatching
522 522 try:
523 523 doctest_reload()
524 524 except ImportError:
525 525 warn("doctest module does not exist.")
526 526
527 527 #-------------------------------------------------------------------------
528 528 # Things related to the banner
529 529 #-------------------------------------------------------------------------
530 530
531 531 def init_banner(self, banner1, banner2, display_banner):
532 532 if banner1 is not None:
533 533 self.banner1 = banner1
534 534 if banner2 is not None:
535 535 self.banner2 = banner2
536 536 if display_banner is not None:
537 537 self.display_banner = display_banner
538 538 self.compute_banner()
539 539
540 540 def show_banner(self, banner=None):
541 541 if banner is None:
542 542 banner = self.banner
543 543 self.write(banner)
544 544
545 545 def compute_banner(self):
546 546 self.banner = self.banner1 + '\n'
547 547 if self.profile:
548 548 self.banner += '\nIPython profile: %s\n' % self.profile
549 549 if self.banner2:
550 550 self.banner += '\n' + self.banner2 + '\n'
551 551
552 552 #-------------------------------------------------------------------------
553 553 # Things related to injections into the sys module
554 554 #-------------------------------------------------------------------------
555 555
556 556 def save_sys_module_state(self):
557 557 """Save the state of hooks in the sys module.
558 558
559 559 This has to be called after self.user_ns is created.
560 560 """
561 561 self._orig_sys_module_state = {}
562 562 self._orig_sys_module_state['stdin'] = sys.stdin
563 563 self._orig_sys_module_state['stdout'] = sys.stdout
564 564 self._orig_sys_module_state['stderr'] = sys.stderr
565 565 self._orig_sys_module_state['excepthook'] = sys.excepthook
566 566 try:
567 567 self._orig_sys_modules_main_name = self.user_ns['__name__']
568 568 except KeyError:
569 569 pass
570 570
571 571 def restore_sys_module_state(self):
572 572 """Restore the state of the sys module."""
573 573 try:
574 574 for k, v in self._orig_sys_module_state.items():
575 575 setattr(sys, k, v)
576 576 except AttributeError:
577 577 pass
578 578 try:
579 579 delattr(sys, 'ipcompleter')
580 580 except AttributeError:
581 581 pass
582 582 # Reset what what done in self.init_sys_modules
583 583 try:
584 584 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
585 585 except (AttributeError, KeyError):
586 586 pass
587 587
588 588 #-------------------------------------------------------------------------
589 589 # Things related to hooks
590 590 #-------------------------------------------------------------------------
591 591
592 592 def init_hooks(self):
593 593 # hooks holds pointers used for user-side customizations
594 594 self.hooks = Struct()
595 595
596 596 self.strdispatchers = {}
597 597
598 598 # Set all default hooks, defined in the IPython.hooks module.
599 599 import IPython.core.hooks
600 600 hooks = IPython.core.hooks
601 601 for hook_name in hooks.__all__:
602 602 # default hooks have priority 100, i.e. low; user hooks should have
603 603 # 0-100 priority
604 604 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
605 605
606 606 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
607 607 """set_hook(name,hook) -> sets an internal IPython hook.
608 608
609 609 IPython exposes some of its internal API as user-modifiable hooks. By
610 610 adding your function to one of these hooks, you can modify IPython's
611 611 behavior to call at runtime your own routines."""
612 612
613 613 # At some point in the future, this should validate the hook before it
614 614 # accepts it. Probably at least check that the hook takes the number
615 615 # of args it's supposed to.
616 616
617 617 f = new.instancemethod(hook,self,self.__class__)
618 618
619 619 # check if the hook is for strdispatcher first
620 620 if str_key is not None:
621 621 sdp = self.strdispatchers.get(name, StrDispatch())
622 622 sdp.add_s(str_key, f, priority )
623 623 self.strdispatchers[name] = sdp
624 624 return
625 625 if re_key is not None:
626 626 sdp = self.strdispatchers.get(name, StrDispatch())
627 627 sdp.add_re(re.compile(re_key), f, priority )
628 628 self.strdispatchers[name] = sdp
629 629 return
630 630
631 631 dp = getattr(self.hooks, name, None)
632 632 if name not in IPython.core.hooks.__all__:
633 633 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
634 634 if not dp:
635 635 dp = IPython.core.hooks.CommandChainDispatcher()
636 636
637 637 try:
638 638 dp.add(f,priority)
639 639 except AttributeError:
640 640 # it was not commandchain, plain old func - replace
641 641 dp = f
642 642
643 643 setattr(self.hooks,name, dp)
644 644
645 645 #-------------------------------------------------------------------------
646 646 # Things related to the "main" module
647 647 #-------------------------------------------------------------------------
648 648
649 649 def new_main_mod(self,ns=None):
650 650 """Return a new 'main' module object for user code execution.
651 651 """
652 652 main_mod = self._user_main_module
653 653 init_fakemod_dict(main_mod,ns)
654 654 return main_mod
655 655
656 656 def cache_main_mod(self,ns,fname):
657 657 """Cache a main module's namespace.
658 658
659 659 When scripts are executed via %run, we must keep a reference to the
660 660 namespace of their __main__ module (a FakeModule instance) around so
661 661 that Python doesn't clear it, rendering objects defined therein
662 662 useless.
663 663
664 664 This method keeps said reference in a private dict, keyed by the
665 665 absolute path of the module object (which corresponds to the script
666 666 path). This way, for multiple executions of the same script we only
667 667 keep one copy of the namespace (the last one), thus preventing memory
668 668 leaks from old references while allowing the objects from the last
669 669 execution to be accessible.
670 670
671 671 Note: we can not allow the actual FakeModule instances to be deleted,
672 672 because of how Python tears down modules (it hard-sets all their
673 673 references to None without regard for reference counts). This method
674 674 must therefore make a *copy* of the given namespace, to allow the
675 675 original module's __dict__ to be cleared and reused.
676 676
677 677
678 678 Parameters
679 679 ----------
680 680 ns : a namespace (a dict, typically)
681 681
682 682 fname : str
683 683 Filename associated with the namespace.
684 684
685 685 Examples
686 686 --------
687 687
688 688 In [10]: import IPython
689 689
690 690 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
691 691
692 692 In [12]: IPython.__file__ in _ip._main_ns_cache
693 693 Out[12]: True
694 694 """
695 695 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
696 696
697 697 def clear_main_mod_cache(self):
698 698 """Clear the cache of main modules.
699 699
700 700 Mainly for use by utilities like %reset.
701 701
702 702 Examples
703 703 --------
704 704
705 705 In [15]: import IPython
706 706
707 707 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
708 708
709 709 In [17]: len(_ip._main_ns_cache) > 0
710 710 Out[17]: True
711 711
712 712 In [18]: _ip.clear_main_mod_cache()
713 713
714 714 In [19]: len(_ip._main_ns_cache) == 0
715 715 Out[19]: True
716 716 """
717 717 self._main_ns_cache.clear()
718 718
719 719 #-------------------------------------------------------------------------
720 720 # Things related to debugging
721 721 #-------------------------------------------------------------------------
722 722
723 723 def init_pdb(self):
724 724 # Set calling of pdb on exceptions
725 725 # self.call_pdb is a property
726 726 self.call_pdb = self.pdb
727 727
728 728 def _get_call_pdb(self):
729 729 return self._call_pdb
730 730
731 731 def _set_call_pdb(self,val):
732 732
733 733 if val not in (0,1,False,True):
734 734 raise ValueError,'new call_pdb value must be boolean'
735 735
736 736 # store value in instance
737 737 self._call_pdb = val
738 738
739 739 # notify the actual exception handlers
740 740 self.InteractiveTB.call_pdb = val
741 741 if self.isthreaded:
742 742 try:
743 743 self.sys_excepthook.call_pdb = val
744 744 except:
745 745 warn('Failed to activate pdb for threaded exception handler')
746 746
747 747 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
748 748 'Control auto-activation of pdb at exceptions')
749 749
750 750 def debugger(self,force=False):
751 751 """Call the pydb/pdb debugger.
752 752
753 753 Keywords:
754 754
755 755 - force(False): by default, this routine checks the instance call_pdb
756 756 flag and does not actually invoke the debugger if the flag is false.
757 757 The 'force' option forces the debugger to activate even if the flag
758 758 is false.
759 759 """
760 760
761 761 if not (force or self.call_pdb):
762 762 return
763 763
764 764 if not hasattr(sys,'last_traceback'):
765 765 error('No traceback has been produced, nothing to debug.')
766 766 return
767 767
768 768 # use pydb if available
769 769 if debugger.has_pydb:
770 770 from pydb import pm
771 771 else:
772 772 # fallback to our internal debugger
773 773 pm = lambda : self.InteractiveTB.debugger(force=True)
774 774 self.history_saving_wrapper(pm)()
775 775
776 776 #-------------------------------------------------------------------------
777 777 # Things related to IPython's various namespaces
778 778 #-------------------------------------------------------------------------
779 779
780 780 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
781 781 # Create the namespace where the user will operate. user_ns is
782 782 # normally the only one used, and it is passed to the exec calls as
783 783 # the locals argument. But we do carry a user_global_ns namespace
784 784 # given as the exec 'globals' argument, This is useful in embedding
785 785 # situations where the ipython shell opens in a context where the
786 786 # distinction between locals and globals is meaningful. For
787 787 # non-embedded contexts, it is just the same object as the user_ns dict.
788 788
789 789 # FIXME. For some strange reason, __builtins__ is showing up at user
790 790 # level as a dict instead of a module. This is a manual fix, but I
791 791 # should really track down where the problem is coming from. Alex
792 792 # Schmolck reported this problem first.
793 793
794 794 # A useful post by Alex Martelli on this topic:
795 795 # Re: inconsistent value from __builtins__
796 796 # Von: Alex Martelli <aleaxit@yahoo.com>
797 797 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
798 798 # Gruppen: comp.lang.python
799 799
800 800 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
801 801 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
802 802 # > <type 'dict'>
803 803 # > >>> print type(__builtins__)
804 804 # > <type 'module'>
805 805 # > Is this difference in return value intentional?
806 806
807 807 # Well, it's documented that '__builtins__' can be either a dictionary
808 808 # or a module, and it's been that way for a long time. Whether it's
809 809 # intentional (or sensible), I don't know. In any case, the idea is
810 810 # that if you need to access the built-in namespace directly, you
811 811 # should start with "import __builtin__" (note, no 's') which will
812 812 # definitely give you a module. Yeah, it's somewhat confusing:-(.
813 813
814 814 # These routines return properly built dicts as needed by the rest of
815 815 # the code, and can also be used by extension writers to generate
816 816 # properly initialized namespaces.
817 817 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
818 818 user_global_ns)
819 819
820 820 # Assign namespaces
821 821 # This is the namespace where all normal user variables live
822 822 self.user_ns = user_ns
823 823 self.user_global_ns = user_global_ns
824 824
825 825 # An auxiliary namespace that checks what parts of the user_ns were
826 826 # loaded at startup, so we can list later only variables defined in
827 827 # actual interactive use. Since it is always a subset of user_ns, it
828 828 # doesn't need to be seaparately tracked in the ns_table
829 829 self.user_config_ns = {}
830 830
831 831 # A namespace to keep track of internal data structures to prevent
832 832 # them from cluttering user-visible stuff. Will be updated later
833 833 self.internal_ns = {}
834 834
835 835 # Now that FakeModule produces a real module, we've run into a nasty
836 836 # problem: after script execution (via %run), the module where the user
837 837 # code ran is deleted. Now that this object is a true module (needed
838 838 # so docetst and other tools work correctly), the Python module
839 839 # teardown mechanism runs over it, and sets to None every variable
840 840 # present in that module. Top-level references to objects from the
841 841 # script survive, because the user_ns is updated with them. However,
842 842 # calling functions defined in the script that use other things from
843 843 # the script will fail, because the function's closure had references
844 844 # to the original objects, which are now all None. So we must protect
845 845 # these modules from deletion by keeping a cache.
846 846 #
847 847 # To avoid keeping stale modules around (we only need the one from the
848 848 # last run), we use a dict keyed with the full path to the script, so
849 849 # only the last version of the module is held in the cache. Note,
850 850 # however, that we must cache the module *namespace contents* (their
851 851 # __dict__). Because if we try to cache the actual modules, old ones
852 852 # (uncached) could be destroyed while still holding references (such as
853 853 # those held by GUI objects that tend to be long-lived)>
854 854 #
855 855 # The %reset command will flush this cache. See the cache_main_mod()
856 856 # and clear_main_mod_cache() methods for details on use.
857 857
858 858 # This is the cache used for 'main' namespaces
859 859 self._main_ns_cache = {}
860 860 # And this is the single instance of FakeModule whose __dict__ we keep
861 861 # copying and clearing for reuse on each %run
862 862 self._user_main_module = FakeModule()
863 863
864 864 # A table holding all the namespaces IPython deals with, so that
865 865 # introspection facilities can search easily.
866 866 self.ns_table = {'user':user_ns,
867 867 'user_global':user_global_ns,
868 868 'internal':self.internal_ns,
869 869 'builtin':__builtin__.__dict__
870 870 }
871 871
872 872 # Similarly, track all namespaces where references can be held and that
873 873 # we can safely clear (so it can NOT include builtin). This one can be
874 874 # a simple list.
875 875 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
876 876 self.internal_ns, self._main_ns_cache ]
877 877
878 878 def init_sys_modules(self):
879 879 # We need to insert into sys.modules something that looks like a
880 880 # module but which accesses the IPython namespace, for shelve and
881 881 # pickle to work interactively. Normally they rely on getting
882 882 # everything out of __main__, but for embedding purposes each IPython
883 883 # instance has its own private namespace, so we can't go shoving
884 884 # everything into __main__.
885 885
886 886 # note, however, that we should only do this for non-embedded
887 887 # ipythons, which really mimic the __main__.__dict__ with their own
888 888 # namespace. Embedded instances, on the other hand, should not do
889 889 # this because they need to manage the user local/global namespaces
890 890 # only, but they live within a 'normal' __main__ (meaning, they
891 891 # shouldn't overtake the execution environment of the script they're
892 892 # embedded in).
893 893
894 894 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
895 895
896 896 try:
897 897 main_name = self.user_ns['__name__']
898 898 except KeyError:
899 899 raise KeyError('user_ns dictionary MUST have a "__name__" key')
900 900 else:
901 901 sys.modules[main_name] = FakeModule(self.user_ns)
902 902
903 903 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
904 904 """Return a valid local and global user interactive namespaces.
905 905
906 906 This builds a dict with the minimal information needed to operate as a
907 907 valid IPython user namespace, which you can pass to the various
908 908 embedding classes in ipython. The default implementation returns the
909 909 same dict for both the locals and the globals to allow functions to
910 910 refer to variables in the namespace. Customized implementations can
911 911 return different dicts. The locals dictionary can actually be anything
912 912 following the basic mapping protocol of a dict, but the globals dict
913 913 must be a true dict, not even a subclass. It is recommended that any
914 914 custom object for the locals namespace synchronize with the globals
915 915 dict somehow.
916 916
917 917 Raises TypeError if the provided globals namespace is not a true dict.
918 918
919 919 :Parameters:
920 920 user_ns : dict-like, optional
921 921 The current user namespace. The items in this namespace should
922 922 be included in the output. If None, an appropriate blank
923 923 namespace should be created.
924 924 user_global_ns : dict, optional
925 925 The current user global namespace. The items in this namespace
926 926 should be included in the output. If None, an appropriate
927 927 blank namespace should be created.
928 928
929 929 :Returns:
930 930 A tuple pair of dictionary-like object to be used as the local namespace
931 931 of the interpreter and a dict to be used as the global namespace.
932 932 """
933 933
934 934 if user_ns is None:
935 935 # Set __name__ to __main__ to better match the behavior of the
936 936 # normal interpreter.
937 937 user_ns = {'__name__' :'__main__',
938 938 '__builtins__' : __builtin__,
939 939 }
940 940 else:
941 941 user_ns.setdefault('__name__','__main__')
942 942 user_ns.setdefault('__builtins__',__builtin__)
943 943
944 944 if user_global_ns is None:
945 945 user_global_ns = user_ns
946 946 if type(user_global_ns) is not dict:
947 947 raise TypeError("user_global_ns must be a true dict; got %r"
948 948 % type(user_global_ns))
949 949
950 950 return user_ns, user_global_ns
951 951
952 952 def init_user_ns(self):
953 953 """Initialize all user-visible namespaces to their minimum defaults.
954 954
955 955 Certain history lists are also initialized here, as they effectively
956 956 act as user namespaces.
957 957
958 958 Notes
959 959 -----
960 960 All data structures here are only filled in, they are NOT reset by this
961 961 method. If they were not empty before, data will simply be added to
962 962 therm.
963 963 """
964 964 # Store myself as the public api!!!
965 965 self.user_ns['get_ipython'] = self.get_ipython
966 966
967 967 # make global variables for user access to the histories
968 968 self.user_ns['_ih'] = self.input_hist
969 969 self.user_ns['_oh'] = self.output_hist
970 970 self.user_ns['_dh'] = self.dir_hist
971 971
972 972 # user aliases to input and output histories
973 973 self.user_ns['In'] = self.input_hist
974 974 self.user_ns['Out'] = self.output_hist
975 975
976 976 self.user_ns['_sh'] = shadowns
977 977
978 978 # Put 'help' in the user namespace
979 979 try:
980 980 from site import _Helper
981 981 self.user_ns['help'] = _Helper()
982 982 except ImportError:
983 983 warn('help() not available - check site.py')
984 984
985 985 def reset(self):
986 986 """Clear all internal namespaces.
987 987
988 988 Note that this is much more aggressive than %reset, since it clears
989 989 fully all namespaces, as well as all input/output lists.
990 990 """
991 991 for ns in self.ns_refs_table:
992 992 ns.clear()
993 993
994 994 self.alias_manager.clear_aliases()
995 995
996 996 # Clear input and output histories
997 997 self.input_hist[:] = []
998 998 self.input_hist_raw[:] = []
999 999 self.output_hist.clear()
1000 1000
1001 1001 # Restore the user namespaces to minimal usability
1002 1002 self.init_user_ns()
1003 1003
1004 1004 # Restore the default and user aliases
1005 1005 self.alias_manager.init_aliases()
1006 1006
1007 1007 def push(self, variables, interactive=True):
1008 1008 """Inject a group of variables into the IPython user namespace.
1009 1009
1010 1010 Parameters
1011 1011 ----------
1012 1012 variables : dict, str or list/tuple of str
1013 1013 The variables to inject into the user's namespace. If a dict,
1014 1014 a simple update is done. If a str, the string is assumed to
1015 1015 have variable names separated by spaces. A list/tuple of str
1016 1016 can also be used to give the variable names. If just the variable
1017 1017 names are give (list/tuple/str) then the variable values looked
1018 1018 up in the callers frame.
1019 1019 interactive : bool
1020 1020 If True (default), the variables will be listed with the ``who``
1021 1021 magic.
1022 1022 """
1023 1023 vdict = None
1024 1024
1025 1025 # We need a dict of name/value pairs to do namespace updates.
1026 1026 if isinstance(variables, dict):
1027 1027 vdict = variables
1028 1028 elif isinstance(variables, (basestring, list, tuple)):
1029 1029 if isinstance(variables, basestring):
1030 1030 vlist = variables.split()
1031 1031 else:
1032 1032 vlist = variables
1033 1033 vdict = {}
1034 1034 cf = sys._getframe(1)
1035 1035 for name in vlist:
1036 1036 try:
1037 1037 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1038 1038 except:
1039 1039 print ('Could not get variable %s from %s' %
1040 1040 (name,cf.f_code.co_name))
1041 1041 else:
1042 1042 raise ValueError('variables must be a dict/str/list/tuple')
1043 1043
1044 1044 # Propagate variables to user namespace
1045 1045 self.user_ns.update(vdict)
1046 1046
1047 1047 # And configure interactive visibility
1048 1048 config_ns = self.user_config_ns
1049 1049 if interactive:
1050 1050 for name, val in vdict.iteritems():
1051 1051 config_ns.pop(name, None)
1052 1052 else:
1053 1053 for name,val in vdict.iteritems():
1054 1054 config_ns[name] = val
1055 1055
1056 1056 #-------------------------------------------------------------------------
1057 1057 # Things related to history management
1058 1058 #-------------------------------------------------------------------------
1059 1059
1060 1060 def init_history(self):
1061 1061 # List of input with multi-line handling.
1062 1062 self.input_hist = InputList()
1063 1063 # This one will hold the 'raw' input history, without any
1064 1064 # pre-processing. This will allow users to retrieve the input just as
1065 1065 # it was exactly typed in by the user, with %hist -r.
1066 1066 self.input_hist_raw = InputList()
1067 1067
1068 1068 # list of visited directories
1069 1069 try:
1070 1070 self.dir_hist = [os.getcwd()]
1071 1071 except OSError:
1072 1072 self.dir_hist = []
1073 1073
1074 1074 # dict of output history
1075 1075 self.output_hist = {}
1076 1076
1077 1077 # Now the history file
1078 1078 if self.profile:
1079 1079 histfname = 'history-%s' % self.profile
1080 1080 else:
1081 1081 histfname = 'history'
1082 1082 self.histfile = os.path.join(self.ipythondir, histfname)
1083 1083
1084 1084 # Fill the history zero entry, user counter starts at 1
1085 1085 self.input_hist.append('\n')
1086 1086 self.input_hist_raw.append('\n')
1087 1087
1088 1088 def init_shadow_hist(self):
1089 1089 try:
1090 1090 self.db = pickleshare.PickleShareDB(self.ipythondir + "/db")
1091 1091 except exceptions.UnicodeDecodeError:
1092 1092 print "Your ipythondir can't be decoded to unicode!"
1093 1093 print "Please set HOME environment variable to something that"
1094 1094 print r"only has ASCII characters, e.g. c:\home"
1095 1095 print "Now it is", self.ipythondir
1096 1096 sys.exit()
1097 1097 self.shadowhist = ipcorehist.ShadowHist(self.db)
1098 1098
1099 1099 def savehist(self):
1100 1100 """Save input history to a file (via readline library)."""
1101 1101
1102 1102 if not self.has_readline:
1103 1103 return
1104 1104
1105 1105 try:
1106 1106 self.readline.write_history_file(self.histfile)
1107 1107 except:
1108 1108 print 'Unable to save IPython command history to file: ' + \
1109 1109 `self.histfile`
1110 1110
1111 1111 def reloadhist(self):
1112 1112 """Reload the input history from disk file."""
1113 1113
1114 1114 if self.has_readline:
1115 1115 try:
1116 1116 self.readline.clear_history()
1117 1117 self.readline.read_history_file(self.shell.histfile)
1118 1118 except AttributeError:
1119 1119 pass
1120 1120
1121 1121 def history_saving_wrapper(self, func):
1122 1122 """ Wrap func for readline history saving
1123 1123
1124 1124 Convert func into callable that saves & restores
1125 1125 history around the call """
1126 1126
1127 1127 if not self.has_readline:
1128 1128 return func
1129 1129
1130 1130 def wrapper():
1131 1131 self.savehist()
1132 1132 try:
1133 1133 func()
1134 1134 finally:
1135 1135 readline.read_history_file(self.histfile)
1136 1136 return wrapper
1137 1137
1138 1138 #-------------------------------------------------------------------------
1139 1139 # Things related to exception handling and tracebacks (not debugging)
1140 1140 #-------------------------------------------------------------------------
1141 1141
1142 1142 def init_traceback_handlers(self, custom_exceptions):
1143 1143 # Syntax error handler.
1144 1144 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1145 1145
1146 1146 # The interactive one is initialized with an offset, meaning we always
1147 1147 # want to remove the topmost item in the traceback, which is our own
1148 1148 # internal code. Valid modes: ['Plain','Context','Verbose']
1149 1149 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1150 1150 color_scheme='NoColor',
1151 1151 tb_offset = 1)
1152 1152
1153 1153 # IPython itself shouldn't crash. This will produce a detailed
1154 1154 # post-mortem if it does. But we only install the crash handler for
1155 1155 # non-threaded shells, the threaded ones use a normal verbose reporter
1156 1156 # and lose the crash handler. This is because exceptions in the main
1157 1157 # thread (such as in GUI code) propagate directly to sys.excepthook,
1158 1158 # and there's no point in printing crash dumps for every user exception.
1159 1159 if self.isthreaded:
1160 1160 ipCrashHandler = ultratb.FormattedTB()
1161 1161 else:
1162 1162 from IPython.core import crashhandler
1163 1163 ipCrashHandler = crashhandler.IPythonCrashHandler(self)
1164 1164 self.set_crash_handler(ipCrashHandler)
1165 1165
1166 1166 # and add any custom exception handlers the user may have specified
1167 1167 self.set_custom_exc(*custom_exceptions)
1168 1168
1169 1169 def set_crash_handler(self, crashHandler):
1170 1170 """Set the IPython crash handler.
1171 1171
1172 1172 This must be a callable with a signature suitable for use as
1173 1173 sys.excepthook."""
1174 1174
1175 1175 # Install the given crash handler as the Python exception hook
1176 1176 sys.excepthook = crashHandler
1177 1177
1178 1178 # The instance will store a pointer to this, so that runtime code
1179 1179 # (such as magics) can access it. This is because during the
1180 1180 # read-eval loop, it gets temporarily overwritten (to deal with GUI
1181 1181 # frameworks).
1182 1182 self.sys_excepthook = sys.excepthook
1183 1183
1184 1184 def set_custom_exc(self,exc_tuple,handler):
1185 1185 """set_custom_exc(exc_tuple,handler)
1186 1186
1187 1187 Set a custom exception handler, which will be called if any of the
1188 1188 exceptions in exc_tuple occur in the mainloop (specifically, in the
1189 1189 runcode() method.
1190 1190
1191 1191 Inputs:
1192 1192
1193 1193 - exc_tuple: a *tuple* of valid exceptions to call the defined
1194 1194 handler for. It is very important that you use a tuple, and NOT A
1195 1195 LIST here, because of the way Python's except statement works. If
1196 1196 you only want to trap a single exception, use a singleton tuple:
1197 1197
1198 1198 exc_tuple == (MyCustomException,)
1199 1199
1200 1200 - handler: this must be defined as a function with the following
1201 1201 basic interface: def my_handler(self,etype,value,tb).
1202 1202
1203 1203 This will be made into an instance method (via new.instancemethod)
1204 1204 of IPython itself, and it will be called if any of the exceptions
1205 1205 listed in the exc_tuple are caught. If the handler is None, an
1206 1206 internal basic one is used, which just prints basic info.
1207 1207
1208 1208 WARNING: by putting in your own exception handler into IPython's main
1209 1209 execution loop, you run a very good chance of nasty crashes. This
1210 1210 facility should only be used if you really know what you are doing."""
1211 1211
1212 1212 assert type(exc_tuple)==type(()) , \
1213 1213 "The custom exceptions must be given AS A TUPLE."
1214 1214
1215 1215 def dummy_handler(self,etype,value,tb):
1216 1216 print '*** Simple custom exception handler ***'
1217 1217 print 'Exception type :',etype
1218 1218 print 'Exception value:',value
1219 1219 print 'Traceback :',tb
1220 1220 print 'Source code :','\n'.join(self.buffer)
1221 1221
1222 1222 if handler is None: handler = dummy_handler
1223 1223
1224 1224 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1225 1225 self.custom_exceptions = exc_tuple
1226 1226
1227 1227 def excepthook(self, etype, value, tb):
1228 1228 """One more defense for GUI apps that call sys.excepthook.
1229 1229
1230 1230 GUI frameworks like wxPython trap exceptions and call
1231 1231 sys.excepthook themselves. I guess this is a feature that
1232 1232 enables them to keep running after exceptions that would
1233 1233 otherwise kill their mainloop. This is a bother for IPython
1234 1234 which excepts to catch all of the program exceptions with a try:
1235 1235 except: statement.
1236 1236
1237 1237 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1238 1238 any app directly invokes sys.excepthook, it will look to the user like
1239 1239 IPython crashed. In order to work around this, we can disable the
1240 1240 CrashHandler and replace it with this excepthook instead, which prints a
1241 1241 regular traceback using our InteractiveTB. In this fashion, apps which
1242 1242 call sys.excepthook will generate a regular-looking exception from
1243 1243 IPython, and the CrashHandler will only be triggered by real IPython
1244 1244 crashes.
1245 1245
1246 1246 This hook should be used sparingly, only in places which are not likely
1247 1247 to be true IPython errors.
1248 1248 """
1249 1249 self.showtraceback((etype,value,tb),tb_offset=0)
1250 1250
1251 1251 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1252 1252 """Display the exception that just occurred.
1253 1253
1254 1254 If nothing is known about the exception, this is the method which
1255 1255 should be used throughout the code for presenting user tracebacks,
1256 1256 rather than directly invoking the InteractiveTB object.
1257 1257
1258 1258 A specific showsyntaxerror() also exists, but this method can take
1259 1259 care of calling it if needed, so unless you are explicitly catching a
1260 1260 SyntaxError exception, don't try to analyze the stack manually and
1261 1261 simply call this method."""
1262 1262
1263 1263
1264 1264 # Though this won't be called by syntax errors in the input line,
1265 1265 # there may be SyntaxError cases whith imported code.
1266 1266
1267 1267 try:
1268 1268 if exc_tuple is None:
1269 1269 etype, value, tb = sys.exc_info()
1270 1270 else:
1271 1271 etype, value, tb = exc_tuple
1272 1272
1273 1273 if etype is SyntaxError:
1274 1274 self.showsyntaxerror(filename)
1275 1275 elif etype is UsageError:
1276 1276 print "UsageError:", value
1277 1277 else:
1278 1278 # WARNING: these variables are somewhat deprecated and not
1279 1279 # necessarily safe to use in a threaded environment, but tools
1280 1280 # like pdb depend on their existence, so let's set them. If we
1281 1281 # find problems in the field, we'll need to revisit their use.
1282 1282 sys.last_type = etype
1283 1283 sys.last_value = value
1284 1284 sys.last_traceback = tb
1285 1285
1286 1286 if etype in self.custom_exceptions:
1287 1287 self.CustomTB(etype,value,tb)
1288 1288 else:
1289 1289 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1290 1290 if self.InteractiveTB.call_pdb and self.has_readline:
1291 1291 # pdb mucks up readline, fix it back
1292 1292 self.set_completer()
1293 1293 except KeyboardInterrupt:
1294 1294 self.write("\nKeyboardInterrupt\n")
1295 1295
1296 1296 def showsyntaxerror(self, filename=None):
1297 1297 """Display the syntax error that just occurred.
1298 1298
1299 1299 This doesn't display a stack trace because there isn't one.
1300 1300
1301 1301 If a filename is given, it is stuffed in the exception instead
1302 1302 of what was there before (because Python's parser always uses
1303 1303 "<string>" when reading from a string).
1304 1304 """
1305 1305 etype, value, last_traceback = sys.exc_info()
1306 1306
1307 1307 # See note about these variables in showtraceback() below
1308 1308 sys.last_type = etype
1309 1309 sys.last_value = value
1310 1310 sys.last_traceback = last_traceback
1311 1311
1312 1312 if filename and etype is SyntaxError:
1313 1313 # Work hard to stuff the correct filename in the exception
1314 1314 try:
1315 1315 msg, (dummy_filename, lineno, offset, line) = value
1316 1316 except:
1317 1317 # Not the format we expect; leave it alone
1318 1318 pass
1319 1319 else:
1320 1320 # Stuff in the right filename
1321 1321 try:
1322 1322 # Assume SyntaxError is a class exception
1323 1323 value = SyntaxError(msg, (filename, lineno, offset, line))
1324 1324 except:
1325 1325 # If that failed, assume SyntaxError is a string
1326 1326 value = msg, (filename, lineno, offset, line)
1327 1327 self.SyntaxTB(etype,value,[])
1328 1328
1329 1329 def edit_syntax_error(self):
1330 1330 """The bottom half of the syntax error handler called in the main loop.
1331 1331
1332 1332 Loop until syntax error is fixed or user cancels.
1333 1333 """
1334 1334
1335 1335 while self.SyntaxTB.last_syntax_error:
1336 1336 # copy and clear last_syntax_error
1337 1337 err = self.SyntaxTB.clear_err_state()
1338 1338 if not self._should_recompile(err):
1339 1339 return
1340 1340 try:
1341 1341 # may set last_syntax_error again if a SyntaxError is raised
1342 1342 self.safe_execfile(err.filename,self.user_ns)
1343 1343 except:
1344 1344 self.showtraceback()
1345 1345 else:
1346 1346 try:
1347 1347 f = file(err.filename)
1348 1348 try:
1349 1349 # This should be inside a display_trap block and I
1350 1350 # think it is.
1351 1351 sys.displayhook(f.read())
1352 1352 finally:
1353 1353 f.close()
1354 1354 except:
1355 1355 self.showtraceback()
1356 1356
1357 1357 def _should_recompile(self,e):
1358 1358 """Utility routine for edit_syntax_error"""
1359 1359
1360 1360 if e.filename in ('<ipython console>','<input>','<string>',
1361 1361 '<console>','<BackgroundJob compilation>',
1362 1362 None):
1363 1363
1364 1364 return False
1365 1365 try:
1366 1366 if (self.autoedit_syntax and
1367 1367 not self.ask_yes_no('Return to editor to correct syntax error? '
1368 1368 '[Y/n] ','y')):
1369 1369 return False
1370 1370 except EOFError:
1371 1371 return False
1372 1372
1373 1373 def int0(x):
1374 1374 try:
1375 1375 return int(x)
1376 1376 except TypeError:
1377 1377 return 0
1378 1378 # always pass integer line and offset values to editor hook
1379 1379 try:
1380 1380 self.hooks.fix_error_editor(e.filename,
1381 1381 int0(e.lineno),int0(e.offset),e.msg)
1382 1382 except TryNext:
1383 1383 warn('Could not open editor')
1384 1384 return False
1385 1385 return True
1386 1386
1387 1387 #-------------------------------------------------------------------------
1388 1388 # Things related to tab completion
1389 1389 #-------------------------------------------------------------------------
1390 1390
1391 1391 def complete(self, text):
1392 1392 """Return a sorted list of all possible completions on text.
1393 1393
1394 1394 Inputs:
1395 1395
1396 1396 - text: a string of text to be completed on.
1397 1397
1398 1398 This is a wrapper around the completion mechanism, similar to what
1399 1399 readline does at the command line when the TAB key is hit. By
1400 1400 exposing it as a method, it can be used by other non-readline
1401 1401 environments (such as GUIs) for text completion.
1402 1402
1403 1403 Simple usage example:
1404 1404
1405 1405 In [7]: x = 'hello'
1406 1406
1407 1407 In [8]: x
1408 1408 Out[8]: 'hello'
1409 1409
1410 1410 In [9]: print x
1411 1411 hello
1412 1412
1413 1413 In [10]: _ip.complete('x.l')
1414 1414 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1415 1415 """
1416 1416
1417 1417 # Inject names into __builtin__ so we can complete on the added names.
1418 1418 with self.builtin_trap:
1419 1419 complete = self.Completer.complete
1420 1420 state = 0
1421 1421 # use a dict so we get unique keys, since ipyhton's multiple
1422 1422 # completers can return duplicates. When we make 2.4 a requirement,
1423 1423 # start using sets instead, which are faster.
1424 1424 comps = {}
1425 1425 while True:
1426 1426 newcomp = complete(text,state,line_buffer=text)
1427 1427 if newcomp is None:
1428 1428 break
1429 1429 comps[newcomp] = 1
1430 1430 state += 1
1431 1431 outcomps = comps.keys()
1432 1432 outcomps.sort()
1433 1433 #print "T:",text,"OC:",outcomps # dbg
1434 1434 #print "vars:",self.user_ns.keys()
1435 1435 return outcomps
1436 1436
1437 1437 def set_custom_completer(self,completer,pos=0):
1438 1438 """Adds a new custom completer function.
1439 1439
1440 1440 The position argument (defaults to 0) is the index in the completers
1441 1441 list where you want the completer to be inserted."""
1442 1442
1443 1443 newcomp = new.instancemethod(completer,self.Completer,
1444 1444 self.Completer.__class__)
1445 1445 self.Completer.matchers.insert(pos,newcomp)
1446 1446
1447 1447 def set_completer(self):
1448 1448 """Reset readline's completer to be our own."""
1449 1449 self.readline.set_completer(self.Completer.complete)
1450 1450
1451 1451 def set_completer_frame(self, frame=None):
1452 1452 """Set the frame of the completer."""
1453 1453 if frame:
1454 1454 self.Completer.namespace = frame.f_locals
1455 1455 self.Completer.global_namespace = frame.f_globals
1456 1456 else:
1457 1457 self.Completer.namespace = self.user_ns
1458 1458 self.Completer.global_namespace = self.user_global_ns
1459 1459
1460 1460 #-------------------------------------------------------------------------
1461 1461 # Things related to readline
1462 1462 #-------------------------------------------------------------------------
1463 1463
1464 1464 def init_readline(self):
1465 1465 """Command history completion/saving/reloading."""
1466 1466
1467 1467 self.rl_next_input = None
1468 1468 self.rl_do_indent = False
1469 1469
1470 1470 if not self.readline_use:
1471 1471 return
1472 1472
1473 1473 import IPython.utils.rlineimpl as readline
1474 1474
1475 1475 if not readline.have_readline:
1476 1476 self.has_readline = 0
1477 1477 self.readline = None
1478 1478 # no point in bugging windows users with this every time:
1479 1479 warn('Readline services not available on this platform.')
1480 1480 else:
1481 1481 sys.modules['readline'] = readline
1482 1482 import atexit
1483 1483 from IPython.core.completer import IPCompleter
1484 1484 self.Completer = IPCompleter(self,
1485 1485 self.user_ns,
1486 1486 self.user_global_ns,
1487 1487 self.readline_omit__names,
1488 1488 self.alias_manager.alias_table)
1489 1489 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1490 1490 self.strdispatchers['complete_command'] = sdisp
1491 1491 self.Completer.custom_completers = sdisp
1492 1492 # Platform-specific configuration
1493 1493 if os.name == 'nt':
1494 1494 self.readline_startup_hook = readline.set_pre_input_hook
1495 1495 else:
1496 1496 self.readline_startup_hook = readline.set_startup_hook
1497 1497
1498 1498 # Load user's initrc file (readline config)
1499 1499 # Or if libedit is used, load editrc.
1500 1500 inputrc_name = os.environ.get('INPUTRC')
1501 1501 if inputrc_name is None:
1502 1502 home_dir = get_home_dir()
1503 1503 if home_dir is not None:
1504 1504 inputrc_name = '.inputrc'
1505 1505 if readline.uses_libedit:
1506 1506 inputrc_name = '.editrc'
1507 1507 inputrc_name = os.path.join(home_dir, inputrc_name)
1508 1508 if os.path.isfile(inputrc_name):
1509 1509 try:
1510 1510 readline.read_init_file(inputrc_name)
1511 1511 except:
1512 1512 warn('Problems reading readline initialization file <%s>'
1513 1513 % inputrc_name)
1514 1514
1515 1515 self.has_readline = 1
1516 1516 self.readline = readline
1517 1517 # save this in sys so embedded copies can restore it properly
1518 1518 sys.ipcompleter = self.Completer.complete
1519 1519 self.set_completer()
1520 1520
1521 1521 # Configure readline according to user's prefs
1522 1522 # This is only done if GNU readline is being used. If libedit
1523 1523 # is being used (as on Leopard) the readline config is
1524 1524 # not run as the syntax for libedit is different.
1525 1525 if not readline.uses_libedit:
1526 1526 for rlcommand in self.readline_parse_and_bind:
1527 1527 #print "loading rl:",rlcommand # dbg
1528 1528 readline.parse_and_bind(rlcommand)
1529 1529
1530 1530 # Remove some chars from the delimiters list. If we encounter
1531 1531 # unicode chars, discard them.
1532 1532 delims = readline.get_completer_delims().encode("ascii", "ignore")
1533 1533 delims = delims.translate(string._idmap,
1534 1534 self.readline_remove_delims)
1535 1535 readline.set_completer_delims(delims)
1536 1536 # otherwise we end up with a monster history after a while:
1537 1537 readline.set_history_length(1000)
1538 1538 try:
1539 1539 #print '*** Reading readline history' # dbg
1540 1540 readline.read_history_file(self.histfile)
1541 1541 except IOError:
1542 1542 pass # It doesn't exist yet.
1543 1543
1544 1544 atexit.register(self.atexit_operations)
1545 1545 del atexit
1546 1546
1547 1547 # Configure auto-indent for all platforms
1548 1548 self.set_autoindent(self.autoindent)
1549 1549
1550 1550 def set_next_input(self, s):
1551 1551 """ Sets the 'default' input string for the next command line.
1552 1552
1553 1553 Requires readline.
1554 1554
1555 1555 Example:
1556 1556
1557 1557 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1558 1558 [D:\ipython]|2> Hello Word_ # cursor is here
1559 1559 """
1560 1560
1561 1561 self.rl_next_input = s
1562 1562
1563 1563 def pre_readline(self):
1564 1564 """readline hook to be used at the start of each line.
1565 1565
1566 1566 Currently it handles auto-indent only."""
1567 1567
1568 1568 #debugx('self.indent_current_nsp','pre_readline:')
1569 1569
1570 1570 if self.rl_do_indent:
1571 1571 self.readline.insert_text(self._indent_current_str())
1572 1572 if self.rl_next_input is not None:
1573 1573 self.readline.insert_text(self.rl_next_input)
1574 1574 self.rl_next_input = None
1575 1575
1576 1576 def _indent_current_str(self):
1577 1577 """return the current level of indentation as a string"""
1578 1578 return self.indent_current_nsp * ' '
1579 1579
1580 1580 #-------------------------------------------------------------------------
1581 1581 # Things related to magics
1582 1582 #-------------------------------------------------------------------------
1583 1583
1584 1584 def init_magics(self):
1585 1585 # Set user colors (don't do it in the constructor above so that it
1586 1586 # doesn't crash if colors option is invalid)
1587 1587 self.magic_colors(self.colors)
1588 1588
1589 1589 def magic(self,arg_s):
1590 1590 """Call a magic function by name.
1591 1591
1592 1592 Input: a string containing the name of the magic function to call and any
1593 1593 additional arguments to be passed to the magic.
1594 1594
1595 1595 magic('name -opt foo bar') is equivalent to typing at the ipython
1596 1596 prompt:
1597 1597
1598 1598 In[1]: %name -opt foo bar
1599 1599
1600 1600 To call a magic without arguments, simply use magic('name').
1601 1601
1602 1602 This provides a proper Python function to call IPython's magics in any
1603 1603 valid Python code you can type at the interpreter, including loops and
1604 1604 compound statements.
1605 1605 """
1606 1606
1607 1607 args = arg_s.split(' ',1)
1608 1608 magic_name = args[0]
1609 1609 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1610 1610
1611 1611 try:
1612 1612 magic_args = args[1]
1613 1613 except IndexError:
1614 1614 magic_args = ''
1615 1615 fn = getattr(self,'magic_'+magic_name,None)
1616 1616 if fn is None:
1617 1617 error("Magic function `%s` not found." % magic_name)
1618 1618 else:
1619 1619 magic_args = self.var_expand(magic_args,1)
1620 1620 with nested(self.builtin_trap,):
1621 1621 result = fn(magic_args)
1622 1622 return result
1623 1623
1624 1624 def define_magic(self, magicname, func):
1625 1625 """Expose own function as magic function for ipython
1626 1626
1627 1627 def foo_impl(self,parameter_s=''):
1628 1628 'My very own magic!. (Use docstrings, IPython reads them).'
1629 1629 print 'Magic function. Passed parameter is between < >:'
1630 1630 print '<%s>' % parameter_s
1631 1631 print 'The self object is:',self
1632 1632
1633 1633 self.define_magic('foo',foo_impl)
1634 1634 """
1635 1635
1636 1636 import new
1637 1637 im = new.instancemethod(func,self, self.__class__)
1638 1638 old = getattr(self, "magic_" + magicname, None)
1639 1639 setattr(self, "magic_" + magicname, im)
1640 1640 return old
1641 1641
1642 1642 #-------------------------------------------------------------------------
1643 1643 # Things related to macros
1644 1644 #-------------------------------------------------------------------------
1645 1645
1646 1646 def define_macro(self, name, themacro):
1647 1647 """Define a new macro
1648 1648
1649 1649 Parameters
1650 1650 ----------
1651 1651 name : str
1652 1652 The name of the macro.
1653 1653 themacro : str or Macro
1654 1654 The action to do upon invoking the macro. If a string, a new
1655 1655 Macro object is created by passing the string to it.
1656 1656 """
1657 1657
1658 1658 from IPython.core import macro
1659 1659
1660 1660 if isinstance(themacro, basestring):
1661 1661 themacro = macro.Macro(themacro)
1662 1662 if not isinstance(themacro, macro.Macro):
1663 1663 raise ValueError('A macro must be a string or a Macro instance.')
1664 1664 self.user_ns[name] = themacro
1665 1665
1666 1666 #-------------------------------------------------------------------------
1667 1667 # Things related to the running of system commands
1668 1668 #-------------------------------------------------------------------------
1669 1669
1670 1670 def system(self, cmd):
1671 1671 """Make a system call, using IPython."""
1672 1672 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1673 1673
1674 1674 #-------------------------------------------------------------------------
1675 1675 # Things related to aliases
1676 1676 #-------------------------------------------------------------------------
1677 1677
1678 1678 def init_alias(self):
1679 1679 self.alias_manager = AliasManager(self, config=self.config)
1680 1680 self.ns_table['alias'] = self.alias_manager.alias_table,
1681 1681
1682 1682 #-------------------------------------------------------------------------
1683 1683 # Things related to the running of code
1684 1684 #-------------------------------------------------------------------------
1685 1685
1686 1686 def ex(self, cmd):
1687 1687 """Execute a normal python statement in user namespace."""
1688 1688 with nested(self.builtin_trap,):
1689 1689 exec cmd in self.user_global_ns, self.user_ns
1690 1690
1691 1691 def ev(self, expr):
1692 1692 """Evaluate python expression expr in user namespace.
1693 1693
1694 1694 Returns the result of evaluation
1695 1695 """
1696 1696 with nested(self.builtin_trap,):
1697 1697 return eval(expr, self.user_global_ns, self.user_ns)
1698 1698
1699 1699 def mainloop(self, display_banner=None):
1700 1700 """Start the mainloop.
1701 1701
1702 1702 If an optional banner argument is given, it will override the
1703 1703 internally created default banner.
1704 1704 """
1705 1705
1706 1706 with nested(self.builtin_trap, self.display_trap):
1707 1707
1708 1708 # if you run stuff with -c <cmd>, raw hist is not updated
1709 1709 # ensure that it's in sync
1710 1710 if len(self.input_hist) != len (self.input_hist_raw):
1711 1711 self.input_hist_raw = InputList(self.input_hist)
1712 1712
1713 1713 while 1:
1714 1714 try:
1715 1715 self.interact(display_banner=display_banner)
1716 1716 #self.interact_with_readline()
1717 1717 # XXX for testing of a readline-decoupled repl loop, call
1718 1718 # interact_with_readline above
1719 1719 break
1720 1720 except KeyboardInterrupt:
1721 1721 # this should not be necessary, but KeyboardInterrupt
1722 1722 # handling seems rather unpredictable...
1723 1723 self.write("\nKeyboardInterrupt in interact()\n")
1724 1724
1725 1725 def interact_prompt(self):
1726 1726 """ Print the prompt (in read-eval-print loop)
1727 1727
1728 1728 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1729 1729 used in standard IPython flow.
1730 1730 """
1731 1731 if self.more:
1732 1732 try:
1733 1733 prompt = self.hooks.generate_prompt(True)
1734 1734 except:
1735 1735 self.showtraceback()
1736 1736 if self.autoindent:
1737 1737 self.rl_do_indent = True
1738 1738
1739 1739 else:
1740 1740 try:
1741 1741 prompt = self.hooks.generate_prompt(False)
1742 1742 except:
1743 1743 self.showtraceback()
1744 1744 self.write(prompt)
1745 1745
1746 1746 def interact_handle_input(self,line):
1747 1747 """ Handle the input line (in read-eval-print loop)
1748 1748
1749 1749 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1750 1750 used in standard IPython flow.
1751 1751 """
1752 1752 if line.lstrip() == line:
1753 1753 self.shadowhist.add(line.strip())
1754 1754 lineout = self.prefilter_manager.prefilter_lines(line,self.more)
1755 1755
1756 1756 if line.strip():
1757 1757 if self.more:
1758 1758 self.input_hist_raw[-1] += '%s\n' % line
1759 1759 else:
1760 1760 self.input_hist_raw.append('%s\n' % line)
1761 1761
1762 1762
1763 1763 self.more = self.push_line(lineout)
1764 1764 if (self.SyntaxTB.last_syntax_error and
1765 1765 self.autoedit_syntax):
1766 1766 self.edit_syntax_error()
1767 1767
1768 1768 def interact_with_readline(self):
1769 1769 """ Demo of using interact_handle_input, interact_prompt
1770 1770
1771 1771 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1772 1772 it should work like this.
1773 1773 """
1774 1774 self.readline_startup_hook(self.pre_readline)
1775 1775 while not self.exit_now:
1776 1776 self.interact_prompt()
1777 1777 if self.more:
1778 1778 self.rl_do_indent = True
1779 1779 else:
1780 1780 self.rl_do_indent = False
1781 1781 line = raw_input_original().decode(self.stdin_encoding)
1782 1782 self.interact_handle_input(line)
1783 1783
1784 1784 def interact(self, display_banner=None):
1785 1785 """Closely emulate the interactive Python console."""
1786 1786
1787 1787 # batch run -> do not interact
1788 1788 if self.exit_now:
1789 1789 return
1790 1790
1791 1791 if display_banner is None:
1792 1792 display_banner = self.display_banner
1793 1793 if display_banner:
1794 1794 self.show_banner()
1795 1795
1796 1796 more = 0
1797 1797
1798 1798 # Mark activity in the builtins
1799 1799 __builtin__.__dict__['__IPYTHON__active'] += 1
1800 1800
1801 1801 if self.has_readline:
1802 1802 self.readline_startup_hook(self.pre_readline)
1803 1803 # exit_now is set by a call to %Exit or %Quit, through the
1804 1804 # ask_exit callback.
1805 1805
1806 1806 while not self.exit_now:
1807 1807 self.hooks.pre_prompt_hook()
1808 1808 if more:
1809 1809 try:
1810 1810 prompt = self.hooks.generate_prompt(True)
1811 1811 except:
1812 1812 self.showtraceback()
1813 1813 if self.autoindent:
1814 1814 self.rl_do_indent = True
1815 1815
1816 1816 else:
1817 1817 try:
1818 1818 prompt = self.hooks.generate_prompt(False)
1819 1819 except:
1820 1820 self.showtraceback()
1821 1821 try:
1822 1822 line = self.raw_input(prompt, more)
1823 1823 if self.exit_now:
1824 1824 # quick exit on sys.std[in|out] close
1825 1825 break
1826 1826 if self.autoindent:
1827 1827 self.rl_do_indent = False
1828 1828
1829 1829 except KeyboardInterrupt:
1830 1830 #double-guard against keyboardinterrupts during kbdint handling
1831 1831 try:
1832 1832 self.write('\nKeyboardInterrupt\n')
1833 1833 self.resetbuffer()
1834 1834 # keep cache in sync with the prompt counter:
1835 1835 self.outputcache.prompt_count -= 1
1836 1836
1837 1837 if self.autoindent:
1838 1838 self.indent_current_nsp = 0
1839 1839 more = 0
1840 1840 except KeyboardInterrupt:
1841 1841 pass
1842 1842 except EOFError:
1843 1843 if self.autoindent:
1844 1844 self.rl_do_indent = False
1845 1845 self.readline_startup_hook(None)
1846 1846 self.write('\n')
1847 1847 self.exit()
1848 1848 except bdb.BdbQuit:
1849 1849 warn('The Python debugger has exited with a BdbQuit exception.\n'
1850 1850 'Because of how pdb handles the stack, it is impossible\n'
1851 1851 'for IPython to properly format this particular exception.\n'
1852 1852 'IPython will resume normal operation.')
1853 1853 except:
1854 1854 # exceptions here are VERY RARE, but they can be triggered
1855 1855 # asynchronously by signal handlers, for example.
1856 1856 self.showtraceback()
1857 1857 else:
1858 1858 more = self.push_line(line)
1859 1859 if (self.SyntaxTB.last_syntax_error and
1860 1860 self.autoedit_syntax):
1861 1861 self.edit_syntax_error()
1862 1862
1863 1863 # We are off again...
1864 1864 __builtin__.__dict__['__IPYTHON__active'] -= 1
1865 1865
1866 1866 def safe_execfile(self, fname, *where, **kw):
1867 1867 """A safe version of the builtin execfile().
1868 1868
1869 1869 This version will never throw an exception, but instead print
1870 1870 helpful error messages to the screen. This only works on pure
1871 1871 Python files with the .py extension.
1872 1872
1873 1873 Parameters
1874 1874 ----------
1875 1875 fname : string
1876 1876 The name of the file to be executed.
1877 1877 where : tuple
1878 1878 One or two namespaces, passed to execfile() as (globals,locals).
1879 1879 If only one is given, it is passed as both.
1880 1880 exit_ignore : bool (False)
1881 1881 If True, then don't print errors for non-zero exit statuses.
1882 1882 """
1883 1883 kw.setdefault('exit_ignore', False)
1884 1884
1885 1885 fname = os.path.abspath(os.path.expanduser(fname))
1886 1886
1887 1887 # Make sure we have a .py file
1888 1888 if not fname.endswith('.py'):
1889 1889 warn('File must end with .py to be run using execfile: <%s>' % fname)
1890 1890
1891 1891 # Make sure we can open the file
1892 1892 try:
1893 1893 with open(fname) as thefile:
1894 1894 pass
1895 1895 except:
1896 1896 warn('Could not open file <%s> for safe execution.' % fname)
1897 1897 return
1898 1898
1899 1899 # Find things also in current directory. This is needed to mimic the
1900 1900 # behavior of running a script from the system command line, where
1901 1901 # Python inserts the script's directory into sys.path
1902 1902 dname = os.path.dirname(fname)
1903 1903
1904 1904 with prepended_to_syspath(dname):
1905 1905 try:
1906 1906 if sys.platform == 'win32' and sys.version_info < (2,5,1):
1907 1907 # Work around a bug in Python for Windows. The bug was
1908 1908 # fixed in in Python 2.5 r54159 and 54158, but that's still
1909 1909 # SVN Python as of March/07. For details, see:
1910 1910 # http://projects.scipy.org/ipython/ipython/ticket/123
1911 1911 try:
1912 1912 globs,locs = where[0:2]
1913 1913 except:
1914 1914 try:
1915 1915 globs = locs = where[0]
1916 1916 except:
1917 1917 globs = locs = globals()
1918 1918 exec file(fname) in globs,locs
1919 1919 else:
1920 1920 execfile(fname,*where)
1921 1921 except SyntaxError:
1922 1922 self.showsyntaxerror()
1923 1923 warn('Failure executing file: <%s>' % fname)
1924 1924 except SystemExit, status:
1925 1925 # Code that correctly sets the exit status flag to success (0)
1926 1926 # shouldn't be bothered with a traceback. Note that a plain
1927 1927 # sys.exit() does NOT set the message to 0 (it's empty) so that
1928 1928 # will still get a traceback. Note that the structure of the
1929 1929 # SystemExit exception changed between Python 2.4 and 2.5, so
1930 1930 # the checks must be done in a version-dependent way.
1931 1931 show = False
1932 1932 if status.args[0]==0 and not kw['exit_ignore']:
1933 1933 show = True
1934 1934 if show:
1935 1935 self.showtraceback()
1936 1936 warn('Failure executing file: <%s>' % fname)
1937 1937 except:
1938 1938 self.showtraceback()
1939 1939 warn('Failure executing file: <%s>' % fname)
1940 1940
1941 1941 def safe_execfile_ipy(self, fname):
1942 1942 """Like safe_execfile, but for .ipy files with IPython syntax.
1943 1943
1944 1944 Parameters
1945 1945 ----------
1946 1946 fname : str
1947 1947 The name of the file to execute. The filename must have a
1948 1948 .ipy extension.
1949 1949 """
1950 1950 fname = os.path.abspath(os.path.expanduser(fname))
1951 1951
1952 1952 # Make sure we have a .py file
1953 1953 if not fname.endswith('.ipy'):
1954 1954 warn('File must end with .py to be run using execfile: <%s>' % fname)
1955 1955
1956 1956 # Make sure we can open the file
1957 1957 try:
1958 1958 with open(fname) as thefile:
1959 1959 pass
1960 1960 except:
1961 1961 warn('Could not open file <%s> for safe execution.' % fname)
1962 1962 return
1963 1963
1964 1964 # Find things also in current directory. This is needed to mimic the
1965 1965 # behavior of running a script from the system command line, where
1966 1966 # Python inserts the script's directory into sys.path
1967 1967 dname = os.path.dirname(fname)
1968 1968
1969 1969 with prepended_to_syspath(dname):
1970 1970 try:
1971 1971 with open(fname) as thefile:
1972 1972 script = thefile.read()
1973 1973 # self.runlines currently captures all exceptions
1974 1974 # raise in user code. It would be nice if there were
1975 1975 # versions of runlines, execfile that did raise, so
1976 1976 # we could catch the errors.
1977 1977 self.runlines(script, clean=True)
1978 1978 except:
1979 1979 self.showtraceback()
1980 1980 warn('Unknown failure executing file: <%s>' % fname)
1981 1981
1982 1982 def _is_secondary_block_start(self, s):
1983 1983 if not s.endswith(':'):
1984 1984 return False
1985 1985 if (s.startswith('elif') or
1986 1986 s.startswith('else') or
1987 1987 s.startswith('except') or
1988 1988 s.startswith('finally')):
1989 1989 return True
1990 1990
1991 1991 def cleanup_ipy_script(self, script):
1992 1992 """Make a script safe for self.runlines()
1993 1993
1994 1994 Currently, IPython is lines based, with blocks being detected by
1995 1995 empty lines. This is a problem for block based scripts that may
1996 1996 not have empty lines after blocks. This script adds those empty
1997 1997 lines to make scripts safe for running in the current line based
1998 1998 IPython.
1999 1999 """
2000 2000 res = []
2001 2001 lines = script.splitlines()
2002 2002 level = 0
2003 2003
2004 2004 for l in lines:
2005 2005 lstripped = l.lstrip()
2006 2006 stripped = l.strip()
2007 2007 if not stripped:
2008 2008 continue
2009 2009 newlevel = len(l) - len(lstripped)
2010 2010 if level > 0 and newlevel == 0 and \
2011 2011 not self._is_secondary_block_start(stripped):
2012 2012 # add empty line
2013 2013 res.append('')
2014 2014 res.append(l)
2015 2015 level = newlevel
2016 2016
2017 2017 return '\n'.join(res) + '\n'
2018 2018
2019 2019 def runlines(self, lines, clean=False):
2020 2020 """Run a string of one or more lines of source.
2021 2021
2022 2022 This method is capable of running a string containing multiple source
2023 2023 lines, as if they had been entered at the IPython prompt. Since it
2024 2024 exposes IPython's processing machinery, the given strings can contain
2025 2025 magic calls (%magic), special shell access (!cmd), etc.
2026 2026 """
2027 2027
2028 2028 if isinstance(lines, (list, tuple)):
2029 2029 lines = '\n'.join(lines)
2030 2030
2031 2031 if clean:
2032 2032 lines = self.cleanup_ipy_script(lines)
2033 2033
2034 2034 # We must start with a clean buffer, in case this is run from an
2035 2035 # interactive IPython session (via a magic, for example).
2036 2036 self.resetbuffer()
2037 2037 lines = lines.splitlines()
2038 2038 more = 0
2039 2039
2040 2040 with nested(self.builtin_trap, self.display_trap):
2041 2041 for line in lines:
2042 2042 # skip blank lines so we don't mess up the prompt counter, but do
2043 2043 # NOT skip even a blank line if we are in a code block (more is
2044 2044 # true)
2045 2045
2046 2046 if line or more:
2047 2047 # push to raw history, so hist line numbers stay in sync
2048 2048 self.input_hist_raw.append("# " + line + "\n")
2049 2049 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
2050 2050 more = self.push_line(prefiltered)
2051 2051 # IPython's runsource returns None if there was an error
2052 2052 # compiling the code. This allows us to stop processing right
2053 2053 # away, so the user gets the error message at the right place.
2054 2054 if more is None:
2055 2055 break
2056 2056 else:
2057 2057 self.input_hist_raw.append("\n")
2058 2058 # final newline in case the input didn't have it, so that the code
2059 2059 # actually does get executed
2060 2060 if more:
2061 2061 self.push_line('\n')
2062 2062
2063 2063 def runsource(self, source, filename='<input>', symbol='single'):
2064 2064 """Compile and run some source in the interpreter.
2065 2065
2066 2066 Arguments are as for compile_command().
2067 2067
2068 2068 One several things can happen:
2069 2069
2070 2070 1) The input is incorrect; compile_command() raised an
2071 2071 exception (SyntaxError or OverflowError). A syntax traceback
2072 2072 will be printed by calling the showsyntaxerror() method.
2073 2073
2074 2074 2) The input is incomplete, and more input is required;
2075 2075 compile_command() returned None. Nothing happens.
2076 2076
2077 2077 3) The input is complete; compile_command() returned a code
2078 2078 object. The code is executed by calling self.runcode() (which
2079 2079 also handles run-time exceptions, except for SystemExit).
2080 2080
2081 2081 The return value is:
2082 2082
2083 2083 - True in case 2
2084 2084
2085 2085 - False in the other cases, unless an exception is raised, where
2086 2086 None is returned instead. This can be used by external callers to
2087 2087 know whether to continue feeding input or not.
2088 2088
2089 2089 The return value can be used to decide whether to use sys.ps1 or
2090 2090 sys.ps2 to prompt the next line."""
2091 2091
2092 2092 # if the source code has leading blanks, add 'if 1:\n' to it
2093 2093 # this allows execution of indented pasted code. It is tempting
2094 2094 # to add '\n' at the end of source to run commands like ' a=1'
2095 2095 # directly, but this fails for more complicated scenarios
2096 2096 source=source.encode(self.stdin_encoding)
2097 2097 if source[:1] in [' ', '\t']:
2098 2098 source = 'if 1:\n%s' % source
2099 2099
2100 2100 try:
2101 2101 code = self.compile(source,filename,symbol)
2102 2102 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2103 2103 # Case 1
2104 2104 self.showsyntaxerror(filename)
2105 2105 return None
2106 2106
2107 2107 if code is None:
2108 2108 # Case 2
2109 2109 return True
2110 2110
2111 2111 # Case 3
2112 2112 # We store the code object so that threaded shells and
2113 2113 # custom exception handlers can access all this info if needed.
2114 2114 # The source corresponding to this can be obtained from the
2115 2115 # buffer attribute as '\n'.join(self.buffer).
2116 2116 self.code_to_run = code
2117 2117 # now actually execute the code object
2118 2118 if self.runcode(code) == 0:
2119 2119 return False
2120 2120 else:
2121 2121 return None
2122 2122
2123 2123 def runcode(self,code_obj):
2124 2124 """Execute a code object.
2125 2125
2126 2126 When an exception occurs, self.showtraceback() is called to display a
2127 2127 traceback.
2128 2128
2129 2129 Return value: a flag indicating whether the code to be run completed
2130 2130 successfully:
2131 2131
2132 2132 - 0: successful execution.
2133 2133 - 1: an error occurred.
2134 2134 """
2135 2135
2136 2136 # Set our own excepthook in case the user code tries to call it
2137 2137 # directly, so that the IPython crash handler doesn't get triggered
2138 2138 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2139 2139
2140 2140 # we save the original sys.excepthook in the instance, in case config
2141 2141 # code (such as magics) needs access to it.
2142 2142 self.sys_excepthook = old_excepthook
2143 2143 outflag = 1 # happens in more places, so it's easier as default
2144 2144 try:
2145 2145 try:
2146 2146 self.hooks.pre_runcode_hook()
2147 2147 exec code_obj in self.user_global_ns, self.user_ns
2148 2148 finally:
2149 2149 # Reset our crash handler in place
2150 2150 sys.excepthook = old_excepthook
2151 2151 except SystemExit:
2152 2152 self.resetbuffer()
2153 2153 self.showtraceback()
2154 2154 warn("Type %exit or %quit to exit IPython "
2155 2155 "(%Exit or %Quit do so unconditionally).",level=1)
2156 2156 except self.custom_exceptions:
2157 2157 etype,value,tb = sys.exc_info()
2158 2158 self.CustomTB(etype,value,tb)
2159 2159 except:
2160 2160 self.showtraceback()
2161 2161 else:
2162 2162 outflag = 0
2163 2163 if softspace(sys.stdout, 0):
2164 2164 print
2165 2165 # Flush out code object which has been run (and source)
2166 2166 self.code_to_run = None
2167 2167 return outflag
2168 2168
2169 2169 def push_line(self, line):
2170 2170 """Push a line to the interpreter.
2171 2171
2172 2172 The line should not have a trailing newline; it may have
2173 2173 internal newlines. The line is appended to a buffer and the
2174 2174 interpreter's runsource() method is called with the
2175 2175 concatenated contents of the buffer as source. If this
2176 2176 indicates that the command was executed or invalid, the buffer
2177 2177 is reset; otherwise, the command is incomplete, and the buffer
2178 2178 is left as it was after the line was appended. The return
2179 2179 value is 1 if more input is required, 0 if the line was dealt
2180 2180 with in some way (this is the same as runsource()).
2181 2181 """
2182 2182
2183 2183 # autoindent management should be done here, and not in the
2184 2184 # interactive loop, since that one is only seen by keyboard input. We
2185 2185 # need this done correctly even for code run via runlines (which uses
2186 2186 # push).
2187 2187
2188 2188 #print 'push line: <%s>' % line # dbg
2189 2189 for subline in line.splitlines():
2190 2190 self._autoindent_update(subline)
2191 2191 self.buffer.append(line)
2192 2192 more = self.runsource('\n'.join(self.buffer), self.filename)
2193 2193 if not more:
2194 2194 self.resetbuffer()
2195 2195 return more
2196 2196
2197 2197 def _autoindent_update(self,line):
2198 2198 """Keep track of the indent level."""
2199 2199
2200 2200 #debugx('line')
2201 2201 #debugx('self.indent_current_nsp')
2202 2202 if self.autoindent:
2203 2203 if line:
2204 2204 inisp = num_ini_spaces(line)
2205 2205 if inisp < self.indent_current_nsp:
2206 2206 self.indent_current_nsp = inisp
2207 2207
2208 2208 if line[-1] == ':':
2209 2209 self.indent_current_nsp += 4
2210 2210 elif dedent_re.match(line):
2211 2211 self.indent_current_nsp -= 4
2212 2212 else:
2213 2213 self.indent_current_nsp = 0
2214 2214
2215 2215 def resetbuffer(self):
2216 2216 """Reset the input buffer."""
2217 2217 self.buffer[:] = []
2218 2218
2219 2219 def raw_input(self,prompt='',continue_prompt=False):
2220 2220 """Write a prompt and read a line.
2221 2221
2222 2222 The returned line does not include the trailing newline.
2223 2223 When the user enters the EOF key sequence, EOFError is raised.
2224 2224
2225 2225 Optional inputs:
2226 2226
2227 2227 - prompt(''): a string to be printed to prompt the user.
2228 2228
2229 2229 - continue_prompt(False): whether this line is the first one or a
2230 2230 continuation in a sequence of inputs.
2231 2231 """
2232 2232 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
2233 2233
2234 2234 # Code run by the user may have modified the readline completer state.
2235 2235 # We must ensure that our completer is back in place.
2236 2236
2237 2237 if self.has_readline:
2238 2238 self.set_completer()
2239 2239
2240 2240 try:
2241 2241 line = raw_input_original(prompt).decode(self.stdin_encoding)
2242 2242 except ValueError:
2243 2243 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2244 2244 " or sys.stdout.close()!\nExiting IPython!")
2245 2245 self.ask_exit()
2246 2246 return ""
2247 2247
2248 2248 # Try to be reasonably smart about not re-indenting pasted input more
2249 2249 # than necessary. We do this by trimming out the auto-indent initial
2250 2250 # spaces, if the user's actual input started itself with whitespace.
2251 2251 #debugx('self.buffer[-1]')
2252 2252
2253 2253 if self.autoindent:
2254 2254 if num_ini_spaces(line) > self.indent_current_nsp:
2255 2255 line = line[self.indent_current_nsp:]
2256 2256 self.indent_current_nsp = 0
2257 2257
2258 2258 # store the unfiltered input before the user has any chance to modify
2259 2259 # it.
2260 2260 if line.strip():
2261 2261 if continue_prompt:
2262 2262 self.input_hist_raw[-1] += '%s\n' % line
2263 2263 if self.has_readline and self.readline_use:
2264 2264 try:
2265 2265 histlen = self.readline.get_current_history_length()
2266 2266 if histlen > 1:
2267 2267 newhist = self.input_hist_raw[-1].rstrip()
2268 2268 self.readline.remove_history_item(histlen-1)
2269 2269 self.readline.replace_history_item(histlen-2,
2270 2270 newhist.encode(self.stdin_encoding))
2271 2271 except AttributeError:
2272 2272 pass # re{move,place}_history_item are new in 2.4.
2273 2273 else:
2274 2274 self.input_hist_raw.append('%s\n' % line)
2275 2275 # only entries starting at first column go to shadow history
2276 2276 if line.lstrip() == line:
2277 2277 self.shadowhist.add(line.strip())
2278 2278 elif not continue_prompt:
2279 2279 self.input_hist_raw.append('\n')
2280 2280 try:
2281 2281 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
2282 2282 except:
2283 2283 # blanket except, in case a user-defined prefilter crashes, so it
2284 2284 # can't take all of ipython with it.
2285 2285 self.showtraceback()
2286 2286 return ''
2287 2287 else:
2288 2288 return lineout
2289 2289
2290 2290 #-------------------------------------------------------------------------
2291 2291 # Working with components
2292 2292 #-------------------------------------------------------------------------
2293 2293
2294 2294 def get_component(self, name=None, klass=None):
2295 2295 """Fetch a component by name and klass in my tree."""
2296 2296 c = Component.get_instances(root=self, name=name, klass=klass)
2297 if len(c) == 0:
2298 return None
2297 2299 if len(c) == 1:
2298 2300 return c[0]
2299 2301 else:
2300 2302 return c
2301 2303
2302 2304 #-------------------------------------------------------------------------
2303 2305 # IPython extensions
2304 2306 #-------------------------------------------------------------------------
2305 2307
2306 2308 def load_extension(self, module_str):
2307 2309 """Load an IPython extension by its module name.
2308 2310
2309 2311 An IPython extension is an importable Python module that has
2310 2312 a function with the signature::
2311 2313
2312 2314 def load_ipython_extension(ipython):
2313 2315 # Do things with ipython
2314 2316
2315 2317 This function is called after your extension is imported and the
2316 2318 currently active :class:`InteractiveShell` instance is passed as
2317 2319 the only argument. You can do anything you want with IPython at
2318 2320 that point, including defining new magic and aliases, adding new
2319 2321 components, etc.
2320 2322
2321 2323 The :func:`load_ipython_extension` will be called again is you
2322 2324 load or reload the extension again. It is up to the extension
2323 2325 author to add code to manage that.
2324 2326
2325 2327 You can put your extension modules anywhere you want, as long as
2326 2328 they can be imported by Python's standard import mechanism. However,
2327 2329 to make it easy to write extensions, you can also put your extensions
2328 2330 in ``os.path.join(self.ipythondir, 'extensions')``. This directory
2329 2331 is added to ``sys.path`` automatically.
2330 2332 """
2331 2333 from IPython.utils.syspathcontext import prepended_to_syspath
2332 2334
2333 2335 if module_str not in sys.modules:
2334 2336 with prepended_to_syspath(self.ipython_extension_dir):
2335 2337 __import__(module_str)
2336 2338 mod = sys.modules[module_str]
2337 2339 self._call_load_ipython_extension(mod)
2338 2340
2339 2341 def unload_extension(self, module_str):
2340 2342 """Unload an IPython extension by its module name.
2341 2343
2342 2344 This function looks up the extension's name in ``sys.modules`` and
2343 2345 simply calls ``mod.unload_ipython_extension(self)``.
2344 2346 """
2345 2347 if module_str in sys.modules:
2346 2348 mod = sys.modules[module_str]
2347 2349 self._call_unload_ipython_extension(mod)
2348 2350
2349 2351 def reload_extension(self, module_str):
2350 2352 """Reload an IPython extension by calling reload.
2351 2353
2352 2354 If the module has not been loaded before,
2353 2355 :meth:`InteractiveShell.load_extension` is called. Otherwise
2354 2356 :func:`reload` is called and then the :func:`load_ipython_extension`
2355 2357 function of the module, if it exists is called.
2356 2358 """
2357 2359 from IPython.utils.syspathcontext import prepended_to_syspath
2358 2360
2359 2361 with prepended_to_syspath(self.ipython_extension_dir):
2360 2362 if module_str in sys.modules:
2361 2363 mod = sys.modules[module_str]
2362 2364 reload(mod)
2363 2365 self._call_load_ipython_extension(mod)
2364 2366 else:
2365 2367 self.load_extension(module_str)
2366 2368
2367 2369 def _call_load_ipython_extension(self, mod):
2368 2370 if hasattr(mod, 'load_ipython_extension'):
2369 2371 mod.load_ipython_extension(self)
2370 2372
2371 2373 def _call_unload_ipython_extension(self, mod):
2372 2374 if hasattr(mod, 'unload_ipython_extension'):
2373 2375 mod.unload_ipython_extension(self)
2374 2376
2375 2377 #-------------------------------------------------------------------------
2376 2378 # Things related to the prefilter
2377 2379 #-------------------------------------------------------------------------
2378 2380
2379 2381 def init_prefilter(self):
2380 2382 self.prefilter_manager = PrefilterManager(self, config=self.config)
2381 2383
2382 2384 #-------------------------------------------------------------------------
2383 2385 # Utilities
2384 2386 #-------------------------------------------------------------------------
2385 2387
2386 2388 def getoutput(self, cmd):
2387 2389 return getoutput(self.var_expand(cmd,depth=2),
2388 2390 header=self.system_header,
2389 2391 verbose=self.system_verbose)
2390 2392
2391 2393 def getoutputerror(self, cmd):
2392 2394 return getoutputerror(self.var_expand(cmd,depth=2),
2393 2395 header=self.system_header,
2394 2396 verbose=self.system_verbose)
2395 2397
2396 2398 def var_expand(self,cmd,depth=0):
2397 2399 """Expand python variables in a string.
2398 2400
2399 2401 The depth argument indicates how many frames above the caller should
2400 2402 be walked to look for the local namespace where to expand variables.
2401 2403
2402 2404 The global namespace for expansion is always the user's interactive
2403 2405 namespace.
2404 2406 """
2405 2407
2406 2408 return str(ItplNS(cmd,
2407 2409 self.user_ns, # globals
2408 2410 # Skip our own frame in searching for locals:
2409 2411 sys._getframe(depth+1).f_locals # locals
2410 2412 ))
2411 2413
2412 2414 def mktempfile(self,data=None):
2413 2415 """Make a new tempfile and return its filename.
2414 2416
2415 2417 This makes a call to tempfile.mktemp, but it registers the created
2416 2418 filename internally so ipython cleans it up at exit time.
2417 2419
2418 2420 Optional inputs:
2419 2421
2420 2422 - data(None): if data is given, it gets written out to the temp file
2421 2423 immediately, and the file is closed again."""
2422 2424
2423 2425 filename = tempfile.mktemp('.py','ipython_edit_')
2424 2426 self.tempfiles.append(filename)
2425 2427
2426 2428 if data:
2427 2429 tmp_file = open(filename,'w')
2428 2430 tmp_file.write(data)
2429 2431 tmp_file.close()
2430 2432 return filename
2431 2433
2432 2434 def write(self,data):
2433 2435 """Write a string to the default output"""
2434 2436 Term.cout.write(data)
2435 2437
2436 2438 def write_err(self,data):
2437 2439 """Write a string to the default error output"""
2438 2440 Term.cerr.write(data)
2439 2441
2440 2442 def ask_yes_no(self,prompt,default=True):
2441 2443 if self.quiet:
2442 2444 return True
2443 2445 return ask_yes_no(prompt,default)
2444 2446
2445 2447 #-------------------------------------------------------------------------
2446 2448 # Things related to IPython exiting
2447 2449 #-------------------------------------------------------------------------
2448 2450
2449 2451 def ask_exit(self):
2450 2452 """ Call for exiting. Can be overiden and used as a callback. """
2451 2453 self.exit_now = True
2452 2454
2453 2455 def exit(self):
2454 2456 """Handle interactive exit.
2455 2457
2456 2458 This method calls the ask_exit callback."""
2457 2459 if self.confirm_exit:
2458 2460 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2459 2461 self.ask_exit()
2460 2462 else:
2461 2463 self.ask_exit()
2462 2464
2463 2465 def atexit_operations(self):
2464 2466 """This will be executed at the time of exit.
2465 2467
2466 2468 Saving of persistent data should be performed here.
2467 2469 """
2468 2470 self.savehist()
2469 2471
2470 2472 # Cleanup all tempfiles left around
2471 2473 for tfile in self.tempfiles:
2472 2474 try:
2473 2475 os.unlink(tfile)
2474 2476 except OSError:
2475 2477 pass
2476 2478
2477 2479 # Clear all user namespaces to release all references cleanly.
2478 2480 self.reset()
2479 2481
2480 2482 # Run user hooks
2481 2483 self.hooks.shutdown_hook()
2482 2484
2483 2485 def cleanup(self):
2484 2486 self.restore_sys_module_state()
2485 2487
2486 2488
@@ -1,963 +1,967 b''
1 1 # encoding: utf-8
2 2 # -*- test-case-name: IPython.kernel.test.test_multiengineclient -*-
3 3
4 4 """General Classes for IMultiEngine clients."""
5 5
6 6 __docformat__ = "restructuredtext en"
7 7
8 8 #-------------------------------------------------------------------------------
9 9 # Copyright (C) 2008 The IPython Development Team
10 10 #
11 11 # Distributed under the terms of the BSD License. The full license is in
12 12 # the file COPYING, distributed as part of this software.
13 13 #-------------------------------------------------------------------------------
14 14
15 15 #-------------------------------------------------------------------------------
16 16 # Imports
17 17 #-------------------------------------------------------------------------------
18 18
19 19 import sys
20 20 import linecache
21 21 import warnings
22 22
23 23 from twisted.python import components
24 24 from twisted.python.failure import Failure
25 25 from zope.interface import Interface, implements, Attribute
26 26
27 27 from IPython.utils.coloransi import TermColors
28 28
29 29 from IPython.kernel.twistedutil import blockingCallFromThread
30 30 from IPython.kernel import error
31 31 from IPython.kernel.parallelfunction import ParallelFunction
32 32 from IPython.kernel.mapper import (
33 33 MultiEngineMapper,
34 34 IMultiEngineMapperFactory,
35 35 IMapper
36 36 )
37 37
38 38 from IPython.kernel.multiengine import IFullSynchronousMultiEngine
39 39
40 40
41 41 #-------------------------------------------------------------------------------
42 42 # Pending Result things
43 43 #-------------------------------------------------------------------------------
44 44
45 45 class IPendingResult(Interface):
46 46 """A representation of a result that is pending.
47 47
48 48 This class is similar to Twisted's `Deferred` object, but is designed to be
49 49 used in a synchronous context.
50 50 """
51 51
52 52 result_id=Attribute("ID of the deferred on the other side")
53 53 client=Attribute("A client that I came from")
54 54 r=Attribute("An attribute that is a property that calls and returns get_result")
55 55
56 56 def get_result(default=None, block=True):
57 57 """
58 58 Get a result that is pending.
59 59
60 60 :Parameters:
61 61 default
62 62 The value to return if the result is not ready.
63 63 block : boolean
64 64 Should I block for the result.
65 65
66 66 :Returns: The actual result or the default value.
67 67 """
68 68
69 69 def add_callback(f, *args, **kwargs):
70 70 """
71 71 Add a callback that is called with the result.
72 72
73 73 If the original result is foo, adding a callback will cause
74 74 f(foo, *args, **kwargs) to be returned instead. If multiple
75 75 callbacks are registered, they are chained together: the result of
76 76 one is passed to the next and so on.
77 77
78 78 Unlike Twisted's Deferred object, there is no errback chain. Thus
79 79 any exception raised will not be caught and handled. User must
80 80 catch these by hand when calling `get_result`.
81 81 """
82 82
83 83
84 84 class PendingResult(object):
85 85 """A representation of a result that is not yet ready.
86 86
87 87 A user should not create a `PendingResult` instance by hand.
88 88
89 89 Methods:
90 90
91 91 * `get_result`
92 92 * `add_callback`
93 93
94 94 Properties:
95 95
96 96 * `r`
97 97 """
98 98
99 99 def __init__(self, client, result_id):
100 100 """Create a PendingResult with a result_id and a client instance.
101 101
102 102 The client should implement `_getPendingResult(result_id, block)`.
103 103 """
104 104 self.client = client
105 105 self.result_id = result_id
106 106 self.called = False
107 107 self.raised = False
108 108 self.callbacks = []
109 109
110 110 def get_result(self, default=None, block=True):
111 111 """Get a result that is pending.
112 112
113 113 This method will connect to an IMultiEngine adapted controller
114 114 and see if the result is ready. If the action triggers an exception
115 115 raise it and record it. This method records the result/exception once it is
116 116 retrieved. Calling `get_result` again will get this cached result or will
117 117 re-raise the exception. The .r attribute is a property that calls
118 118 `get_result` with block=True.
119 119
120 120 :Parameters:
121 121 default
122 122 The value to return if the result is not ready.
123 123 block : boolean
124 124 Should I block for the result.
125 125
126 126 :Returns: The actual result or the default value.
127 127 """
128 128
129 129 if self.called:
130 130 if self.raised:
131 131 raise self.result[0], self.result[1], self.result[2]
132 132 else:
133 133 return self.result
134 134 try:
135 135 result = self.client.get_pending_deferred(self.result_id, block)
136 136 except error.ResultNotCompleted:
137 137 return default
138 138 except:
139 139 # Reraise other error, but first record them so they can be reraised
140 140 # later if .r or get_result is called again.
141 141 self.result = sys.exc_info()
142 142 self.called = True
143 143 self.raised = True
144 144 raise
145 145 else:
146 146 for cb in self.callbacks:
147 147 result = cb[0](result, *cb[1], **cb[2])
148 148 self.result = result
149 149 self.called = True
150 150 return result
151 151
152 152 def add_callback(self, f, *args, **kwargs):
153 153 """Add a callback that is called with the result.
154 154
155 155 If the original result is result, adding a callback will cause
156 156 f(result, *args, **kwargs) to be returned instead. If multiple
157 157 callbacks are registered, they are chained together: the result of
158 158 one is passed to the next and so on.
159 159
160 160 Unlike Twisted's Deferred object, there is no errback chain. Thus
161 161 any exception raised will not be caught and handled. User must
162 162 catch these by hand when calling `get_result`.
163 163 """
164 164 assert callable(f)
165 165 self.callbacks.append((f, args, kwargs))
166 166
167 167 def __cmp__(self, other):
168 168 if self.result_id < other.result_id:
169 169 return -1
170 170 else:
171 171 return 1
172 172
173 173 def _get_r(self):
174 174 return self.get_result(block=True)
175 175
176 176 r = property(_get_r)
177 177 """This property is a shortcut to a `get_result(block=True)`."""
178 178
179 179
180 180 #-------------------------------------------------------------------------------
181 181 # Pretty printing wrappers for certain lists
182 182 #-------------------------------------------------------------------------------
183 183
184 184 class ResultList(list):
185 185 """A subclass of list that pretty prints the output of `execute`/`get_result`."""
186 186
187 187 def __repr__(self):
188 188 output = []
189 189 # These colored prompts were not working on Windows
190 190 if sys.platform == 'win32':
191 191 blue = normal = red = green = ''
192 192 else:
193 193 blue = TermColors.Blue
194 194 normal = TermColors.Normal
195 195 red = TermColors.Red
196 196 green = TermColors.Green
197 197 output.append("<Results List>\n")
198 198 for cmd in self:
199 199 if isinstance(cmd, Failure):
200 200 output.append(cmd)
201 201 else:
202 202 target = cmd.get('id',None)
203 203 cmd_num = cmd.get('number',None)
204 204 cmd_stdin = cmd.get('input',{}).get('translated','No Input')
205 205 cmd_stdout = cmd.get('stdout', None)
206 206 cmd_stderr = cmd.get('stderr', None)
207 207 output.append("%s[%i]%s In [%i]:%s %s\n" % \
208 208 (green, target,
209 209 blue, cmd_num, normal, cmd_stdin))
210 210 if cmd_stdout:
211 211 output.append("%s[%i]%s Out[%i]:%s %s\n" % \
212 212 (green, target,
213 213 red, cmd_num, normal, cmd_stdout))
214 214 if cmd_stderr:
215 215 output.append("%s[%i]%s Err[%i]:\n%s %s" % \
216 216 (green, target,
217 217 red, cmd_num, normal, cmd_stderr))
218 218 return ''.join(output)
219 219
220 220
221 221 def wrapResultList(result):
222 222 """A function that wraps the output of `execute`/`get_result` -> `ResultList`."""
223 223 if len(result) == 0:
224 224 result = [result]
225 225 return ResultList(result)
226 226
227 227
228 228 class QueueStatusList(list):
229 229 """A subclass of list that pretty prints the output of `queue_status`."""
230 230
231 231 def __repr__(self):
232 232 output = []
233 233 output.append("<Queue Status List>\n")
234 234 for e in self:
235 235 output.append("Engine: %s\n" % repr(e[0]))
236 236 output.append(" Pending: %s\n" % repr(e[1]['pending']))
237 237 for q in e[1]['queue']:
238 238 output.append(" Command: %s\n" % repr(q))
239 239 return ''.join(output)
240 240
241 241
242 242 #-------------------------------------------------------------------------------
243 243 # InteractiveMultiEngineClient
244 244 #-------------------------------------------------------------------------------
245 245
246 246 class InteractiveMultiEngineClient(object):
247 247 """A mixin class that add a few methods to a multiengine client.
248 248
249 249 The methods in this mixin class are designed for interactive usage.
250 250 """
251 251
252 252 def activate(self):
253 253 """Make this `MultiEngineClient` active for parallel magic commands.
254 254
255 255 IPython has a magic command syntax to work with `MultiEngineClient` objects.
256 256 In a given IPython session there is a single active one. While
257 257 there can be many `MultiEngineClient` created and used by the user,
258 258 there is only one active one. The active `MultiEngineClient` is used whenever
259 259 the magic commands %px and %autopx are used.
260 260
261 261 The activate() method is called on a given `MultiEngineClient` to make it
262 262 active. Once this has been done, the magic commands can be used.
263 263 """
264 264
265 265 try:
266 266 # This is injected into __builtins__.
267 267 ip = get_ipython()
268 268 except NameError:
269 269 print "The IPython parallel magics (%result, %px, %autopx) only work within IPython."
270 270 else:
271 271 pmagic = ip.get_component('parallel_magic')
272 pmagic.active_multiengine_client = self
273
272 if pmagic is not None:
273 pmagic.active_multiengine_client = self
274 else:
275 print "You must first load the parallelmagic extension " \
276 "by doing '%load_ext parallelmagic'"
277
274 278 def __setitem__(self, key, value):
275 279 """Add a dictionary interface for pushing/pulling.
276 280
277 281 This functions as a shorthand for `push`.
278 282
279 283 :Parameters:
280 284 key : str
281 285 What to call the remote object.
282 286 value : object
283 287 The local Python object to push.
284 288 """
285 289 targets, block = self._findTargetsAndBlock()
286 290 return self.push({key:value}, targets=targets, block=block)
287 291
288 292 def __getitem__(self, key):
289 293 """Add a dictionary interface for pushing/pulling.
290 294
291 295 This functions as a shorthand to `pull`.
292 296
293 297 :Parameters:
294 298 - `key`: A string representing the key.
295 299 """
296 300 if isinstance(key, str):
297 301 targets, block = self._findTargetsAndBlock()
298 302 return self.pull(key, targets=targets, block=block)
299 303 else:
300 304 raise TypeError("__getitem__ only takes strs")
301 305
302 306 def __len__(self):
303 307 """Return the number of available engines."""
304 308 return len(self.get_ids())
305 309
306 310 #---------------------------------------------------------------------------
307 311 # Make this a context manager for with
308 312 #---------------------------------------------------------------------------
309 313
310 314 def findsource_file(self,f):
311 315 linecache.checkcache()
312 316 s = findsource(f.f_code) # findsource is not defined!
313 317 lnum = f.f_lineno
314 318 wsource = s[0][f.f_lineno:]
315 319 return strip_whitespace(wsource)
316 320
317 321 def findsource_ipython(self,f):
318 322 from IPython.core import ipapi
319 323 self.ip = ipapi.get()
320 324 wsource = [l+'\n' for l in
321 325 self.ip.input_hist_raw[-1].splitlines()[1:]]
322 326 return strip_whitespace(wsource)
323 327
324 328 def __enter__(self):
325 329 f = sys._getframe(1)
326 330 local_ns = f.f_locals
327 331 global_ns = f.f_globals
328 332 if f.f_code.co_filename == '<ipython console>':
329 333 s = self.findsource_ipython(f)
330 334 else:
331 335 s = self.findsource_file(f)
332 336
333 337 self._with_context_result = self.execute(s)
334 338
335 339 def __exit__ (self, etype, value, tb):
336 340 if issubclass(etype,error.StopLocalExecution):
337 341 return True
338 342
339 343
340 344 def remote():
341 345 m = 'Special exception to stop local execution of parallel code.'
342 346 raise error.StopLocalExecution(m)
343 347
344 348 def strip_whitespace(source):
345 349 # Expand tabs to avoid any confusion.
346 350 wsource = [l.expandtabs(4) for l in source]
347 351 # Detect the indentation level
348 352 done = False
349 353 for line in wsource:
350 354 if line.isspace():
351 355 continue
352 356 for col,char in enumerate(line):
353 357 if char != ' ':
354 358 done = True
355 359 break
356 360 if done:
357 361 break
358 362 # Now we know how much leading space there is in the code. Next, we
359 363 # extract up to the first line that has less indentation.
360 364 # WARNINGS: we skip comments that may be misindented, but we do NOT yet
361 365 # detect triple quoted strings that may have flush left text.
362 366 for lno,line in enumerate(wsource):
363 367 lead = line[:col]
364 368 if lead.isspace():
365 369 continue
366 370 else:
367 371 if not lead.lstrip().startswith('#'):
368 372 break
369 373 # The real 'with' source is up to lno
370 374 src_lines = [l[col:] for l in wsource[:lno+1]]
371 375
372 376 # Finally, check that the source's first non-comment line begins with the
373 377 # special call 'remote()'
374 378 for nline,line in enumerate(src_lines):
375 379 if line.isspace() or line.startswith('#'):
376 380 continue
377 381 if 'remote()' in line:
378 382 break
379 383 else:
380 384 raise ValueError('remote() call missing at the start of code')
381 385 src = ''.join(src_lines[nline+1:])
382 386 #print 'SRC:\n<<<<<<<>>>>>>>\n%s<<<<<>>>>>>' % src # dbg
383 387 return src
384 388
385 389
386 390 #-------------------------------------------------------------------------------
387 391 # The top-level MultiEngine client adaptor
388 392 #-------------------------------------------------------------------------------
389 393
390 394
391 395 _prop_warn = """\
392 396
393 397 We are currently refactoring the task dependency system. This might
394 398 involve the removal of this method and other methods related to engine
395 399 properties. Please see the docstrings for IPython.kernel.TaskRejectError
396 400 for more information."""
397 401
398 402
399 403 class IFullBlockingMultiEngineClient(Interface):
400 404 pass
401 405
402 406
403 407 class FullBlockingMultiEngineClient(InteractiveMultiEngineClient):
404 408 """
405 409 A blocking client to the `IMultiEngine` controller interface.
406 410
407 411 This class allows users to use a set of engines for a parallel
408 412 computation through the `IMultiEngine` interface. In this interface,
409 413 each engine has a specific id (an int) that is used to refer to the
410 414 engine, run code on it, etc.
411 415 """
412 416
413 417 implements(
414 418 IFullBlockingMultiEngineClient,
415 419 IMultiEngineMapperFactory,
416 420 IMapper
417 421 )
418 422
419 423 def __init__(self, smultiengine):
420 424 self.smultiengine = smultiengine
421 425 self.block = True
422 426 self.targets = 'all'
423 427
424 428 def _findBlock(self, block=None):
425 429 if block is None:
426 430 return self.block
427 431 else:
428 432 if block in (True, False):
429 433 return block
430 434 else:
431 435 raise ValueError("block must be True or False")
432 436
433 437 def _findTargets(self, targets=None):
434 438 if targets is None:
435 439 return self.targets
436 440 else:
437 441 if not isinstance(targets, (str,list,tuple,int)):
438 442 raise ValueError("targets must be a str, list, tuple or int")
439 443 return targets
440 444
441 445 def _findTargetsAndBlock(self, targets=None, block=None):
442 446 return self._findTargets(targets), self._findBlock(block)
443 447
444 448 def _blockFromThread(self, function, *args, **kwargs):
445 449 block = kwargs.get('block', None)
446 450 if block is None:
447 451 raise error.MissingBlockArgument("'block' keyword argument is missing")
448 452 result = blockingCallFromThread(function, *args, **kwargs)
449 453 if not block:
450 454 result = PendingResult(self, result)
451 455 return result
452 456
453 457 def get_pending_deferred(self, deferredID, block):
454 458 return blockingCallFromThread(self.smultiengine.get_pending_deferred, deferredID, block)
455 459
456 460 def barrier(self, pendingResults):
457 461 """Synchronize a set of `PendingResults`.
458 462
459 463 This method is a synchronization primitive that waits for a set of
460 464 `PendingResult` objects to complete. More specifically, barier does
461 465 the following.
462 466
463 467 * The `PendingResult`s are sorted by result_id.
464 468 * The `get_result` method is called for each `PendingResult` sequentially
465 469 with block=True.
466 470 * If a `PendingResult` gets a result that is an exception, it is
467 471 trapped and can be re-raised later by calling `get_result` again.
468 472 * The `PendingResult`s are flushed from the controller.
469 473
470 474 After barrier has been called on a `PendingResult`, its results can
471 475 be retrieved by calling `get_result` again or accesing the `r` attribute
472 476 of the instance.
473 477 """
474 478
475 479 # Convert to list for sorting and check class type
476 480 prList = list(pendingResults)
477 481 for pr in prList:
478 482 if not isinstance(pr, PendingResult):
479 483 raise error.NotAPendingResult("Objects passed to barrier must be PendingResult instances")
480 484
481 485 # Sort the PendingResults so they are in order
482 486 prList.sort()
483 487 # Block on each PendingResult object
484 488 for pr in prList:
485 489 try:
486 490 result = pr.get_result(block=True)
487 491 except Exception:
488 492 pass
489 493
490 494 def flush(self):
491 495 """
492 496 Clear all pending deferreds/results from the controller.
493 497
494 498 For each `PendingResult` that is created by this client, the controller
495 499 holds on to the result for that `PendingResult`. This can be a problem
496 500 if there are a large number of `PendingResult` objects that are created.
497 501
498 502 Once the result of the `PendingResult` has been retrieved, the result
499 503 is removed from the controller, but if a user doesn't get a result (
500 504 they just ignore the `PendingResult`) the result is kept forever on the
501 505 controller. This method allows the user to clear out all un-retrieved
502 506 results on the controller.
503 507 """
504 508 r = blockingCallFromThread(self.smultiengine.clear_pending_deferreds)
505 509 return r
506 510
507 511 clear_pending_results = flush
508 512
509 513 #---------------------------------------------------------------------------
510 514 # IEngineMultiplexer related methods
511 515 #---------------------------------------------------------------------------
512 516
513 517 def execute(self, lines, targets=None, block=None):
514 518 """
515 519 Execute code on a set of engines.
516 520
517 521 :Parameters:
518 522 lines : str
519 523 The Python code to execute as a string
520 524 targets : id or list of ids
521 525 The engine to use for the execution
522 526 block : boolean
523 527 If False, this method will return the actual result. If False,
524 528 a `PendingResult` is returned which can be used to get the result
525 529 at a later time.
526 530 """
527 531 targets, block = self._findTargetsAndBlock(targets, block)
528 532 result = blockingCallFromThread(self.smultiengine.execute, lines,
529 533 targets=targets, block=block)
530 534 if block:
531 535 result = ResultList(result)
532 536 else:
533 537 result = PendingResult(self, result)
534 538 result.add_callback(wrapResultList)
535 539 return result
536 540
537 541 def push(self, namespace, targets=None, block=None):
538 542 """
539 543 Push a dictionary of keys and values to engines namespace.
540 544
541 545 Each engine has a persistent namespace. This method is used to push
542 546 Python objects into that namespace.
543 547
544 548 The objects in the namespace must be pickleable.
545 549
546 550 :Parameters:
547 551 namespace : dict
548 552 A dict that contains Python objects to be injected into
549 553 the engine persistent namespace.
550 554 targets : id or list of ids
551 555 The engine to use for the execution
552 556 block : boolean
553 557 If False, this method will return the actual result. If False,
554 558 a `PendingResult` is returned which can be used to get the result
555 559 at a later time.
556 560 """
557 561 targets, block = self._findTargetsAndBlock(targets, block)
558 562 return self._blockFromThread(self.smultiengine.push, namespace,
559 563 targets=targets, block=block)
560 564
561 565 def pull(self, keys, targets=None, block=None):
562 566 """
563 567 Pull Python objects by key out of engines namespaces.
564 568
565 569 :Parameters:
566 570 keys : str or list of str
567 571 The names of the variables to be pulled
568 572 targets : id or list of ids
569 573 The engine to use for the execution
570 574 block : boolean
571 575 If False, this method will return the actual result. If False,
572 576 a `PendingResult` is returned which can be used to get the result
573 577 at a later time.
574 578 """
575 579 targets, block = self._findTargetsAndBlock(targets, block)
576 580 return self._blockFromThread(self.smultiengine.pull, keys, targets=targets, block=block)
577 581
578 582 def push_function(self, namespace, targets=None, block=None):
579 583 """
580 584 Push a Python function to an engine.
581 585
582 586 This method is used to push a Python function to an engine. This
583 587 method can then be used in code on the engines. Closures are not supported.
584 588
585 589 :Parameters:
586 590 namespace : dict
587 591 A dict whose values are the functions to be pushed. The keys give
588 592 that names that the function will appear as in the engines
589 593 namespace.
590 594 targets : id or list of ids
591 595 The engine to use for the execution
592 596 block : boolean
593 597 If False, this method will return the actual result. If False,
594 598 a `PendingResult` is returned which can be used to get the result
595 599 at a later time.
596 600 """
597 601 targets, block = self._findTargetsAndBlock(targets, block)
598 602 return self._blockFromThread(self.smultiengine.push_function, namespace, targets=targets, block=block)
599 603
600 604 def pull_function(self, keys, targets=None, block=None):
601 605 """
602 606 Pull a Python function from an engine.
603 607
604 608 This method is used to pull a Python function from an engine.
605 609 Closures are not supported.
606 610
607 611 :Parameters:
608 612 keys : str or list of str
609 613 The names of the functions to be pulled
610 614 targets : id or list of ids
611 615 The engine to use for the execution
612 616 block : boolean
613 617 If False, this method will return the actual result. If False,
614 618 a `PendingResult` is returned which can be used to get the result
615 619 at a later time.
616 620 """
617 621 targets, block = self._findTargetsAndBlock(targets, block)
618 622 return self._blockFromThread(self.smultiengine.pull_function, keys, targets=targets, block=block)
619 623
620 624 def push_serialized(self, namespace, targets=None, block=None):
621 625 targets, block = self._findTargetsAndBlock(targets, block)
622 626 return self._blockFromThread(self.smultiengine.push_serialized, namespace, targets=targets, block=block)
623 627
624 628 def pull_serialized(self, keys, targets=None, block=None):
625 629 targets, block = self._findTargetsAndBlock(targets, block)
626 630 return self._blockFromThread(self.smultiengine.pull_serialized, keys, targets=targets, block=block)
627 631
628 632 def get_result(self, i=None, targets=None, block=None):
629 633 """
630 634 Get a previous result.
631 635
632 636 When code is executed in an engine, a dict is created and returned. This
633 637 method retrieves that dict for previous commands.
634 638
635 639 :Parameters:
636 640 i : int
637 641 The number of the result to get
638 642 targets : id or list of ids
639 643 The engine to use for the execution
640 644 block : boolean
641 645 If False, this method will return the actual result. If False,
642 646 a `PendingResult` is returned which can be used to get the result
643 647 at a later time.
644 648 """
645 649 targets, block = self._findTargetsAndBlock(targets, block)
646 650 result = blockingCallFromThread(self.smultiengine.get_result, i, targets=targets, block=block)
647 651 if block:
648 652 result = ResultList(result)
649 653 else:
650 654 result = PendingResult(self, result)
651 655 result.add_callback(wrapResultList)
652 656 return result
653 657
654 658 def reset(self, targets=None, block=None):
655 659 """
656 660 Reset an engine.
657 661
658 662 This method clears out the namespace of an engine.
659 663
660 664 :Parameters:
661 665 targets : id or list of ids
662 666 The engine to use for the execution
663 667 block : boolean
664 668 If False, this method will return the actual result. If False,
665 669 a `PendingResult` is returned which can be used to get the result
666 670 at a later time.
667 671 """
668 672 targets, block = self._findTargetsAndBlock(targets, block)
669 673 return self._blockFromThread(self.smultiengine.reset, targets=targets, block=block)
670 674
671 675 def keys(self, targets=None, block=None):
672 676 """
673 677 Get a list of all the variables in an engine's namespace.
674 678
675 679 :Parameters:
676 680 targets : id or list of ids
677 681 The engine to use for the execution
678 682 block : boolean
679 683 If False, this method will return the actual result. If False,
680 684 a `PendingResult` is returned which can be used to get the result
681 685 at a later time.
682 686 """
683 687 targets, block = self._findTargetsAndBlock(targets, block)
684 688 return self._blockFromThread(self.smultiengine.keys, targets=targets, block=block)
685 689
686 690 def kill(self, controller=False, targets=None, block=None):
687 691 """
688 692 Kill the engines and controller.
689 693
690 694 This method is used to stop the engine and controller by calling
691 695 `reactor.stop`.
692 696
693 697 :Parameters:
694 698 controller : boolean
695 699 If True, kill the engines and controller. If False, just the
696 700 engines
697 701 targets : id or list of ids
698 702 The engine to use for the execution
699 703 block : boolean
700 704 If False, this method will return the actual result. If False,
701 705 a `PendingResult` is returned which can be used to get the result
702 706 at a later time.
703 707 """
704 708 targets, block = self._findTargetsAndBlock(targets, block)
705 709 return self._blockFromThread(self.smultiengine.kill, controller, targets=targets, block=block)
706 710
707 711 def clear_queue(self, targets=None, block=None):
708 712 """
709 713 Clear out the controller's queue for an engine.
710 714
711 715 The controller maintains a queue for each engine. This clear it out.
712 716
713 717 :Parameters:
714 718 targets : id or list of ids
715 719 The engine to use for the execution
716 720 block : boolean
717 721 If False, this method will return the actual result. If False,
718 722 a `PendingResult` is returned which can be used to get the result
719 723 at a later time.
720 724 """
721 725 targets, block = self._findTargetsAndBlock(targets, block)
722 726 return self._blockFromThread(self.smultiengine.clear_queue, targets=targets, block=block)
723 727
724 728 def queue_status(self, targets=None, block=None):
725 729 """
726 730 Get the status of an engines queue.
727 731
728 732 :Parameters:
729 733 targets : id or list of ids
730 734 The engine to use for the execution
731 735 block : boolean
732 736 If False, this method will return the actual result. If False,
733 737 a `PendingResult` is returned which can be used to get the result
734 738 at a later time.
735 739 """
736 740 targets, block = self._findTargetsAndBlock(targets, block)
737 741 return self._blockFromThread(self.smultiengine.queue_status, targets=targets, block=block)
738 742
739 743 def set_properties(self, properties, targets=None, block=None):
740 744 warnings.warn(_prop_warn)
741 745 targets, block = self._findTargetsAndBlock(targets, block)
742 746 return self._blockFromThread(self.smultiengine.set_properties, properties, targets=targets, block=block)
743 747
744 748 def get_properties(self, keys=None, targets=None, block=None):
745 749 warnings.warn(_prop_warn)
746 750 targets, block = self._findTargetsAndBlock(targets, block)
747 751 return self._blockFromThread(self.smultiengine.get_properties, keys, targets=targets, block=block)
748 752
749 753 def has_properties(self, keys, targets=None, block=None):
750 754 warnings.warn(_prop_warn)
751 755 targets, block = self._findTargetsAndBlock(targets, block)
752 756 return self._blockFromThread(self.smultiengine.has_properties, keys, targets=targets, block=block)
753 757
754 758 def del_properties(self, keys, targets=None, block=None):
755 759 warnings.warn(_prop_warn)
756 760 targets, block = self._findTargetsAndBlock(targets, block)
757 761 return self._blockFromThread(self.smultiengine.del_properties, keys, targets=targets, block=block)
758 762
759 763 def clear_properties(self, targets=None, block=None):
760 764 warnings.warn(_prop_warn)
761 765 targets, block = self._findTargetsAndBlock(targets, block)
762 766 return self._blockFromThread(self.smultiengine.clear_properties, targets=targets, block=block)
763 767
764 768 #---------------------------------------------------------------------------
765 769 # IMultiEngine related methods
766 770 #---------------------------------------------------------------------------
767 771
768 772 def get_ids(self):
769 773 """
770 774 Returns the ids of currently registered engines.
771 775 """
772 776 result = blockingCallFromThread(self.smultiengine.get_ids)
773 777 return result
774 778
775 779 #---------------------------------------------------------------------------
776 780 # IMultiEngineCoordinator
777 781 #---------------------------------------------------------------------------
778 782
779 783 def scatter(self, key, seq, dist='b', flatten=False, targets=None, block=None):
780 784 """
781 785 Partition a Python sequence and send the partitions to a set of engines.
782 786 """
783 787 targets, block = self._findTargetsAndBlock(targets, block)
784 788 return self._blockFromThread(self.smultiengine.scatter, key, seq,
785 789 dist, flatten, targets=targets, block=block)
786 790
787 791 def gather(self, key, dist='b', targets=None, block=None):
788 792 """
789 793 Gather a partitioned sequence on a set of engines as a single local seq.
790 794 """
791 795 targets, block = self._findTargetsAndBlock(targets, block)
792 796 return self._blockFromThread(self.smultiengine.gather, key, dist,
793 797 targets=targets, block=block)
794 798
795 799 def raw_map(self, func, seq, dist='b', targets=None, block=None):
796 800 """
797 801 A parallelized version of Python's builtin map.
798 802
799 803 This has a slightly different syntax than the builtin `map`.
800 804 This is needed because we need to have keyword arguments and thus
801 805 can't use *args to capture all the sequences. Instead, they must
802 806 be passed in a list or tuple.
803 807
804 808 raw_map(func, seqs) -> map(func, seqs[0], seqs[1], ...)
805 809
806 810 Most users will want to use parallel functions or the `mapper`
807 811 and `map` methods for an API that follows that of the builtin
808 812 `map`.
809 813 """
810 814 targets, block = self._findTargetsAndBlock(targets, block)
811 815 return self._blockFromThread(self.smultiengine.raw_map, func, seq,
812 816 dist, targets=targets, block=block)
813 817
814 818 def map(self, func, *sequences):
815 819 """
816 820 A parallel version of Python's builtin `map` function.
817 821
818 822 This method applies a function to sequences of arguments. It
819 823 follows the same syntax as the builtin `map`.
820 824
821 825 This method creates a mapper objects by calling `self.mapper` with
822 826 no arguments and then uses that mapper to do the mapping. See
823 827 the documentation of `mapper` for more details.
824 828 """
825 829 return self.mapper().map(func, *sequences)
826 830
827 831 def mapper(self, dist='b', targets='all', block=None):
828 832 """
829 833 Create a mapper object that has a `map` method.
830 834
831 835 This method returns an object that implements the `IMapper`
832 836 interface. This method is a factory that is used to control how
833 837 the map happens.
834 838
835 839 :Parameters:
836 840 dist : str
837 841 What decomposition to use, 'b' is the only one supported
838 842 currently
839 843 targets : str, int, sequence of ints
840 844 Which engines to use for the map
841 845 block : boolean
842 846 Should calls to `map` block or not
843 847 """
844 848 return MultiEngineMapper(self, dist, targets, block)
845 849
846 850 def parallel(self, dist='b', targets=None, block=None):
847 851 """
848 852 A decorator that turns a function into a parallel function.
849 853
850 854 This can be used as:
851 855
852 856 @parallel()
853 857 def f(x, y)
854 858 ...
855 859
856 860 f(range(10), range(10))
857 861
858 862 This causes f(0,0), f(1,1), ... to be called in parallel.
859 863
860 864 :Parameters:
861 865 dist : str
862 866 What decomposition to use, 'b' is the only one supported
863 867 currently
864 868 targets : str, int, sequence of ints
865 869 Which engines to use for the map
866 870 block : boolean
867 871 Should calls to `map` block or not
868 872 """
869 873 targets, block = self._findTargetsAndBlock(targets, block)
870 874 mapper = self.mapper(dist, targets, block)
871 875 pf = ParallelFunction(mapper)
872 876 return pf
873 877
874 878 #---------------------------------------------------------------------------
875 879 # IMultiEngineExtras
876 880 #---------------------------------------------------------------------------
877 881
878 882 def zip_pull(self, keys, targets=None, block=None):
879 883 targets, block = self._findTargetsAndBlock(targets, block)
880 884 return self._blockFromThread(self.smultiengine.zip_pull, keys,
881 885 targets=targets, block=block)
882 886
883 887 def run(self, filename, targets=None, block=None):
884 888 """
885 889 Run a Python code in a file on the engines.
886 890
887 891 :Parameters:
888 892 filename : str
889 893 The name of the local file to run
890 894 targets : id or list of ids
891 895 The engine to use for the execution
892 896 block : boolean
893 897 If False, this method will return the actual result. If False,
894 898 a `PendingResult` is returned which can be used to get the result
895 899 at a later time.
896 900 """
897 901 targets, block = self._findTargetsAndBlock(targets, block)
898 902 return self._blockFromThread(self.smultiengine.run, filename,
899 903 targets=targets, block=block)
900 904
901 905 def benchmark(self, push_size=10000):
902 906 """
903 907 Run performance benchmarks for the current IPython cluster.
904 908
905 909 This method tests both the latency of sending command and data to the
906 910 engines as well as the throughput of sending large objects to the
907 911 engines using push. The latency is measured by having one or more
908 912 engines execute the command 'pass'. The throughput is measure by
909 913 sending an NumPy array of size `push_size` to one or more engines.
910 914
911 915 These benchmarks will vary widely on different hardware and networks
912 916 and thus can be used to get an idea of the performance characteristics
913 917 of a particular configuration of an IPython controller and engines.
914 918
915 919 This function is not testable within our current testing framework.
916 920 """
917 921 import timeit, __builtin__
918 922 __builtin__._mec_self = self
919 923 benchmarks = {}
920 924 repeat = 3
921 925 count = 10
922 926
923 927 timer = timeit.Timer('_mec_self.execute("pass",0)')
924 928 result = 1000*min(timer.repeat(repeat,count))/count
925 929 benchmarks['single_engine_latency'] = (result,'msec')
926 930
927 931 timer = timeit.Timer('_mec_self.execute("pass")')
928 932 result = 1000*min(timer.repeat(repeat,count))/count
929 933 benchmarks['all_engine_latency'] = (result,'msec')
930 934
931 935 try:
932 936 import numpy as np
933 937 except:
934 938 pass
935 939 else:
936 940 timer = timeit.Timer(
937 941 "_mec_self.push(d)",
938 942 "import numpy as np; d = dict(a=np.zeros(%r,dtype='float64'))" % push_size
939 943 )
940 944 result = min(timer.repeat(repeat,count))/count
941 945 benchmarks['all_engine_push'] = (1e-6*push_size*8/result, 'MB/sec')
942 946
943 947 try:
944 948 import numpy as np
945 949 except:
946 950 pass
947 951 else:
948 952 timer = timeit.Timer(
949 953 "_mec_self.push(d,0)",
950 954 "import numpy as np; d = dict(a=np.zeros(%r,dtype='float64'))" % push_size
951 955 )
952 956 result = min(timer.repeat(repeat,count))/count
953 957 benchmarks['single_engine_push'] = (1e-6*push_size*8/result, 'MB/sec')
954 958
955 959 return benchmarks
956 960
957 961
958 962 components.registerAdapter(FullBlockingMultiEngineClient,
959 963 IFullSynchronousMultiEngine, IFullBlockingMultiEngineClient)
960 964
961 965
962 966
963 967
General Comments 0
You need to be logged in to leave comments. Login now