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