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