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