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