##// END OF EJS Templates
Move most readline code from InteractiveShell to terminal subclass...
Thomas Kluyver -
Show More
@@ -1,3416 +1,3242 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 from __future__ import absolute_import, print_function
14 14
15 15 import __future__
16 16 import abc
17 17 import ast
18 18 import atexit
19 19 import functools
20 20 import os
21 21 import re
22 22 import runpy
23 23 import sys
24 24 import tempfile
25 25 import traceback
26 26 import types
27 27 import subprocess
28 28 import warnings
29 29 from io import open as io_open
30 30
31 31 from pickleshare import PickleShareDB
32 32
33 33 from traitlets.config.configurable import SingletonConfigurable
34 34 from IPython.core import debugger, oinspect
35 35 from IPython.core import magic
36 36 from IPython.core import page
37 37 from IPython.core import prefilter
38 38 from IPython.core import shadowns
39 39 from IPython.core import ultratb
40 40 from IPython.core.alias import Alias, AliasManager
41 41 from IPython.core.autocall import ExitAutocall
42 42 from IPython.core.builtin_trap import BuiltinTrap
43 43 from IPython.core.events import EventManager, available_events
44 44 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
45 45 from IPython.core.display_trap import DisplayTrap
46 46 from IPython.core.displayhook import DisplayHook
47 47 from IPython.core.displaypub import DisplayPublisher
48 48 from IPython.core.error import InputRejected, UsageError
49 49 from IPython.core.extensions import ExtensionManager
50 50 from IPython.core.formatters import DisplayFormatter
51 51 from IPython.core.history import HistoryManager
52 52 from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2
53 53 from IPython.core.logger import Logger
54 54 from IPython.core.macro import Macro
55 55 from IPython.core.payload import PayloadManager
56 56 from IPython.core.prefilter import PrefilterManager
57 57 from IPython.core.profiledir import ProfileDir
58 58 from IPython.core.prompts import PromptManager
59 59 from IPython.core.usage import default_banner
60 60 from IPython.testing.skipdoctest import skip_doctest
61 61 from IPython.utils import PyColorize
62 62 from IPython.utils import io
63 63 from IPython.utils import py3compat
64 64 from IPython.utils import openpy
65 from IPython.utils.contexts import NoOpContext
65 66 from IPython.utils.decorators import undoc
66 67 from IPython.utils.io import ask_yes_no
67 68 from IPython.utils.ipstruct import Struct
68 69 from IPython.paths import get_ipython_dir
69 70 from IPython.utils.path import get_home_dir, get_py_filename, unquote_filename, ensure_dir_exists
70 71 from IPython.utils.process import system, getoutput
71 72 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
72 73 with_metaclass, iteritems)
73 74 from IPython.utils.strdispatch import StrDispatch
74 75 from IPython.utils.syspathcontext import prepended_to_syspath
75 76 from IPython.utils.text import (format_screen, LSString, SList,
76 77 DollarFormatter)
77 78 from traitlets import (Integer, Bool, CBool, CaselessStrEnum, Enum,
78 79 List, Dict, Unicode, Instance, Type)
79 80 from IPython.utils.warn import warn, error
80 81 import IPython.core.hooks
81 82
82 83 #-----------------------------------------------------------------------------
83 84 # Globals
84 85 #-----------------------------------------------------------------------------
85 86
86 87 # compiled regexps for autoindent management
87 88 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
88 89
89 90 #-----------------------------------------------------------------------------
90 91 # Utilities
91 92 #-----------------------------------------------------------------------------
92 93
93 94 @undoc
94 95 def softspace(file, newvalue):
95 96 """Copied from code.py, to remove the dependency"""
96 97
97 98 oldvalue = 0
98 99 try:
99 100 oldvalue = file.softspace
100 101 except AttributeError:
101 102 pass
102 103 try:
103 104 file.softspace = newvalue
104 105 except (AttributeError, TypeError):
105 106 # "attribute-less object" or "read-only attributes"
106 107 pass
107 108 return oldvalue
108 109
109 110 @undoc
110 111 def no_op(*a, **kw): pass
111 112
112 @undoc
113 class NoOpContext(object):
114 def __enter__(self): pass
115 def __exit__(self, type, value, traceback): pass
116 no_op_context = NoOpContext()
117 113
118 114 class SpaceInInput(Exception): pass
119 115
120 116 @undoc
121 117 class Bunch: pass
122 118
123 119
124 120 def get_default_colors():
125 121 if sys.platform=='darwin':
126 122 return "LightBG"
127 123 elif os.name=='nt':
128 124 return 'Linux'
129 125 else:
130 126 return 'Linux'
131 127
132 128
133 129 class SeparateUnicode(Unicode):
134 130 r"""A Unicode subclass to validate separate_in, separate_out, etc.
135 131
136 132 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
137 133 """
138 134
139 135 def validate(self, obj, value):
140 136 if value == '0': value = ''
141 137 value = value.replace('\\n','\n')
142 138 return super(SeparateUnicode, self).validate(obj, value)
143 139
144 140
145 class ReadlineNoRecord(object):
146 """Context manager to execute some code, then reload readline history
147 so that interactive input to the code doesn't appear when pressing up."""
148 def __init__(self, shell):
149 self.shell = shell
150 self._nested_level = 0
151
152 def __enter__(self):
153 if self._nested_level == 0:
154 try:
155 self.orig_length = self.current_length()
156 self.readline_tail = self.get_readline_tail()
157 except (AttributeError, IndexError): # Can fail with pyreadline
158 self.orig_length, self.readline_tail = 999999, []
159 self._nested_level += 1
160
161 def __exit__(self, type, value, traceback):
162 self._nested_level -= 1
163 if self._nested_level == 0:
164 # Try clipping the end if it's got longer
165 try:
166 e = self.current_length() - self.orig_length
167 if e > 0:
168 for _ in range(e):
169 self.shell.readline.remove_history_item(self.orig_length)
170
171 # If it still doesn't match, just reload readline history.
172 if self.current_length() != self.orig_length \
173 or self.get_readline_tail() != self.readline_tail:
174 self.shell.refill_readline_hist()
175 except (AttributeError, IndexError):
176 pass
177 # Returning False will cause exceptions to propagate
178 return False
179
180 def current_length(self):
181 return self.shell.readline.get_current_history_length()
182
183 def get_readline_tail(self, n=10):
184 """Get the last n items in readline history."""
185 end = self.shell.readline.get_current_history_length() + 1
186 start = max(end-n, 1)
187 ghi = self.shell.readline.get_history_item
188 return [ghi(x) for x in range(start, end)]
189
190
191 141 @undoc
192 142 class DummyMod(object):
193 143 """A dummy module used for IPython's interactive module when
194 144 a namespace must be assigned to the module's __dict__."""
195 145 pass
196 146
197 147
198 148 class ExecutionResult(object):
199 149 """The result of a call to :meth:`InteractiveShell.run_cell`
200 150
201 151 Stores information about what took place.
202 152 """
203 153 execution_count = None
204 154 error_before_exec = None
205 155 error_in_exec = None
206 156 result = None
207 157
208 158 @property
209 159 def success(self):
210 160 return (self.error_before_exec is None) and (self.error_in_exec is None)
211 161
212 162 def raise_error(self):
213 163 """Reraises error if `success` is `False`, otherwise does nothing"""
214 164 if self.error_before_exec is not None:
215 165 raise self.error_before_exec
216 166 if self.error_in_exec is not None:
217 167 raise self.error_in_exec
218 168
219 169
220 170 class InteractiveShell(SingletonConfigurable):
221 171 """An enhanced, interactive shell for Python."""
222 172
223 173 _instance = None
224 174
225 175 ast_transformers = List([], config=True, help=
226 176 """
227 177 A list of ast.NodeTransformer subclass instances, which will be applied
228 178 to user input before code is run.
229 179 """
230 180 )
231 181
232 182 autocall = Enum((0,1,2), default_value=0, config=True, help=
233 183 """
234 184 Make IPython automatically call any callable object even if you didn't
235 185 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
236 186 automatically. The value can be '0' to disable the feature, '1' for
237 187 'smart' autocall, where it is not applied if there are no more
238 188 arguments on the line, and '2' for 'full' autocall, where all callable
239 189 objects are automatically called (even if no arguments are present).
240 190 """
241 191 )
242 192 # TODO: remove all autoindent logic and put into frontends.
243 193 # We can't do this yet because even runlines uses the autoindent.
244 194 autoindent = CBool(True, config=True, help=
245 195 """
246 196 Autoindent IPython code entered interactively.
247 197 """
248 198 )
249 199 automagic = CBool(True, config=True, help=
250 200 """
251 201 Enable magic commands to be called without the leading %.
252 202 """
253 203 )
254 204
255 205 banner1 = Unicode(default_banner, config=True,
256 206 help="""The part of the banner to be printed before the profile"""
257 207 )
258 208 banner2 = Unicode('', config=True,
259 209 help="""The part of the banner to be printed after the profile"""
260 210 )
261 211
262 212 cache_size = Integer(1000, config=True, help=
263 213 """
264 214 Set the size of the output cache. The default is 1000, you can
265 215 change it permanently in your config file. Setting it to 0 completely
266 216 disables the caching system, and the minimum value accepted is 20 (if
267 217 you provide a value less than 20, it is reset to 0 and a warning is
268 218 issued). This limit is defined because otherwise you'll spend more
269 219 time re-flushing a too small cache than working
270 220 """
271 221 )
272 222 color_info = CBool(True, config=True, help=
273 223 """
274 224 Use colors for displaying information about objects. Because this
275 225 information is passed through a pager (like 'less'), and some pagers
276 226 get confused with color codes, this capability can be turned off.
277 227 """
278 228 )
279 229 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
280 230 default_value=get_default_colors(), config=True,
281 231 help="Set the color scheme (NoColor, Linux, or LightBG)."
282 232 )
283 233 colors_force = CBool(False, help=
284 234 """
285 235 Force use of ANSI color codes, regardless of OS and readline
286 236 availability.
287 237 """
288 238 # FIXME: This is essentially a hack to allow ZMQShell to show colors
289 239 # without readline on Win32. When the ZMQ formatting system is
290 240 # refactored, this should be removed.
291 241 )
292 242 debug = CBool(False, config=True)
293 243 deep_reload = CBool(False, config=True, help=
294 244 """
295 245 **Deprecated**
296 246
297 247 Enable deep (recursive) reloading by default. IPython can use the
298 248 deep_reload module which reloads changes in modules recursively (it
299 249 replaces the reload() function, so you don't need to change anything to
300 250 use it). `deep_reload` forces a full reload of modules whose code may
301 251 have changed, which the default reload() function does not. When
302 252 deep_reload is off, IPython will use the normal reload(), but
303 253 deep_reload will still be available as dreload().
304 254 """
305 255 )
306 256 disable_failing_post_execute = CBool(False, config=True,
307 257 help="Don't call post-execute functions that have failed in the past."
308 258 )
309 259 display_formatter = Instance(DisplayFormatter, allow_none=True)
310 260 displayhook_class = Type(DisplayHook)
311 261 display_pub_class = Type(DisplayPublisher)
312 262 data_pub_class = None
313 263
314 264 exit_now = CBool(False)
315 265 exiter = Instance(ExitAutocall)
316 266 def _exiter_default(self):
317 267 return ExitAutocall(self)
318 268 # Monotonically increasing execution counter
319 269 execution_count = Integer(1)
320 270 filename = Unicode("<ipython console>")
321 271 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
322 272
323 273 # Input splitter, to transform input line by line and detect when a block
324 274 # is ready to be executed.
325 275 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
326 276 (), {'line_input_checker': True})
327 277
328 278 # This InputSplitter instance is used to transform completed cells before
329 279 # running them. It allows cell magics to contain blank lines.
330 280 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
331 281 (), {'line_input_checker': False})
332 282
333 283 logstart = CBool(False, config=True, help=
334 284 """
335 285 Start logging to the default log file in overwrite mode.
336 286 Use `logappend` to specify a log file to **append** logs to.
337 287 """
338 288 )
339 289 logfile = Unicode('', config=True, help=
340 290 """
341 291 The name of the logfile to use.
342 292 """
343 293 )
344 294 logappend = Unicode('', config=True, help=
345 295 """
346 296 Start logging to the given file in append mode.
347 297 Use `logfile` to specify a log file to **overwrite** logs to.
348 298 """
349 299 )
350 300 object_info_string_level = Enum((0,1,2), default_value=0,
351 301 config=True)
352 302 pdb = CBool(False, config=True, help=
353 303 """
354 304 Automatically call the pdb debugger after every exception.
355 305 """
356 306 )
357 307 multiline_history = CBool(sys.platform != 'win32', config=True,
358 308 help="Save multi-line entries as one entry in readline history"
359 309 )
360 310 display_page = Bool(False, config=True,
361 311 help="""If True, anything that would be passed to the pager
362 312 will be displayed as regular output instead."""
363 313 )
364 314
365 315 # deprecated prompt traits:
366 316
367 317 prompt_in1 = Unicode('In [\\#]: ', config=True,
368 318 help="Deprecated, use PromptManager.in_template")
369 319 prompt_in2 = Unicode(' .\\D.: ', config=True,
370 320 help="Deprecated, use PromptManager.in2_template")
371 321 prompt_out = Unicode('Out[\\#]: ', config=True,
372 322 help="Deprecated, use PromptManager.out_template")
373 323 prompts_pad_left = CBool(True, config=True,
374 324 help="Deprecated, use PromptManager.justify")
375 325
376 326 def _prompt_trait_changed(self, name, old, new):
377 327 table = {
378 328 'prompt_in1' : 'in_template',
379 329 'prompt_in2' : 'in2_template',
380 330 'prompt_out' : 'out_template',
381 331 'prompts_pad_left' : 'justify',
382 332 }
383 333 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format(
384 334 name=name, newname=table[name])
385 335 )
386 336 # protect against weird cases where self.config may not exist:
387 337 if self.config is not None:
388 338 # propagate to corresponding PromptManager trait
389 339 setattr(self.config.PromptManager, table[name], new)
390 340
391 341 _prompt_in1_changed = _prompt_trait_changed
392 342 _prompt_in2_changed = _prompt_trait_changed
393 343 _prompt_out_changed = _prompt_trait_changed
394 344 _prompt_pad_left_changed = _prompt_trait_changed
395 345
396 346 show_rewritten_input = CBool(True, config=True,
397 347 help="Show rewritten input, e.g. for autocall."
398 348 )
399 349
400 350 quiet = CBool(False, config=True)
401 351
402 352 history_length = Integer(10000, config=True)
403 353
404 354 history_load_length = Integer(1000, config=True, help=
405 355 """
406 356 The number of saved history entries to be loaded
407 357 into the readline buffer at startup.
408 358 """
409 359 )
410 360
411 361 # The readline stuff will eventually be moved to the terminal subclass
412 362 # but for now, we can't do that as readline is welded in everywhere.
413 363 readline_use = CBool(True, config=True)
414 364 readline_remove_delims = Unicode('-/~', config=True)
415 365 readline_delims = Unicode() # set by init_readline()
416 366 # don't use \M- bindings by default, because they
417 367 # conflict with 8-bit encodings. See gh-58,gh-88
418 368 readline_parse_and_bind = List([
419 369 'tab: complete',
420 370 '"\C-l": clear-screen',
421 371 'set show-all-if-ambiguous on',
422 372 '"\C-o": tab-insert',
423 373 '"\C-r": reverse-search-history',
424 374 '"\C-s": forward-search-history',
425 375 '"\C-p": history-search-backward',
426 376 '"\C-n": history-search-forward',
427 377 '"\e[A": history-search-backward',
428 378 '"\e[B": history-search-forward',
429 379 '"\C-k": kill-line',
430 380 '"\C-u": unix-line-discard',
431 381 ], config=True)
432 382
433 383 _custom_readline_config = False
434 384
435 385 def _readline_parse_and_bind_changed(self, name, old, new):
436 386 # notice that readline config is customized
437 387 # indicates that it should have higher priority than inputrc
438 388 self._custom_readline_config = True
439 389
440 390 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
441 391 default_value='last_expr', config=True,
442 392 help="""
443 393 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
444 394 run interactively (displaying output from expressions).""")
445 395
446 396 # TODO: this part of prompt management should be moved to the frontends.
447 397 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
448 398 separate_in = SeparateUnicode('\n', config=True)
449 399 separate_out = SeparateUnicode('', config=True)
450 400 separate_out2 = SeparateUnicode('', config=True)
451 401 wildcards_case_sensitive = CBool(True, config=True)
452 402 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
453 403 default_value='Context', config=True)
454 404
455 405 # Subcomponents of InteractiveShell
456 406 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
457 407 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
458 408 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
459 409 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
460 410 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
461 411 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
462 412 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
463 413 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
464 414
465 415 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
466 416 @property
467 417 def profile(self):
468 418 if self.profile_dir is not None:
469 419 name = os.path.basename(self.profile_dir.location)
470 420 return name.replace('profile_','')
471 421
472 422
473 423 # Private interface
474 424 _post_execute = Dict()
475 425
476 426 # Tracks any GUI loop loaded for pylab
477 427 pylab_gui_select = None
478 428
479 429 def __init__(self, ipython_dir=None, profile_dir=None,
480 430 user_module=None, user_ns=None,
481 431 custom_exceptions=((), None), **kwargs):
482 432
483 433 # This is where traits with a config_key argument are updated
484 434 # from the values on config.
485 435 super(InteractiveShell, self).__init__(**kwargs)
486 436 self.configurables = [self]
487 437
488 438 # These are relatively independent and stateless
489 439 self.init_ipython_dir(ipython_dir)
490 440 self.init_profile_dir(profile_dir)
491 441 self.init_instance_attrs()
492 442 self.init_environment()
493 443
494 444 # Check if we're in a virtualenv, and set up sys.path.
495 445 self.init_virtualenv()
496 446
497 447 # Create namespaces (user_ns, user_global_ns, etc.)
498 448 self.init_create_namespaces(user_module, user_ns)
499 449 # This has to be done after init_create_namespaces because it uses
500 450 # something in self.user_ns, but before init_sys_modules, which
501 451 # is the first thing to modify sys.
502 452 # TODO: When we override sys.stdout and sys.stderr before this class
503 453 # is created, we are saving the overridden ones here. Not sure if this
504 454 # is what we want to do.
505 455 self.save_sys_module_state()
506 456 self.init_sys_modules()
507 457
508 458 # While we're trying to have each part of the code directly access what
509 459 # it needs without keeping redundant references to objects, we have too
510 460 # much legacy code that expects ip.db to exist.
511 461 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
512 462
513 463 self.init_history()
514 464 self.init_encoding()
515 465 self.init_prefilter()
516 466
517 467 self.init_syntax_highlighting()
518 468 self.init_hooks()
519 469 self.init_events()
520 470 self.init_pushd_popd_magic()
521 471 # self.init_traceback_handlers use to be here, but we moved it below
522 472 # because it and init_io have to come after init_readline.
523 473 self.init_user_ns()
524 474 self.init_logger()
525 475 self.init_builtins()
526 476
527 477 # The following was in post_config_initialization
528 478 self.init_inspector()
529 479 # init_readline() must come before init_io(), because init_io uses
530 480 # readline related things.
531 481 self.init_readline()
532 482 # We save this here in case user code replaces raw_input, but it needs
533 483 # to be after init_readline(), because PyPy's readline works by replacing
534 484 # raw_input.
535 485 if py3compat.PY3:
536 486 self.raw_input_original = input
537 487 else:
538 488 self.raw_input_original = raw_input
539 489 # init_completer must come after init_readline, because it needs to
540 490 # know whether readline is present or not system-wide to configure the
541 491 # completers, since the completion machinery can now operate
542 492 # independently of readline (e.g. over the network)
543 493 self.init_completer()
544 494 # TODO: init_io() needs to happen before init_traceback handlers
545 495 # because the traceback handlers hardcode the stdout/stderr streams.
546 496 # This logic in in debugger.Pdb and should eventually be changed.
547 497 self.init_io()
548 498 self.init_traceback_handlers(custom_exceptions)
549 499 self.init_prompts()
550 500 self.init_display_formatter()
551 501 self.init_display_pub()
552 502 self.init_data_pub()
553 503 self.init_displayhook()
554 504 self.init_magics()
555 505 self.init_alias()
556 506 self.init_logstart()
557 507 self.init_pdb()
558 508 self.init_extension_manager()
559 509 self.init_payload()
560 510 self.init_deprecation_warnings()
561 511 self.hooks.late_startup_hook()
562 512 self.events.trigger('shell_initialized', self)
563 513 atexit.register(self.atexit_operations)
564 514
565 515 def get_ipython(self):
566 516 """Return the currently running IPython instance."""
567 517 return self
568 518
569 519 #-------------------------------------------------------------------------
570 520 # Trait changed handlers
571 521 #-------------------------------------------------------------------------
572 522
573 523 def _ipython_dir_changed(self, name, new):
574 524 ensure_dir_exists(new)
575 525
576 526 def set_autoindent(self,value=None):
577 527 """Set the autoindent flag, checking for readline support.
578 528
579 529 If called with no arguments, it acts as a toggle."""
580 530
581 531 if value != 0 and not self.has_readline:
582 532 if os.name == 'posix':
583 533 warn("The auto-indent feature requires the readline library")
584 534 self.autoindent = 0
585 535 return
586 536 if value is None:
587 537 self.autoindent = not self.autoindent
588 538 else:
589 539 self.autoindent = value
590 540
591 541 #-------------------------------------------------------------------------
592 542 # init_* methods called by __init__
593 543 #-------------------------------------------------------------------------
594 544
595 545 def init_ipython_dir(self, ipython_dir):
596 546 if ipython_dir is not None:
597 547 self.ipython_dir = ipython_dir
598 548 return
599 549
600 550 self.ipython_dir = get_ipython_dir()
601 551
602 552 def init_profile_dir(self, profile_dir):
603 553 if profile_dir is not None:
604 554 self.profile_dir = profile_dir
605 555 return
606 556 self.profile_dir =\
607 557 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
608 558
609 559 def init_instance_attrs(self):
610 560 self.more = False
611 561
612 562 # command compiler
613 563 self.compile = CachingCompiler()
614 564
615 565 # Make an empty namespace, which extension writers can rely on both
616 566 # existing and NEVER being used by ipython itself. This gives them a
617 567 # convenient location for storing additional information and state
618 568 # their extensions may require, without fear of collisions with other
619 569 # ipython names that may develop later.
620 570 self.meta = Struct()
621 571
622 572 # Temporary files used for various purposes. Deleted at exit.
623 573 self.tempfiles = []
624 574 self.tempdirs = []
625 575
626 576 # Keep track of readline usage (later set by init_readline)
627 577 self.has_readline = False
628 578
629 579 # keep track of where we started running (mainly for crash post-mortem)
630 580 # This is not being used anywhere currently.
631 581 self.starting_dir = py3compat.getcwd()
632 582
633 583 # Indentation management
634 584 self.indent_current_nsp = 0
635 585
636 586 # Dict to track post-execution functions that have been registered
637 587 self._post_execute = {}
638 588
639 589 def init_environment(self):
640 590 """Any changes we need to make to the user's environment."""
641 591 pass
642 592
643 593 def init_encoding(self):
644 594 # Get system encoding at startup time. Certain terminals (like Emacs
645 595 # under Win32 have it set to None, and we need to have a known valid
646 596 # encoding to use in the raw_input() method
647 597 try:
648 598 self.stdin_encoding = sys.stdin.encoding or 'ascii'
649 599 except AttributeError:
650 600 self.stdin_encoding = 'ascii'
651 601
652 602 def init_syntax_highlighting(self):
653 603 # Python source parser/formatter for syntax highlighting
654 604 pyformat = PyColorize.Parser().format
655 605 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
656 606
657 607 def init_pushd_popd_magic(self):
658 608 # for pushd/popd management
659 609 self.home_dir = get_home_dir()
660 610
661 611 self.dir_stack = []
662 612
663 613 def init_logger(self):
664 614 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
665 615 logmode='rotate')
666 616
667 617 def init_logstart(self):
668 618 """Initialize logging in case it was requested at the command line.
669 619 """
670 620 if self.logappend:
671 621 self.magic('logstart %s append' % self.logappend)
672 622 elif self.logfile:
673 623 self.magic('logstart %s' % self.logfile)
674 624 elif self.logstart:
675 625 self.magic('logstart')
676 626
677 627 def init_deprecation_warnings(self):
678 628 """
679 629 register default filter for deprecation warning.
680 630
681 631 This will allow deprecation warning of function used interactively to show
682 632 warning to users, and still hide deprecation warning from libraries import.
683 633 """
684 634 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
685 635
686 636 def init_builtins(self):
687 637 # A single, static flag that we set to True. Its presence indicates
688 638 # that an IPython shell has been created, and we make no attempts at
689 639 # removing on exit or representing the existence of more than one
690 640 # IPython at a time.
691 641 builtin_mod.__dict__['__IPYTHON__'] = True
692 642
693 643 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
694 644 # manage on enter/exit, but with all our shells it's virtually
695 645 # impossible to get all the cases right. We're leaving the name in for
696 646 # those who adapted their codes to check for this flag, but will
697 647 # eventually remove it after a few more releases.
698 648 builtin_mod.__dict__['__IPYTHON__active'] = \
699 649 'Deprecated, check for __IPYTHON__'
700 650
701 651 self.builtin_trap = BuiltinTrap(shell=self)
702 652
703 653 def init_inspector(self):
704 654 # Object inspector
705 655 self.inspector = oinspect.Inspector(oinspect.InspectColors,
706 656 PyColorize.ANSICodeColors,
707 657 'NoColor',
708 658 self.object_info_string_level)
709 659
710 660 def init_io(self):
711 661 # This will just use sys.stdout and sys.stderr. If you want to
712 662 # override sys.stdout and sys.stderr themselves, you need to do that
713 663 # *before* instantiating this class, because io holds onto
714 664 # references to the underlying streams.
715 665 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
716 666 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
717 667 else:
718 668 io.stdout = io.IOStream(sys.stdout)
719 669 io.stderr = io.IOStream(sys.stderr)
720 670
721 671 def init_prompts(self):
722 672 self.prompt_manager = PromptManager(shell=self, parent=self)
723 673 self.configurables.append(self.prompt_manager)
724 674 # Set system prompts, so that scripts can decide if they are running
725 675 # interactively.
726 676 sys.ps1 = 'In : '
727 677 sys.ps2 = '...: '
728 678 sys.ps3 = 'Out: '
729 679
730 680 def init_display_formatter(self):
731 681 self.display_formatter = DisplayFormatter(parent=self)
732 682 self.configurables.append(self.display_formatter)
733 683
734 684 def init_display_pub(self):
735 685 self.display_pub = self.display_pub_class(parent=self)
736 686 self.configurables.append(self.display_pub)
737 687
738 688 def init_data_pub(self):
739 689 if not self.data_pub_class:
740 690 self.data_pub = None
741 691 return
742 692 self.data_pub = self.data_pub_class(parent=self)
743 693 self.configurables.append(self.data_pub)
744 694
745 695 def init_displayhook(self):
746 696 # Initialize displayhook, set in/out prompts and printing system
747 697 self.displayhook = self.displayhook_class(
748 698 parent=self,
749 699 shell=self,
750 700 cache_size=self.cache_size,
751 701 )
752 702 self.configurables.append(self.displayhook)
753 703 # This is a context manager that installs/revmoes the displayhook at
754 704 # the appropriate time.
755 705 self.display_trap = DisplayTrap(hook=self.displayhook)
756 706
757 707 def init_virtualenv(self):
758 708 """Add a virtualenv to sys.path so the user can import modules from it.
759 709 This isn't perfect: it doesn't use the Python interpreter with which the
760 710 virtualenv was built, and it ignores the --no-site-packages option. A
761 711 warning will appear suggesting the user installs IPython in the
762 712 virtualenv, but for many cases, it probably works well enough.
763 713
764 714 Adapted from code snippets online.
765 715
766 716 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
767 717 """
768 718 if 'VIRTUAL_ENV' not in os.environ:
769 719 # Not in a virtualenv
770 720 return
771 721
772 722 # venv detection:
773 723 # stdlib venv may symlink sys.executable, so we can't use realpath.
774 724 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
775 725 # So we just check every item in the symlink tree (generally <= 3)
776 726 p = os.path.normcase(sys.executable)
777 727 paths = [p]
778 728 while os.path.islink(p):
779 729 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
780 730 paths.append(p)
781 731 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
782 732 if any(p.startswith(p_venv) for p in paths):
783 733 # Running properly in the virtualenv, don't need to do anything
784 734 return
785 735
786 736 warn("Attempting to work in a virtualenv. If you encounter problems, please "
787 737 "install IPython inside the virtualenv.")
788 738 if sys.platform == "win32":
789 739 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
790 740 else:
791 741 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
792 742 'python%d.%d' % sys.version_info[:2], 'site-packages')
793 743
794 744 import site
795 745 sys.path.insert(0, virtual_env)
796 746 site.addsitedir(virtual_env)
797 747
798 748 #-------------------------------------------------------------------------
799 749 # Things related to injections into the sys module
800 750 #-------------------------------------------------------------------------
801 751
802 752 def save_sys_module_state(self):
803 753 """Save the state of hooks in the sys module.
804 754
805 755 This has to be called after self.user_module is created.
806 756 """
807 757 self._orig_sys_module_state = {'stdin': sys.stdin,
808 758 'stdout': sys.stdout,
809 759 'stderr': sys.stderr,
810 760 'excepthook': sys.excepthook}
811 761 self._orig_sys_modules_main_name = self.user_module.__name__
812 762 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
813 763
814 764 def restore_sys_module_state(self):
815 765 """Restore the state of the sys module."""
816 766 try:
817 767 for k, v in iteritems(self._orig_sys_module_state):
818 768 setattr(sys, k, v)
819 769 except AttributeError:
820 770 pass
821 771 # Reset what what done in self.init_sys_modules
822 772 if self._orig_sys_modules_main_mod is not None:
823 773 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
824 774
825 775 #-------------------------------------------------------------------------
826 776 # Things related to the banner
827 777 #-------------------------------------------------------------------------
828 778
829 779 @property
830 780 def banner(self):
831 781 banner = self.banner1
832 782 if self.profile and self.profile != 'default':
833 783 banner += '\nIPython profile: %s\n' % self.profile
834 784 if self.banner2:
835 785 banner += '\n' + self.banner2
836 786 return banner
837 787
838 788 def show_banner(self, banner=None):
839 789 if banner is None:
840 790 banner = self.banner
841 791 self.write(banner)
842 792
843 793 #-------------------------------------------------------------------------
844 794 # Things related to hooks
845 795 #-------------------------------------------------------------------------
846 796
847 797 def init_hooks(self):
848 798 # hooks holds pointers used for user-side customizations
849 799 self.hooks = Struct()
850 800
851 801 self.strdispatchers = {}
852 802
853 803 # Set all default hooks, defined in the IPython.hooks module.
854 804 hooks = IPython.core.hooks
855 805 for hook_name in hooks.__all__:
856 806 # default hooks have priority 100, i.e. low; user hooks should have
857 807 # 0-100 priority
858 808 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
859 809
860 810 if self.display_page:
861 811 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
862 812
863 813 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
864 814 _warn_deprecated=True):
865 815 """set_hook(name,hook) -> sets an internal IPython hook.
866 816
867 817 IPython exposes some of its internal API as user-modifiable hooks. By
868 818 adding your function to one of these hooks, you can modify IPython's
869 819 behavior to call at runtime your own routines."""
870 820
871 821 # At some point in the future, this should validate the hook before it
872 822 # accepts it. Probably at least check that the hook takes the number
873 823 # of args it's supposed to.
874 824
875 825 f = types.MethodType(hook,self)
876 826
877 827 # check if the hook is for strdispatcher first
878 828 if str_key is not None:
879 829 sdp = self.strdispatchers.get(name, StrDispatch())
880 830 sdp.add_s(str_key, f, priority )
881 831 self.strdispatchers[name] = sdp
882 832 return
883 833 if re_key is not None:
884 834 sdp = self.strdispatchers.get(name, StrDispatch())
885 835 sdp.add_re(re.compile(re_key), f, priority )
886 836 self.strdispatchers[name] = sdp
887 837 return
888 838
889 839 dp = getattr(self.hooks, name, None)
890 840 if name not in IPython.core.hooks.__all__:
891 841 print("Warning! Hook '%s' is not one of %s" % \
892 842 (name, IPython.core.hooks.__all__ ))
893 843
894 844 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
895 845 alternative = IPython.core.hooks.deprecated[name]
896 846 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
897 847
898 848 if not dp:
899 849 dp = IPython.core.hooks.CommandChainDispatcher()
900 850
901 851 try:
902 852 dp.add(f,priority)
903 853 except AttributeError:
904 854 # it was not commandchain, plain old func - replace
905 855 dp = f
906 856
907 857 setattr(self.hooks,name, dp)
908 858
909 859 #-------------------------------------------------------------------------
910 860 # Things related to events
911 861 #-------------------------------------------------------------------------
912 862
913 863 def init_events(self):
914 864 self.events = EventManager(self, available_events)
915 865
916 866 self.events.register("pre_execute", self._clear_warning_registry)
917 867
918 868 def register_post_execute(self, func):
919 869 """DEPRECATED: Use ip.events.register('post_run_cell', func)
920 870
921 871 Register a function for calling after code execution.
922 872 """
923 873 warn("ip.register_post_execute is deprecated, use "
924 874 "ip.events.register('post_run_cell', func) instead.")
925 875 self.events.register('post_run_cell', func)
926 876
927 877 def _clear_warning_registry(self):
928 878 # clear the warning registry, so that different code blocks with
929 879 # overlapping line number ranges don't cause spurious suppression of
930 880 # warnings (see gh-6611 for details)
931 881 if "__warningregistry__" in self.user_global_ns:
932 882 del self.user_global_ns["__warningregistry__"]
933 883
934 884 #-------------------------------------------------------------------------
935 885 # Things related to the "main" module
936 886 #-------------------------------------------------------------------------
937 887
938 888 def new_main_mod(self, filename, modname):
939 889 """Return a new 'main' module object for user code execution.
940 890
941 891 ``filename`` should be the path of the script which will be run in the
942 892 module. Requests with the same filename will get the same module, with
943 893 its namespace cleared.
944 894
945 895 ``modname`` should be the module name - normally either '__main__' or
946 896 the basename of the file without the extension.
947 897
948 898 When scripts are executed via %run, we must keep a reference to their
949 899 __main__ module around so that Python doesn't
950 900 clear it, rendering references to module globals useless.
951 901
952 902 This method keeps said reference in a private dict, keyed by the
953 903 absolute path of the script. This way, for multiple executions of the
954 904 same script we only keep one copy of the namespace (the last one),
955 905 thus preventing memory leaks from old references while allowing the
956 906 objects from the last execution to be accessible.
957 907 """
958 908 filename = os.path.abspath(filename)
959 909 try:
960 910 main_mod = self._main_mod_cache[filename]
961 911 except KeyError:
962 912 main_mod = self._main_mod_cache[filename] = types.ModuleType(
963 913 py3compat.cast_bytes_py2(modname),
964 914 doc="Module created for script run in IPython")
965 915 else:
966 916 main_mod.__dict__.clear()
967 917 main_mod.__name__ = modname
968 918
969 919 main_mod.__file__ = filename
970 920 # It seems pydoc (and perhaps others) needs any module instance to
971 921 # implement a __nonzero__ method
972 922 main_mod.__nonzero__ = lambda : True
973 923
974 924 return main_mod
975 925
976 926 def clear_main_mod_cache(self):
977 927 """Clear the cache of main modules.
978 928
979 929 Mainly for use by utilities like %reset.
980 930
981 931 Examples
982 932 --------
983 933
984 934 In [15]: import IPython
985 935
986 936 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
987 937
988 938 In [17]: len(_ip._main_mod_cache) > 0
989 939 Out[17]: True
990 940
991 941 In [18]: _ip.clear_main_mod_cache()
992 942
993 943 In [19]: len(_ip._main_mod_cache) == 0
994 944 Out[19]: True
995 945 """
996 946 self._main_mod_cache.clear()
997 947
998 948 #-------------------------------------------------------------------------
999 949 # Things related to debugging
1000 950 #-------------------------------------------------------------------------
1001 951
1002 952 def init_pdb(self):
1003 953 # Set calling of pdb on exceptions
1004 954 # self.call_pdb is a property
1005 955 self.call_pdb = self.pdb
1006 956
1007 957 def _get_call_pdb(self):
1008 958 return self._call_pdb
1009 959
1010 960 def _set_call_pdb(self,val):
1011 961
1012 962 if val not in (0,1,False,True):
1013 963 raise ValueError('new call_pdb value must be boolean')
1014 964
1015 965 # store value in instance
1016 966 self._call_pdb = val
1017 967
1018 968 # notify the actual exception handlers
1019 969 self.InteractiveTB.call_pdb = val
1020 970
1021 971 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1022 972 'Control auto-activation of pdb at exceptions')
1023 973
1024 974 def debugger(self,force=False):
1025 975 """Call the pydb/pdb debugger.
1026 976
1027 977 Keywords:
1028 978
1029 979 - force(False): by default, this routine checks the instance call_pdb
1030 980 flag and does not actually invoke the debugger if the flag is false.
1031 981 The 'force' option forces the debugger to activate even if the flag
1032 982 is false.
1033 983 """
1034 984
1035 985 if not (force or self.call_pdb):
1036 986 return
1037 987
1038 988 if not hasattr(sys,'last_traceback'):
1039 989 error('No traceback has been produced, nothing to debug.')
1040 990 return
1041 991
1042 992 # use pydb if available
1043 993 if debugger.has_pydb:
1044 994 from pydb import pm
1045 995 else:
1046 996 # fallback to our internal debugger
1047 997 pm = lambda : self.InteractiveTB.debugger(force=True)
1048 998
1049 999 with self.readline_no_record:
1050 1000 pm()
1051 1001
1052 1002 #-------------------------------------------------------------------------
1053 1003 # Things related to IPython's various namespaces
1054 1004 #-------------------------------------------------------------------------
1055 1005 default_user_namespaces = True
1056 1006
1057 1007 def init_create_namespaces(self, user_module=None, user_ns=None):
1058 1008 # Create the namespace where the user will operate. user_ns is
1059 1009 # normally the only one used, and it is passed to the exec calls as
1060 1010 # the locals argument. But we do carry a user_global_ns namespace
1061 1011 # given as the exec 'globals' argument, This is useful in embedding
1062 1012 # situations where the ipython shell opens in a context where the
1063 1013 # distinction between locals and globals is meaningful. For
1064 1014 # non-embedded contexts, it is just the same object as the user_ns dict.
1065 1015
1066 1016 # FIXME. For some strange reason, __builtins__ is showing up at user
1067 1017 # level as a dict instead of a module. This is a manual fix, but I
1068 1018 # should really track down where the problem is coming from. Alex
1069 1019 # Schmolck reported this problem first.
1070 1020
1071 1021 # A useful post by Alex Martelli on this topic:
1072 1022 # Re: inconsistent value from __builtins__
1073 1023 # Von: Alex Martelli <aleaxit@yahoo.com>
1074 1024 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1075 1025 # Gruppen: comp.lang.python
1076 1026
1077 1027 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1078 1028 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1079 1029 # > <type 'dict'>
1080 1030 # > >>> print type(__builtins__)
1081 1031 # > <type 'module'>
1082 1032 # > Is this difference in return value intentional?
1083 1033
1084 1034 # Well, it's documented that '__builtins__' can be either a dictionary
1085 1035 # or a module, and it's been that way for a long time. Whether it's
1086 1036 # intentional (or sensible), I don't know. In any case, the idea is
1087 1037 # that if you need to access the built-in namespace directly, you
1088 1038 # should start with "import __builtin__" (note, no 's') which will
1089 1039 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1090 1040
1091 1041 # These routines return a properly built module and dict as needed by
1092 1042 # the rest of the code, and can also be used by extension writers to
1093 1043 # generate properly initialized namespaces.
1094 1044 if (user_ns is not None) or (user_module is not None):
1095 1045 self.default_user_namespaces = False
1096 1046 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1097 1047
1098 1048 # A record of hidden variables we have added to the user namespace, so
1099 1049 # we can list later only variables defined in actual interactive use.
1100 1050 self.user_ns_hidden = {}
1101 1051
1102 1052 # Now that FakeModule produces a real module, we've run into a nasty
1103 1053 # problem: after script execution (via %run), the module where the user
1104 1054 # code ran is deleted. Now that this object is a true module (needed
1105 1055 # so docetst and other tools work correctly), the Python module
1106 1056 # teardown mechanism runs over it, and sets to None every variable
1107 1057 # present in that module. Top-level references to objects from the
1108 1058 # script survive, because the user_ns is updated with them. However,
1109 1059 # calling functions defined in the script that use other things from
1110 1060 # the script will fail, because the function's closure had references
1111 1061 # to the original objects, which are now all None. So we must protect
1112 1062 # these modules from deletion by keeping a cache.
1113 1063 #
1114 1064 # To avoid keeping stale modules around (we only need the one from the
1115 1065 # last run), we use a dict keyed with the full path to the script, so
1116 1066 # only the last version of the module is held in the cache. Note,
1117 1067 # however, that we must cache the module *namespace contents* (their
1118 1068 # __dict__). Because if we try to cache the actual modules, old ones
1119 1069 # (uncached) could be destroyed while still holding references (such as
1120 1070 # those held by GUI objects that tend to be long-lived)>
1121 1071 #
1122 1072 # The %reset command will flush this cache. See the cache_main_mod()
1123 1073 # and clear_main_mod_cache() methods for details on use.
1124 1074
1125 1075 # This is the cache used for 'main' namespaces
1126 1076 self._main_mod_cache = {}
1127 1077
1128 1078 # A table holding all the namespaces IPython deals with, so that
1129 1079 # introspection facilities can search easily.
1130 1080 self.ns_table = {'user_global':self.user_module.__dict__,
1131 1081 'user_local':self.user_ns,
1132 1082 'builtin':builtin_mod.__dict__
1133 1083 }
1134 1084
1135 1085 @property
1136 1086 def user_global_ns(self):
1137 1087 return self.user_module.__dict__
1138 1088
1139 1089 def prepare_user_module(self, user_module=None, user_ns=None):
1140 1090 """Prepare the module and namespace in which user code will be run.
1141 1091
1142 1092 When IPython is started normally, both parameters are None: a new module
1143 1093 is created automatically, and its __dict__ used as the namespace.
1144 1094
1145 1095 If only user_module is provided, its __dict__ is used as the namespace.
1146 1096 If only user_ns is provided, a dummy module is created, and user_ns
1147 1097 becomes the global namespace. If both are provided (as they may be
1148 1098 when embedding), user_ns is the local namespace, and user_module
1149 1099 provides the global namespace.
1150 1100
1151 1101 Parameters
1152 1102 ----------
1153 1103 user_module : module, optional
1154 1104 The current user module in which IPython is being run. If None,
1155 1105 a clean module will be created.
1156 1106 user_ns : dict, optional
1157 1107 A namespace in which to run interactive commands.
1158 1108
1159 1109 Returns
1160 1110 -------
1161 1111 A tuple of user_module and user_ns, each properly initialised.
1162 1112 """
1163 1113 if user_module is None and user_ns is not None:
1164 1114 user_ns.setdefault("__name__", "__main__")
1165 1115 user_module = DummyMod()
1166 1116 user_module.__dict__ = user_ns
1167 1117
1168 1118 if user_module is None:
1169 1119 user_module = types.ModuleType("__main__",
1170 1120 doc="Automatically created module for IPython interactive environment")
1171 1121
1172 1122 # We must ensure that __builtin__ (without the final 's') is always
1173 1123 # available and pointing to the __builtin__ *module*. For more details:
1174 1124 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1175 1125 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1176 1126 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1177 1127
1178 1128 if user_ns is None:
1179 1129 user_ns = user_module.__dict__
1180 1130
1181 1131 return user_module, user_ns
1182 1132
1183 1133 def init_sys_modules(self):
1184 1134 # We need to insert into sys.modules something that looks like a
1185 1135 # module but which accesses the IPython namespace, for shelve and
1186 1136 # pickle to work interactively. Normally they rely on getting
1187 1137 # everything out of __main__, but for embedding purposes each IPython
1188 1138 # instance has its own private namespace, so we can't go shoving
1189 1139 # everything into __main__.
1190 1140
1191 1141 # note, however, that we should only do this for non-embedded
1192 1142 # ipythons, which really mimic the __main__.__dict__ with their own
1193 1143 # namespace. Embedded instances, on the other hand, should not do
1194 1144 # this because they need to manage the user local/global namespaces
1195 1145 # only, but they live within a 'normal' __main__ (meaning, they
1196 1146 # shouldn't overtake the execution environment of the script they're
1197 1147 # embedded in).
1198 1148
1199 1149 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1200 1150 main_name = self.user_module.__name__
1201 1151 sys.modules[main_name] = self.user_module
1202 1152
1203 1153 def init_user_ns(self):
1204 1154 """Initialize all user-visible namespaces to their minimum defaults.
1205 1155
1206 1156 Certain history lists are also initialized here, as they effectively
1207 1157 act as user namespaces.
1208 1158
1209 1159 Notes
1210 1160 -----
1211 1161 All data structures here are only filled in, they are NOT reset by this
1212 1162 method. If they were not empty before, data will simply be added to
1213 1163 therm.
1214 1164 """
1215 1165 # This function works in two parts: first we put a few things in
1216 1166 # user_ns, and we sync that contents into user_ns_hidden so that these
1217 1167 # initial variables aren't shown by %who. After the sync, we add the
1218 1168 # rest of what we *do* want the user to see with %who even on a new
1219 1169 # session (probably nothing, so theye really only see their own stuff)
1220 1170
1221 1171 # The user dict must *always* have a __builtin__ reference to the
1222 1172 # Python standard __builtin__ namespace, which must be imported.
1223 1173 # This is so that certain operations in prompt evaluation can be
1224 1174 # reliably executed with builtins. Note that we can NOT use
1225 1175 # __builtins__ (note the 's'), because that can either be a dict or a
1226 1176 # module, and can even mutate at runtime, depending on the context
1227 1177 # (Python makes no guarantees on it). In contrast, __builtin__ is
1228 1178 # always a module object, though it must be explicitly imported.
1229 1179
1230 1180 # For more details:
1231 1181 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1232 1182 ns = dict()
1233 1183
1234 1184 # make global variables for user access to the histories
1235 1185 ns['_ih'] = self.history_manager.input_hist_parsed
1236 1186 ns['_oh'] = self.history_manager.output_hist
1237 1187 ns['_dh'] = self.history_manager.dir_hist
1238 1188
1239 1189 ns['_sh'] = shadowns
1240 1190
1241 1191 # user aliases to input and output histories. These shouldn't show up
1242 1192 # in %who, as they can have very large reprs.
1243 1193 ns['In'] = self.history_manager.input_hist_parsed
1244 1194 ns['Out'] = self.history_manager.output_hist
1245 1195
1246 1196 # Store myself as the public api!!!
1247 1197 ns['get_ipython'] = self.get_ipython
1248 1198
1249 1199 ns['exit'] = self.exiter
1250 1200 ns['quit'] = self.exiter
1251 1201
1252 1202 # Sync what we've added so far to user_ns_hidden so these aren't seen
1253 1203 # by %who
1254 1204 self.user_ns_hidden.update(ns)
1255 1205
1256 1206 # Anything put into ns now would show up in %who. Think twice before
1257 1207 # putting anything here, as we really want %who to show the user their
1258 1208 # stuff, not our variables.
1259 1209
1260 1210 # Finally, update the real user's namespace
1261 1211 self.user_ns.update(ns)
1262 1212
1263 1213 @property
1264 1214 def all_ns_refs(self):
1265 1215 """Get a list of references to all the namespace dictionaries in which
1266 1216 IPython might store a user-created object.
1267 1217
1268 1218 Note that this does not include the displayhook, which also caches
1269 1219 objects from the output."""
1270 1220 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1271 1221 [m.__dict__ for m in self._main_mod_cache.values()]
1272 1222
1273 1223 def reset(self, new_session=True):
1274 1224 """Clear all internal namespaces, and attempt to release references to
1275 1225 user objects.
1276 1226
1277 1227 If new_session is True, a new history session will be opened.
1278 1228 """
1279 1229 # Clear histories
1280 1230 self.history_manager.reset(new_session)
1281 1231 # Reset counter used to index all histories
1282 1232 if new_session:
1283 1233 self.execution_count = 1
1284 1234
1285 1235 # Flush cached output items
1286 1236 if self.displayhook.do_full_cache:
1287 1237 self.displayhook.flush()
1288 1238
1289 1239 # The main execution namespaces must be cleared very carefully,
1290 1240 # skipping the deletion of the builtin-related keys, because doing so
1291 1241 # would cause errors in many object's __del__ methods.
1292 1242 if self.user_ns is not self.user_global_ns:
1293 1243 self.user_ns.clear()
1294 1244 ns = self.user_global_ns
1295 1245 drop_keys = set(ns.keys())
1296 1246 drop_keys.discard('__builtin__')
1297 1247 drop_keys.discard('__builtins__')
1298 1248 drop_keys.discard('__name__')
1299 1249 for k in drop_keys:
1300 1250 del ns[k]
1301 1251
1302 1252 self.user_ns_hidden.clear()
1303 1253
1304 1254 # Restore the user namespaces to minimal usability
1305 1255 self.init_user_ns()
1306 1256
1307 1257 # Restore the default and user aliases
1308 1258 self.alias_manager.clear_aliases()
1309 1259 self.alias_manager.init_aliases()
1310 1260
1311 1261 # Flush the private list of module references kept for script
1312 1262 # execution protection
1313 1263 self.clear_main_mod_cache()
1314 1264
1315 1265 def del_var(self, varname, by_name=False):
1316 1266 """Delete a variable from the various namespaces, so that, as
1317 1267 far as possible, we're not keeping any hidden references to it.
1318 1268
1319 1269 Parameters
1320 1270 ----------
1321 1271 varname : str
1322 1272 The name of the variable to delete.
1323 1273 by_name : bool
1324 1274 If True, delete variables with the given name in each
1325 1275 namespace. If False (default), find the variable in the user
1326 1276 namespace, and delete references to it.
1327 1277 """
1328 1278 if varname in ('__builtin__', '__builtins__'):
1329 1279 raise ValueError("Refusing to delete %s" % varname)
1330 1280
1331 1281 ns_refs = self.all_ns_refs
1332 1282
1333 1283 if by_name: # Delete by name
1334 1284 for ns in ns_refs:
1335 1285 try:
1336 1286 del ns[varname]
1337 1287 except KeyError:
1338 1288 pass
1339 1289 else: # Delete by object
1340 1290 try:
1341 1291 obj = self.user_ns[varname]
1342 1292 except KeyError:
1343 1293 raise NameError("name '%s' is not defined" % varname)
1344 1294 # Also check in output history
1345 1295 ns_refs.append(self.history_manager.output_hist)
1346 1296 for ns in ns_refs:
1347 1297 to_delete = [n for n, o in iteritems(ns) if o is obj]
1348 1298 for name in to_delete:
1349 1299 del ns[name]
1350 1300
1351 1301 # displayhook keeps extra references, but not in a dictionary
1352 1302 for name in ('_', '__', '___'):
1353 1303 if getattr(self.displayhook, name) is obj:
1354 1304 setattr(self.displayhook, name, None)
1355 1305
1356 1306 def reset_selective(self, regex=None):
1357 1307 """Clear selective variables from internal namespaces based on a
1358 1308 specified regular expression.
1359 1309
1360 1310 Parameters
1361 1311 ----------
1362 1312 regex : string or compiled pattern, optional
1363 1313 A regular expression pattern that will be used in searching
1364 1314 variable names in the users namespaces.
1365 1315 """
1366 1316 if regex is not None:
1367 1317 try:
1368 1318 m = re.compile(regex)
1369 1319 except TypeError:
1370 1320 raise TypeError('regex must be a string or compiled pattern')
1371 1321 # Search for keys in each namespace that match the given regex
1372 1322 # If a match is found, delete the key/value pair.
1373 1323 for ns in self.all_ns_refs:
1374 1324 for var in ns:
1375 1325 if m.search(var):
1376 1326 del ns[var]
1377 1327
1378 1328 def push(self, variables, interactive=True):
1379 1329 """Inject a group of variables into the IPython user namespace.
1380 1330
1381 1331 Parameters
1382 1332 ----------
1383 1333 variables : dict, str or list/tuple of str
1384 1334 The variables to inject into the user's namespace. If a dict, a
1385 1335 simple update is done. If a str, the string is assumed to have
1386 1336 variable names separated by spaces. A list/tuple of str can also
1387 1337 be used to give the variable names. If just the variable names are
1388 1338 give (list/tuple/str) then the variable values looked up in the
1389 1339 callers frame.
1390 1340 interactive : bool
1391 1341 If True (default), the variables will be listed with the ``who``
1392 1342 magic.
1393 1343 """
1394 1344 vdict = None
1395 1345
1396 1346 # We need a dict of name/value pairs to do namespace updates.
1397 1347 if isinstance(variables, dict):
1398 1348 vdict = variables
1399 1349 elif isinstance(variables, string_types+(list, tuple)):
1400 1350 if isinstance(variables, string_types):
1401 1351 vlist = variables.split()
1402 1352 else:
1403 1353 vlist = variables
1404 1354 vdict = {}
1405 1355 cf = sys._getframe(1)
1406 1356 for name in vlist:
1407 1357 try:
1408 1358 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1409 1359 except:
1410 1360 print('Could not get variable %s from %s' %
1411 1361 (name,cf.f_code.co_name))
1412 1362 else:
1413 1363 raise ValueError('variables must be a dict/str/list/tuple')
1414 1364
1415 1365 # Propagate variables to user namespace
1416 1366 self.user_ns.update(vdict)
1417 1367
1418 1368 # And configure interactive visibility
1419 1369 user_ns_hidden = self.user_ns_hidden
1420 1370 if interactive:
1421 1371 for name in vdict:
1422 1372 user_ns_hidden.pop(name, None)
1423 1373 else:
1424 1374 user_ns_hidden.update(vdict)
1425 1375
1426 1376 def drop_by_id(self, variables):
1427 1377 """Remove a dict of variables from the user namespace, if they are the
1428 1378 same as the values in the dictionary.
1429 1379
1430 1380 This is intended for use by extensions: variables that they've added can
1431 1381 be taken back out if they are unloaded, without removing any that the
1432 1382 user has overwritten.
1433 1383
1434 1384 Parameters
1435 1385 ----------
1436 1386 variables : dict
1437 1387 A dictionary mapping object names (as strings) to the objects.
1438 1388 """
1439 1389 for name, obj in iteritems(variables):
1440 1390 if name in self.user_ns and self.user_ns[name] is obj:
1441 1391 del self.user_ns[name]
1442 1392 self.user_ns_hidden.pop(name, None)
1443 1393
1444 1394 #-------------------------------------------------------------------------
1445 1395 # Things related to object introspection
1446 1396 #-------------------------------------------------------------------------
1447 1397
1448 1398 def _ofind(self, oname, namespaces=None):
1449 1399 """Find an object in the available namespaces.
1450 1400
1451 1401 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1452 1402
1453 1403 Has special code to detect magic functions.
1454 1404 """
1455 1405 oname = oname.strip()
1456 1406 #print '1- oname: <%r>' % oname # dbg
1457 1407 if not oname.startswith(ESC_MAGIC) and \
1458 1408 not oname.startswith(ESC_MAGIC2) and \
1459 1409 not py3compat.isidentifier(oname, dotted=True):
1460 1410 return dict(found=False)
1461 1411
1462 1412 alias_ns = None
1463 1413 if namespaces is None:
1464 1414 # Namespaces to search in:
1465 1415 # Put them in a list. The order is important so that we
1466 1416 # find things in the same order that Python finds them.
1467 1417 namespaces = [ ('Interactive', self.user_ns),
1468 1418 ('Interactive (global)', self.user_global_ns),
1469 1419 ('Python builtin', builtin_mod.__dict__),
1470 1420 ]
1471 1421
1472 1422 # initialize results to 'null'
1473 1423 found = False; obj = None; ospace = None; ds = None
1474 1424 ismagic = False; isalias = False; parent = None
1475 1425
1476 1426 # We need to special-case 'print', which as of python2.6 registers as a
1477 1427 # function but should only be treated as one if print_function was
1478 1428 # loaded with a future import. In this case, just bail.
1479 1429 if (oname == 'print' and not py3compat.PY3 and not \
1480 1430 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1481 1431 return {'found':found, 'obj':obj, 'namespace':ospace,
1482 1432 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1483 1433
1484 1434 # Look for the given name by splitting it in parts. If the head is
1485 1435 # found, then we look for all the remaining parts as members, and only
1486 1436 # declare success if we can find them all.
1487 1437 oname_parts = oname.split('.')
1488 1438 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1489 1439 for nsname,ns in namespaces:
1490 1440 try:
1491 1441 obj = ns[oname_head]
1492 1442 except KeyError:
1493 1443 continue
1494 1444 else:
1495 1445 #print 'oname_rest:', oname_rest # dbg
1496 1446 for idx, part in enumerate(oname_rest):
1497 1447 try:
1498 1448 parent = obj
1499 1449 # The last part is looked up in a special way to avoid
1500 1450 # descriptor invocation as it may raise or have side
1501 1451 # effects.
1502 1452 if idx == len(oname_rest) - 1:
1503 1453 obj = self._getattr_property(obj, part)
1504 1454 else:
1505 1455 obj = getattr(obj, part)
1506 1456 except:
1507 1457 # Blanket except b/c some badly implemented objects
1508 1458 # allow __getattr__ to raise exceptions other than
1509 1459 # AttributeError, which then crashes IPython.
1510 1460 break
1511 1461 else:
1512 1462 # If we finish the for loop (no break), we got all members
1513 1463 found = True
1514 1464 ospace = nsname
1515 1465 break # namespace loop
1516 1466
1517 1467 # Try to see if it's magic
1518 1468 if not found:
1519 1469 obj = None
1520 1470 if oname.startswith(ESC_MAGIC2):
1521 1471 oname = oname.lstrip(ESC_MAGIC2)
1522 1472 obj = self.find_cell_magic(oname)
1523 1473 elif oname.startswith(ESC_MAGIC):
1524 1474 oname = oname.lstrip(ESC_MAGIC)
1525 1475 obj = self.find_line_magic(oname)
1526 1476 else:
1527 1477 # search without prefix, so run? will find %run?
1528 1478 obj = self.find_line_magic(oname)
1529 1479 if obj is None:
1530 1480 obj = self.find_cell_magic(oname)
1531 1481 if obj is not None:
1532 1482 found = True
1533 1483 ospace = 'IPython internal'
1534 1484 ismagic = True
1535 1485 isalias = isinstance(obj, Alias)
1536 1486
1537 1487 # Last try: special-case some literals like '', [], {}, etc:
1538 1488 if not found and oname_head in ["''",'""','[]','{}','()']:
1539 1489 obj = eval(oname_head)
1540 1490 found = True
1541 1491 ospace = 'Interactive'
1542 1492
1543 1493 return {'found':found, 'obj':obj, 'namespace':ospace,
1544 1494 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1545 1495
1546 1496 @staticmethod
1547 1497 def _getattr_property(obj, attrname):
1548 1498 """Property-aware getattr to use in object finding.
1549 1499
1550 1500 If attrname represents a property, return it unevaluated (in case it has
1551 1501 side effects or raises an error.
1552 1502
1553 1503 """
1554 1504 if not isinstance(obj, type):
1555 1505 try:
1556 1506 # `getattr(type(obj), attrname)` is not guaranteed to return
1557 1507 # `obj`, but does so for property:
1558 1508 #
1559 1509 # property.__get__(self, None, cls) -> self
1560 1510 #
1561 1511 # The universal alternative is to traverse the mro manually
1562 1512 # searching for attrname in class dicts.
1563 1513 attr = getattr(type(obj), attrname)
1564 1514 except AttributeError:
1565 1515 pass
1566 1516 else:
1567 1517 # This relies on the fact that data descriptors (with both
1568 1518 # __get__ & __set__ magic methods) take precedence over
1569 1519 # instance-level attributes:
1570 1520 #
1571 1521 # class A(object):
1572 1522 # @property
1573 1523 # def foobar(self): return 123
1574 1524 # a = A()
1575 1525 # a.__dict__['foobar'] = 345
1576 1526 # a.foobar # == 123
1577 1527 #
1578 1528 # So, a property may be returned right away.
1579 1529 if isinstance(attr, property):
1580 1530 return attr
1581 1531
1582 1532 # Nothing helped, fall back.
1583 1533 return getattr(obj, attrname)
1584 1534
1585 1535 def _object_find(self, oname, namespaces=None):
1586 1536 """Find an object and return a struct with info about it."""
1587 1537 return Struct(self._ofind(oname, namespaces))
1588 1538
1589 1539 def _inspect(self, meth, oname, namespaces=None, **kw):
1590 1540 """Generic interface to the inspector system.
1591 1541
1592 1542 This function is meant to be called by pdef, pdoc & friends."""
1593 1543 info = self._object_find(oname, namespaces)
1594 1544 if info.found:
1595 1545 pmethod = getattr(self.inspector, meth)
1596 1546 formatter = format_screen if info.ismagic else None
1597 1547 if meth == 'pdoc':
1598 1548 pmethod(info.obj, oname, formatter)
1599 1549 elif meth == 'pinfo':
1600 1550 pmethod(info.obj, oname, formatter, info, **kw)
1601 1551 else:
1602 1552 pmethod(info.obj, oname)
1603 1553 else:
1604 1554 print('Object `%s` not found.' % oname)
1605 1555 return 'not found' # so callers can take other action
1606 1556
1607 1557 def object_inspect(self, oname, detail_level=0):
1608 1558 """Get object info about oname"""
1609 1559 with self.builtin_trap:
1610 1560 info = self._object_find(oname)
1611 1561 if info.found:
1612 1562 return self.inspector.info(info.obj, oname, info=info,
1613 1563 detail_level=detail_level
1614 1564 )
1615 1565 else:
1616 1566 return oinspect.object_info(name=oname, found=False)
1617 1567
1618 1568 def object_inspect_text(self, oname, detail_level=0):
1619 1569 """Get object info as formatted text"""
1620 1570 with self.builtin_trap:
1621 1571 info = self._object_find(oname)
1622 1572 if info.found:
1623 1573 return self.inspector._format_info(info.obj, oname, info=info,
1624 1574 detail_level=detail_level
1625 1575 )
1626 1576 else:
1627 1577 raise KeyError(oname)
1628 1578
1629 1579 #-------------------------------------------------------------------------
1630 1580 # Things related to history management
1631 1581 #-------------------------------------------------------------------------
1632 1582
1633 1583 def init_history(self):
1634 1584 """Sets up the command history, and starts regular autosaves."""
1635 1585 self.history_manager = HistoryManager(shell=self, parent=self)
1636 1586 self.configurables.append(self.history_manager)
1637 1587
1638 1588 #-------------------------------------------------------------------------
1639 1589 # Things related to exception handling and tracebacks (not debugging)
1640 1590 #-------------------------------------------------------------------------
1641 1591
1642 1592 def init_traceback_handlers(self, custom_exceptions):
1643 1593 # Syntax error handler.
1644 1594 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1645 1595
1646 1596 # The interactive one is initialized with an offset, meaning we always
1647 1597 # want to remove the topmost item in the traceback, which is our own
1648 1598 # internal code. Valid modes: ['Plain','Context','Verbose']
1649 1599 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1650 1600 color_scheme='NoColor',
1651 1601 tb_offset = 1,
1652 1602 check_cache=check_linecache_ipython)
1653 1603
1654 1604 # The instance will store a pointer to the system-wide exception hook,
1655 1605 # so that runtime code (such as magics) can access it. This is because
1656 1606 # during the read-eval loop, it may get temporarily overwritten.
1657 1607 self.sys_excepthook = sys.excepthook
1658 1608
1659 1609 # and add any custom exception handlers the user may have specified
1660 1610 self.set_custom_exc(*custom_exceptions)
1661 1611
1662 1612 # Set the exception mode
1663 1613 self.InteractiveTB.set_mode(mode=self.xmode)
1664 1614
1665 1615 def set_custom_exc(self, exc_tuple, handler):
1666 1616 """set_custom_exc(exc_tuple,handler)
1667 1617
1668 1618 Set a custom exception handler, which will be called if any of the
1669 1619 exceptions in exc_tuple occur in the mainloop (specifically, in the
1670 1620 run_code() method).
1671 1621
1672 1622 Parameters
1673 1623 ----------
1674 1624
1675 1625 exc_tuple : tuple of exception classes
1676 1626 A *tuple* of exception classes, for which to call the defined
1677 1627 handler. It is very important that you use a tuple, and NOT A
1678 1628 LIST here, because of the way Python's except statement works. If
1679 1629 you only want to trap a single exception, use a singleton tuple::
1680 1630
1681 1631 exc_tuple == (MyCustomException,)
1682 1632
1683 1633 handler : callable
1684 1634 handler must have the following signature::
1685 1635
1686 1636 def my_handler(self, etype, value, tb, tb_offset=None):
1687 1637 ...
1688 1638 return structured_traceback
1689 1639
1690 1640 Your handler must return a structured traceback (a list of strings),
1691 1641 or None.
1692 1642
1693 1643 This will be made into an instance method (via types.MethodType)
1694 1644 of IPython itself, and it will be called if any of the exceptions
1695 1645 listed in the exc_tuple are caught. If the handler is None, an
1696 1646 internal basic one is used, which just prints basic info.
1697 1647
1698 1648 To protect IPython from crashes, if your handler ever raises an
1699 1649 exception or returns an invalid result, it will be immediately
1700 1650 disabled.
1701 1651
1702 1652 WARNING: by putting in your own exception handler into IPython's main
1703 1653 execution loop, you run a very good chance of nasty crashes. This
1704 1654 facility should only be used if you really know what you are doing."""
1705 1655
1706 1656 assert type(exc_tuple)==type(()) , \
1707 1657 "The custom exceptions must be given AS A TUPLE."
1708 1658
1709 1659 def dummy_handler(self,etype,value,tb,tb_offset=None):
1710 1660 print('*** Simple custom exception handler ***')
1711 1661 print('Exception type :',etype)
1712 1662 print('Exception value:',value)
1713 1663 print('Traceback :',tb)
1714 1664 #print 'Source code :','\n'.join(self.buffer)
1715 1665
1716 1666 def validate_stb(stb):
1717 1667 """validate structured traceback return type
1718 1668
1719 1669 return type of CustomTB *should* be a list of strings, but allow
1720 1670 single strings or None, which are harmless.
1721 1671
1722 1672 This function will *always* return a list of strings,
1723 1673 and will raise a TypeError if stb is inappropriate.
1724 1674 """
1725 1675 msg = "CustomTB must return list of strings, not %r" % stb
1726 1676 if stb is None:
1727 1677 return []
1728 1678 elif isinstance(stb, string_types):
1729 1679 return [stb]
1730 1680 elif not isinstance(stb, list):
1731 1681 raise TypeError(msg)
1732 1682 # it's a list
1733 1683 for line in stb:
1734 1684 # check every element
1735 1685 if not isinstance(line, string_types):
1736 1686 raise TypeError(msg)
1737 1687 return stb
1738 1688
1739 1689 if handler is None:
1740 1690 wrapped = dummy_handler
1741 1691 else:
1742 1692 def wrapped(self,etype,value,tb,tb_offset=None):
1743 1693 """wrap CustomTB handler, to protect IPython from user code
1744 1694
1745 1695 This makes it harder (but not impossible) for custom exception
1746 1696 handlers to crash IPython.
1747 1697 """
1748 1698 try:
1749 1699 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1750 1700 return validate_stb(stb)
1751 1701 except:
1752 1702 # clear custom handler immediately
1753 1703 self.set_custom_exc((), None)
1754 1704 print("Custom TB Handler failed, unregistering", file=io.stderr)
1755 1705 # show the exception in handler first
1756 1706 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1757 1707 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1758 1708 print("The original exception:", file=io.stdout)
1759 1709 stb = self.InteractiveTB.structured_traceback(
1760 1710 (etype,value,tb), tb_offset=tb_offset
1761 1711 )
1762 1712 return stb
1763 1713
1764 1714 self.CustomTB = types.MethodType(wrapped,self)
1765 1715 self.custom_exceptions = exc_tuple
1766 1716
1767 1717 def excepthook(self, etype, value, tb):
1768 1718 """One more defense for GUI apps that call sys.excepthook.
1769 1719
1770 1720 GUI frameworks like wxPython trap exceptions and call
1771 1721 sys.excepthook themselves. I guess this is a feature that
1772 1722 enables them to keep running after exceptions that would
1773 1723 otherwise kill their mainloop. This is a bother for IPython
1774 1724 which excepts to catch all of the program exceptions with a try:
1775 1725 except: statement.
1776 1726
1777 1727 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1778 1728 any app directly invokes sys.excepthook, it will look to the user like
1779 1729 IPython crashed. In order to work around this, we can disable the
1780 1730 CrashHandler and replace it with this excepthook instead, which prints a
1781 1731 regular traceback using our InteractiveTB. In this fashion, apps which
1782 1732 call sys.excepthook will generate a regular-looking exception from
1783 1733 IPython, and the CrashHandler will only be triggered by real IPython
1784 1734 crashes.
1785 1735
1786 1736 This hook should be used sparingly, only in places which are not likely
1787 1737 to be true IPython errors.
1788 1738 """
1789 1739 self.showtraceback((etype, value, tb), tb_offset=0)
1790 1740
1791 1741 def _get_exc_info(self, exc_tuple=None):
1792 1742 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1793 1743
1794 1744 Ensures sys.last_type,value,traceback hold the exc_info we found,
1795 1745 from whichever source.
1796 1746
1797 1747 raises ValueError if none of these contain any information
1798 1748 """
1799 1749 if exc_tuple is None:
1800 1750 etype, value, tb = sys.exc_info()
1801 1751 else:
1802 1752 etype, value, tb = exc_tuple
1803 1753
1804 1754 if etype is None:
1805 1755 if hasattr(sys, 'last_type'):
1806 1756 etype, value, tb = sys.last_type, sys.last_value, \
1807 1757 sys.last_traceback
1808 1758
1809 1759 if etype is None:
1810 1760 raise ValueError("No exception to find")
1811 1761
1812 1762 # Now store the exception info in sys.last_type etc.
1813 1763 # WARNING: these variables are somewhat deprecated and not
1814 1764 # necessarily safe to use in a threaded environment, but tools
1815 1765 # like pdb depend on their existence, so let's set them. If we
1816 1766 # find problems in the field, we'll need to revisit their use.
1817 1767 sys.last_type = etype
1818 1768 sys.last_value = value
1819 1769 sys.last_traceback = tb
1820 1770
1821 1771 return etype, value, tb
1822 1772
1823 1773 def show_usage_error(self, exc):
1824 1774 """Show a short message for UsageErrors
1825 1775
1826 1776 These are special exceptions that shouldn't show a traceback.
1827 1777 """
1828 1778 self.write_err("UsageError: %s" % exc)
1829 1779
1830 1780 def get_exception_only(self, exc_tuple=None):
1831 1781 """
1832 1782 Return as a string (ending with a newline) the exception that
1833 1783 just occurred, without any traceback.
1834 1784 """
1835 1785 etype, value, tb = self._get_exc_info(exc_tuple)
1836 1786 msg = traceback.format_exception_only(etype, value)
1837 1787 return ''.join(msg)
1838 1788
1839 1789 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1840 1790 exception_only=False):
1841 1791 """Display the exception that just occurred.
1842 1792
1843 1793 If nothing is known about the exception, this is the method which
1844 1794 should be used throughout the code for presenting user tracebacks,
1845 1795 rather than directly invoking the InteractiveTB object.
1846 1796
1847 1797 A specific showsyntaxerror() also exists, but this method can take
1848 1798 care of calling it if needed, so unless you are explicitly catching a
1849 1799 SyntaxError exception, don't try to analyze the stack manually and
1850 1800 simply call this method."""
1851 1801
1852 1802 try:
1853 1803 try:
1854 1804 etype, value, tb = self._get_exc_info(exc_tuple)
1855 1805 except ValueError:
1856 1806 self.write_err('No traceback available to show.\n')
1857 1807 return
1858 1808
1859 1809 if issubclass(etype, SyntaxError):
1860 1810 # Though this won't be called by syntax errors in the input
1861 1811 # line, there may be SyntaxError cases with imported code.
1862 1812 self.showsyntaxerror(filename)
1863 1813 elif etype is UsageError:
1864 1814 self.show_usage_error(value)
1865 1815 else:
1866 1816 if exception_only:
1867 1817 stb = ['An exception has occurred, use %tb to see '
1868 1818 'the full traceback.\n']
1869 1819 stb.extend(self.InteractiveTB.get_exception_only(etype,
1870 1820 value))
1871 1821 else:
1872 1822 try:
1873 1823 # Exception classes can customise their traceback - we
1874 1824 # use this in IPython.parallel for exceptions occurring
1875 1825 # in the engines. This should return a list of strings.
1876 1826 stb = value._render_traceback_()
1877 1827 except Exception:
1878 1828 stb = self.InteractiveTB.structured_traceback(etype,
1879 1829 value, tb, tb_offset=tb_offset)
1880 1830
1881 1831 self._showtraceback(etype, value, stb)
1882 1832 if self.call_pdb:
1883 1833 # drop into debugger
1884 1834 self.debugger(force=True)
1885 1835 return
1886 1836
1887 1837 # Actually show the traceback
1888 1838 self._showtraceback(etype, value, stb)
1889 1839
1890 1840 except KeyboardInterrupt:
1891 1841 self.write_err('\n' + self.get_exception_only())
1892 1842
1893 1843 def _showtraceback(self, etype, evalue, stb):
1894 1844 """Actually show a traceback.
1895 1845
1896 1846 Subclasses may override this method to put the traceback on a different
1897 1847 place, like a side channel.
1898 1848 """
1899 1849 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1900 1850
1901 1851 def showsyntaxerror(self, filename=None):
1902 1852 """Display the syntax error that just occurred.
1903 1853
1904 1854 This doesn't display a stack trace because there isn't one.
1905 1855
1906 1856 If a filename is given, it is stuffed in the exception instead
1907 1857 of what was there before (because Python's parser always uses
1908 1858 "<string>" when reading from a string).
1909 1859 """
1910 1860 etype, value, last_traceback = self._get_exc_info()
1911 1861
1912 1862 if filename and issubclass(etype, SyntaxError):
1913 1863 try:
1914 1864 value.filename = filename
1915 1865 except:
1916 1866 # Not the format we expect; leave it alone
1917 1867 pass
1918 1868
1919 1869 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1920 1870 self._showtraceback(etype, value, stb)
1921 1871
1922 1872 # This is overridden in TerminalInteractiveShell to show a message about
1923 1873 # the %paste magic.
1924 1874 def showindentationerror(self):
1925 1875 """Called by run_cell when there's an IndentationError in code entered
1926 1876 at the prompt.
1927 1877
1928 1878 This is overridden in TerminalInteractiveShell to show a message about
1929 1879 the %paste magic."""
1930 1880 self.showsyntaxerror()
1931 1881
1932 1882 #-------------------------------------------------------------------------
1933 1883 # Things related to readline
1934 1884 #-------------------------------------------------------------------------
1935 1885
1936 1886 def init_readline(self):
1937 """Command history completion/saving/reloading."""
1938
1939 if self.readline_use:
1940 import IPython.utils.rlineimpl as readline
1941
1942 self.rl_next_input = None
1943 self.rl_do_indent = False
1944
1945 if not self.readline_use or not readline.have_readline:
1946 self.has_readline = False
1947 self.readline = None
1948 # Set a number of methods that depend on readline to be no-op
1949 self.readline_no_record = no_op_context
1950 self.set_readline_completer = no_op
1951 self.set_custom_completer = no_op
1952 if self.readline_use:
1953 warn('Readline services not available or not loaded.')
1954 else:
1955 self.has_readline = True
1956 self.readline = readline
1957 sys.modules['readline'] = readline
1958
1959 # Platform-specific configuration
1960 if os.name == 'nt':
1961 # FIXME - check with Frederick to see if we can harmonize
1962 # naming conventions with pyreadline to avoid this
1963 # platform-dependent check
1964 self.readline_startup_hook = readline.set_pre_input_hook
1965 else:
1966 self.readline_startup_hook = readline.set_startup_hook
1967
1968 # Readline config order:
1969 # - IPython config (default value)
1970 # - custom inputrc
1971 # - IPython config (user customized)
1972
1973 # load IPython config before inputrc if default
1974 # skip if libedit because parse_and_bind syntax is different
1975 if not self._custom_readline_config and not readline.uses_libedit:
1976 for rlcommand in self.readline_parse_and_bind:
1977 readline.parse_and_bind(rlcommand)
1978
1979 # Load user's initrc file (readline config)
1980 # Or if libedit is used, load editrc.
1981 inputrc_name = os.environ.get('INPUTRC')
1982 if inputrc_name is None:
1983 inputrc_name = '.inputrc'
1984 if readline.uses_libedit:
1985 inputrc_name = '.editrc'
1986 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1987 if os.path.isfile(inputrc_name):
1988 try:
1989 readline.read_init_file(inputrc_name)
1990 except:
1991 warn('Problems reading readline initialization file <%s>'
1992 % inputrc_name)
1993
1994 # load IPython config after inputrc if user has customized
1995 if self._custom_readline_config:
1996 for rlcommand in self.readline_parse_and_bind:
1997 readline.parse_and_bind(rlcommand)
1998
1999 # Remove some chars from the delimiters list. If we encounter
2000 # unicode chars, discard them.
2001 delims = readline.get_completer_delims()
2002 if not py3compat.PY3:
2003 delims = delims.encode("ascii", "ignore")
2004 for d in self.readline_remove_delims:
2005 delims = delims.replace(d, "")
2006 delims = delims.replace(ESC_MAGIC, '')
2007 readline.set_completer_delims(delims)
2008 # Store these so we can restore them if something like rpy2 modifies
2009 # them.
2010 self.readline_delims = delims
2011 # otherwise we end up with a monster history after a while:
2012 readline.set_history_length(self.history_length)
2013
2014 self.refill_readline_hist()
2015 self.readline_no_record = ReadlineNoRecord(self)
2016
2017 # Configure auto-indent for all platforms
2018 self.set_autoindent(self.autoindent)
2019
2020 def refill_readline_hist(self):
2021 # Load the last 1000 lines from history
2022 self.readline.clear_history()
2023 stdin_encoding = sys.stdin.encoding or "utf-8"
2024 last_cell = u""
2025 for _, _, cell in self.history_manager.get_tail(self.history_load_length,
2026 include_latest=True):
2027 # Ignore blank lines and consecutive duplicates
2028 cell = cell.rstrip()
2029 if cell and (cell != last_cell):
2030 try:
2031 if self.multiline_history:
2032 self.readline.add_history(py3compat.unicode_to_str(cell,
2033 stdin_encoding))
2034 else:
2035 for line in cell.splitlines():
2036 self.readline.add_history(py3compat.unicode_to_str(line,
2037 stdin_encoding))
2038 last_cell = cell
2039
2040 except TypeError:
2041 # The history DB can get corrupted so it returns strings
2042 # containing null bytes, which readline objects to.
2043 continue
1887 """Moved to terminal subclass, here only to simplify the init logic."""
1888 self.readline = None
1889 # Set a number of methods that depend on readline to be no-op
1890 self.readline_no_record = NoOpContext()
1891 self.set_readline_completer = no_op
1892 self.set_custom_completer = no_op
2044 1893
2045 1894 @skip_doctest
2046 1895 def set_next_input(self, s, replace=False):
2047 1896 """ Sets the 'default' input string for the next command line.
2048 1897
2049 Requires readline.
2050
2051 1898 Example::
2052 1899
2053 1900 In [1]: _ip.set_next_input("Hello Word")
2054 1901 In [2]: Hello Word_ # cursor is here
2055 1902 """
2056 1903 self.rl_next_input = py3compat.cast_bytes_py2(s)
2057 1904
2058 # Maybe move this to the terminal subclass?
2059 def pre_readline(self):
2060 """readline hook to be used at the start of each line.
2061
2062 Currently it handles auto-indent only."""
2063
2064 if self.rl_do_indent:
2065 self.readline.insert_text(self._indent_current_str())
2066 if self.rl_next_input is not None:
2067 self.readline.insert_text(self.rl_next_input)
2068 self.rl_next_input = None
2069
2070 1905 def _indent_current_str(self):
2071 1906 """return the current level of indentation as a string"""
2072 1907 return self.input_splitter.indent_spaces * ' '
2073 1908
2074 1909 #-------------------------------------------------------------------------
2075 1910 # Things related to text completion
2076 1911 #-------------------------------------------------------------------------
2077 1912
2078 1913 def init_completer(self):
2079 1914 """Initialize the completion machinery.
2080 1915
2081 1916 This creates completion machinery that can be used by client code,
2082 1917 either interactively in-process (typically triggered by the readline
2083 1918 library), programatically (such as in test suites) or out-of-prcess
2084 1919 (typically over the network by remote frontends).
2085 1920 """
2086 1921 from IPython.core.completer import IPCompleter
2087 1922 from IPython.core.completerlib import (module_completer,
2088 1923 magic_run_completer, cd_completer, reset_completer)
2089 1924
2090 1925 self.Completer = IPCompleter(shell=self,
2091 1926 namespace=self.user_ns,
2092 1927 global_namespace=self.user_global_ns,
2093 1928 use_readline=self.has_readline,
2094 1929 parent=self,
2095 1930 )
2096 1931 self.configurables.append(self.Completer)
2097 1932
2098 1933 # Add custom completers to the basic ones built into IPCompleter
2099 1934 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
2100 1935 self.strdispatchers['complete_command'] = sdisp
2101 1936 self.Completer.custom_completers = sdisp
2102 1937
2103 1938 self.set_hook('complete_command', module_completer, str_key = 'import')
2104 1939 self.set_hook('complete_command', module_completer, str_key = 'from')
2105 1940 self.set_hook('complete_command', module_completer, str_key = '%aimport')
2106 1941 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
2107 1942 self.set_hook('complete_command', cd_completer, str_key = '%cd')
2108 1943 self.set_hook('complete_command', reset_completer, str_key = '%reset')
2109 1944
2110 # Only configure readline if we truly are using readline. IPython can
2111 # do tab-completion over the network, in GUIs, etc, where readline
2112 # itself may be absent
2113 if self.has_readline:
2114 self.set_readline_completer()
2115 1945
2116 1946 def complete(self, text, line=None, cursor_pos=None):
2117 1947 """Return the completed text and a list of completions.
2118 1948
2119 1949 Parameters
2120 1950 ----------
2121 1951
2122 1952 text : string
2123 1953 A string of text to be completed on. It can be given as empty and
2124 1954 instead a line/position pair are given. In this case, the
2125 1955 completer itself will split the line like readline does.
2126 1956
2127 1957 line : string, optional
2128 1958 The complete line that text is part of.
2129 1959
2130 1960 cursor_pos : int, optional
2131 1961 The position of the cursor on the input line.
2132 1962
2133 1963 Returns
2134 1964 -------
2135 1965 text : string
2136 1966 The actual text that was completed.
2137 1967
2138 1968 matches : list
2139 1969 A sorted list with all possible completions.
2140 1970
2141 1971 The optional arguments allow the completion to take more context into
2142 1972 account, and are part of the low-level completion API.
2143 1973
2144 1974 This is a wrapper around the completion mechanism, similar to what
2145 1975 readline does at the command line when the TAB key is hit. By
2146 1976 exposing it as a method, it can be used by other non-readline
2147 1977 environments (such as GUIs) for text completion.
2148 1978
2149 1979 Simple usage example:
2150 1980
2151 1981 In [1]: x = 'hello'
2152 1982
2153 1983 In [2]: _ip.complete('x.l')
2154 1984 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2155 1985 """
2156 1986
2157 1987 # Inject names into __builtin__ so we can complete on the added names.
2158 1988 with self.builtin_trap:
2159 1989 return self.Completer.complete(text, line, cursor_pos)
2160 1990
2161 1991 def set_custom_completer(self, completer, pos=0):
2162 1992 """Adds a new custom completer function.
2163 1993
2164 1994 The position argument (defaults to 0) is the index in the completers
2165 1995 list where you want the completer to be inserted."""
2166 1996
2167 1997 newcomp = types.MethodType(completer,self.Completer)
2168 1998 self.Completer.matchers.insert(pos,newcomp)
2169 1999
2170 def set_readline_completer(self):
2171 """Reset readline's completer to be our own."""
2172 self.readline.set_completer(self.Completer.rlcomplete)
2173
2174 2000 def set_completer_frame(self, frame=None):
2175 2001 """Set the frame of the completer."""
2176 2002 if frame:
2177 2003 self.Completer.namespace = frame.f_locals
2178 2004 self.Completer.global_namespace = frame.f_globals
2179 2005 else:
2180 2006 self.Completer.namespace = self.user_ns
2181 2007 self.Completer.global_namespace = self.user_global_ns
2182 2008
2183 2009 #-------------------------------------------------------------------------
2184 2010 # Things related to magics
2185 2011 #-------------------------------------------------------------------------
2186 2012
2187 2013 def init_magics(self):
2188 2014 from IPython.core import magics as m
2189 2015 self.magics_manager = magic.MagicsManager(shell=self,
2190 2016 parent=self,
2191 2017 user_magics=m.UserMagics(self))
2192 2018 self.configurables.append(self.magics_manager)
2193 2019
2194 2020 # Expose as public API from the magics manager
2195 2021 self.register_magics = self.magics_manager.register
2196 2022 self.define_magic = self.magics_manager.define_magic
2197 2023
2198 2024 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2199 2025 m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics,
2200 2026 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2201 2027 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2202 2028 )
2203 2029
2204 2030 # Register Magic Aliases
2205 2031 mman = self.magics_manager
2206 2032 # FIXME: magic aliases should be defined by the Magics classes
2207 2033 # or in MagicsManager, not here
2208 2034 mman.register_alias('ed', 'edit')
2209 2035 mman.register_alias('hist', 'history')
2210 2036 mman.register_alias('rep', 'recall')
2211 2037 mman.register_alias('SVG', 'svg', 'cell')
2212 2038 mman.register_alias('HTML', 'html', 'cell')
2213 2039 mman.register_alias('file', 'writefile', 'cell')
2214 2040
2215 2041 # FIXME: Move the color initialization to the DisplayHook, which
2216 2042 # should be split into a prompt manager and displayhook. We probably
2217 2043 # even need a centralize colors management object.
2218 2044 self.magic('colors %s' % self.colors)
2219 2045
2220 2046 # Defined here so that it's included in the documentation
2221 2047 @functools.wraps(magic.MagicsManager.register_function)
2222 2048 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2223 2049 self.magics_manager.register_function(func,
2224 2050 magic_kind=magic_kind, magic_name=magic_name)
2225 2051
2226 2052 def run_line_magic(self, magic_name, line):
2227 2053 """Execute the given line magic.
2228 2054
2229 2055 Parameters
2230 2056 ----------
2231 2057 magic_name : str
2232 2058 Name of the desired magic function, without '%' prefix.
2233 2059
2234 2060 line : str
2235 2061 The rest of the input line as a single string.
2236 2062 """
2237 2063 fn = self.find_line_magic(magic_name)
2238 2064 if fn is None:
2239 2065 cm = self.find_cell_magic(magic_name)
2240 2066 etpl = "Line magic function `%%%s` not found%s."
2241 2067 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2242 2068 'did you mean that instead?)' % magic_name )
2243 2069 error(etpl % (magic_name, extra))
2244 2070 else:
2245 2071 # Note: this is the distance in the stack to the user's frame.
2246 2072 # This will need to be updated if the internal calling logic gets
2247 2073 # refactored, or else we'll be expanding the wrong variables.
2248 2074 stack_depth = 2
2249 2075 magic_arg_s = self.var_expand(line, stack_depth)
2250 2076 # Put magic args in a list so we can call with f(*a) syntax
2251 2077 args = [magic_arg_s]
2252 2078 kwargs = {}
2253 2079 # Grab local namespace if we need it:
2254 2080 if getattr(fn, "needs_local_scope", False):
2255 2081 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2256 2082 with self.builtin_trap:
2257 2083 result = fn(*args,**kwargs)
2258 2084 return result
2259 2085
2260 2086 def run_cell_magic(self, magic_name, line, cell):
2261 2087 """Execute the given cell magic.
2262 2088
2263 2089 Parameters
2264 2090 ----------
2265 2091 magic_name : str
2266 2092 Name of the desired magic function, without '%' prefix.
2267 2093
2268 2094 line : str
2269 2095 The rest of the first input line as a single string.
2270 2096
2271 2097 cell : str
2272 2098 The body of the cell as a (possibly multiline) string.
2273 2099 """
2274 2100 fn = self.find_cell_magic(magic_name)
2275 2101 if fn is None:
2276 2102 lm = self.find_line_magic(magic_name)
2277 2103 etpl = "Cell magic `%%{0}` not found{1}."
2278 2104 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2279 2105 'did you mean that instead?)'.format(magic_name))
2280 2106 error(etpl.format(magic_name, extra))
2281 2107 elif cell == '':
2282 2108 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2283 2109 if self.find_line_magic(magic_name) is not None:
2284 2110 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2285 2111 raise UsageError(message)
2286 2112 else:
2287 2113 # Note: this is the distance in the stack to the user's frame.
2288 2114 # This will need to be updated if the internal calling logic gets
2289 2115 # refactored, or else we'll be expanding the wrong variables.
2290 2116 stack_depth = 2
2291 2117 magic_arg_s = self.var_expand(line, stack_depth)
2292 2118 with self.builtin_trap:
2293 2119 result = fn(magic_arg_s, cell)
2294 2120 return result
2295 2121
2296 2122 def find_line_magic(self, magic_name):
2297 2123 """Find and return a line magic by name.
2298 2124
2299 2125 Returns None if the magic isn't found."""
2300 2126 return self.magics_manager.magics['line'].get(magic_name)
2301 2127
2302 2128 def find_cell_magic(self, magic_name):
2303 2129 """Find and return a cell magic by name.
2304 2130
2305 2131 Returns None if the magic isn't found."""
2306 2132 return self.magics_manager.magics['cell'].get(magic_name)
2307 2133
2308 2134 def find_magic(self, magic_name, magic_kind='line'):
2309 2135 """Find and return a magic of the given type by name.
2310 2136
2311 2137 Returns None if the magic isn't found."""
2312 2138 return self.magics_manager.magics[magic_kind].get(magic_name)
2313 2139
2314 2140 def magic(self, arg_s):
2315 2141 """DEPRECATED. Use run_line_magic() instead.
2316 2142
2317 2143 Call a magic function by name.
2318 2144
2319 2145 Input: a string containing the name of the magic function to call and
2320 2146 any additional arguments to be passed to the magic.
2321 2147
2322 2148 magic('name -opt foo bar') is equivalent to typing at the ipython
2323 2149 prompt:
2324 2150
2325 2151 In[1]: %name -opt foo bar
2326 2152
2327 2153 To call a magic without arguments, simply use magic('name').
2328 2154
2329 2155 This provides a proper Python function to call IPython's magics in any
2330 2156 valid Python code you can type at the interpreter, including loops and
2331 2157 compound statements.
2332 2158 """
2333 2159 # TODO: should we issue a loud deprecation warning here?
2334 2160 magic_name, _, magic_arg_s = arg_s.partition(' ')
2335 2161 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2336 2162 return self.run_line_magic(magic_name, magic_arg_s)
2337 2163
2338 2164 #-------------------------------------------------------------------------
2339 2165 # Things related to macros
2340 2166 #-------------------------------------------------------------------------
2341 2167
2342 2168 def define_macro(self, name, themacro):
2343 2169 """Define a new macro
2344 2170
2345 2171 Parameters
2346 2172 ----------
2347 2173 name : str
2348 2174 The name of the macro.
2349 2175 themacro : str or Macro
2350 2176 The action to do upon invoking the macro. If a string, a new
2351 2177 Macro object is created by passing the string to it.
2352 2178 """
2353 2179
2354 2180 from IPython.core import macro
2355 2181
2356 2182 if isinstance(themacro, string_types):
2357 2183 themacro = macro.Macro(themacro)
2358 2184 if not isinstance(themacro, macro.Macro):
2359 2185 raise ValueError('A macro must be a string or a Macro instance.')
2360 2186 self.user_ns[name] = themacro
2361 2187
2362 2188 #-------------------------------------------------------------------------
2363 2189 # Things related to the running of system commands
2364 2190 #-------------------------------------------------------------------------
2365 2191
2366 2192 def system_piped(self, cmd):
2367 2193 """Call the given cmd in a subprocess, piping stdout/err
2368 2194
2369 2195 Parameters
2370 2196 ----------
2371 2197 cmd : str
2372 2198 Command to execute (can not end in '&', as background processes are
2373 2199 not supported. Should not be a command that expects input
2374 2200 other than simple text.
2375 2201 """
2376 2202 if cmd.rstrip().endswith('&'):
2377 2203 # this is *far* from a rigorous test
2378 2204 # We do not support backgrounding processes because we either use
2379 2205 # pexpect or pipes to read from. Users can always just call
2380 2206 # os.system() or use ip.system=ip.system_raw
2381 2207 # if they really want a background process.
2382 2208 raise OSError("Background processes not supported.")
2383 2209
2384 2210 # we explicitly do NOT return the subprocess status code, because
2385 2211 # a non-None value would trigger :func:`sys.displayhook` calls.
2386 2212 # Instead, we store the exit_code in user_ns.
2387 2213 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2388 2214
2389 2215 def system_raw(self, cmd):
2390 2216 """Call the given cmd in a subprocess using os.system on Windows or
2391 2217 subprocess.call using the system shell on other platforms.
2392 2218
2393 2219 Parameters
2394 2220 ----------
2395 2221 cmd : str
2396 2222 Command to execute.
2397 2223 """
2398 2224 cmd = self.var_expand(cmd, depth=1)
2399 2225 # protect os.system from UNC paths on Windows, which it can't handle:
2400 2226 if sys.platform == 'win32':
2401 2227 from IPython.utils._process_win32 import AvoidUNCPath
2402 2228 with AvoidUNCPath() as path:
2403 2229 if path is not None:
2404 2230 cmd = '"pushd %s &&"%s' % (path, cmd)
2405 2231 cmd = py3compat.unicode_to_str(cmd)
2406 2232 try:
2407 2233 ec = os.system(cmd)
2408 2234 except KeyboardInterrupt:
2409 2235 self.write_err('\n' + self.get_exception_only())
2410 2236 ec = -2
2411 2237 else:
2412 2238 cmd = py3compat.unicode_to_str(cmd)
2413 2239 # For posix the result of the subprocess.call() below is an exit
2414 2240 # code, which by convention is zero for success, positive for
2415 2241 # program failure. Exit codes above 128 are reserved for signals,
2416 2242 # and the formula for converting a signal to an exit code is usually
2417 2243 # signal_number+128. To more easily differentiate between exit
2418 2244 # codes and signals, ipython uses negative numbers. For instance
2419 2245 # since control-c is signal 2 but exit code 130, ipython's
2420 2246 # _exit_code variable will read -2. Note that some shells like
2421 2247 # csh and fish don't follow sh/bash conventions for exit codes.
2422 2248 executable = os.environ.get('SHELL', None)
2423 2249 try:
2424 2250 # Use env shell instead of default /bin/sh
2425 2251 ec = subprocess.call(cmd, shell=True, executable=executable)
2426 2252 except KeyboardInterrupt:
2427 2253 # intercept control-C; a long traceback is not useful here
2428 2254 self.write_err('\n' + self.get_exception_only())
2429 2255 ec = 130
2430 2256 if ec > 128:
2431 2257 ec = -(ec - 128)
2432 2258
2433 2259 # We explicitly do NOT return the subprocess status code, because
2434 2260 # a non-None value would trigger :func:`sys.displayhook` calls.
2435 2261 # Instead, we store the exit_code in user_ns. Note the semantics
2436 2262 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2437 2263 # but raising SystemExit(_exit_code) will give status 254!
2438 2264 self.user_ns['_exit_code'] = ec
2439 2265
2440 2266 # use piped system by default, because it is better behaved
2441 2267 system = system_piped
2442 2268
2443 2269 def getoutput(self, cmd, split=True, depth=0):
2444 2270 """Get output (possibly including stderr) from a subprocess.
2445 2271
2446 2272 Parameters
2447 2273 ----------
2448 2274 cmd : str
2449 2275 Command to execute (can not end in '&', as background processes are
2450 2276 not supported.
2451 2277 split : bool, optional
2452 2278 If True, split the output into an IPython SList. Otherwise, an
2453 2279 IPython LSString is returned. These are objects similar to normal
2454 2280 lists and strings, with a few convenience attributes for easier
2455 2281 manipulation of line-based output. You can use '?' on them for
2456 2282 details.
2457 2283 depth : int, optional
2458 2284 How many frames above the caller are the local variables which should
2459 2285 be expanded in the command string? The default (0) assumes that the
2460 2286 expansion variables are in the stack frame calling this function.
2461 2287 """
2462 2288 if cmd.rstrip().endswith('&'):
2463 2289 # this is *far* from a rigorous test
2464 2290 raise OSError("Background processes not supported.")
2465 2291 out = getoutput(self.var_expand(cmd, depth=depth+1))
2466 2292 if split:
2467 2293 out = SList(out.splitlines())
2468 2294 else:
2469 2295 out = LSString(out)
2470 2296 return out
2471 2297
2472 2298 #-------------------------------------------------------------------------
2473 2299 # Things related to aliases
2474 2300 #-------------------------------------------------------------------------
2475 2301
2476 2302 def init_alias(self):
2477 2303 self.alias_manager = AliasManager(shell=self, parent=self)
2478 2304 self.configurables.append(self.alias_manager)
2479 2305
2480 2306 #-------------------------------------------------------------------------
2481 2307 # Things related to extensions
2482 2308 #-------------------------------------------------------------------------
2483 2309
2484 2310 def init_extension_manager(self):
2485 2311 self.extension_manager = ExtensionManager(shell=self, parent=self)
2486 2312 self.configurables.append(self.extension_manager)
2487 2313
2488 2314 #-------------------------------------------------------------------------
2489 2315 # Things related to payloads
2490 2316 #-------------------------------------------------------------------------
2491 2317
2492 2318 def init_payload(self):
2493 2319 self.payload_manager = PayloadManager(parent=self)
2494 2320 self.configurables.append(self.payload_manager)
2495 2321
2496 2322 #-------------------------------------------------------------------------
2497 2323 # Things related to the prefilter
2498 2324 #-------------------------------------------------------------------------
2499 2325
2500 2326 def init_prefilter(self):
2501 2327 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2502 2328 self.configurables.append(self.prefilter_manager)
2503 2329 # Ultimately this will be refactored in the new interpreter code, but
2504 2330 # for now, we should expose the main prefilter method (there's legacy
2505 2331 # code out there that may rely on this).
2506 2332 self.prefilter = self.prefilter_manager.prefilter_lines
2507 2333
2508 2334 def auto_rewrite_input(self, cmd):
2509 2335 """Print to the screen the rewritten form of the user's command.
2510 2336
2511 2337 This shows visual feedback by rewriting input lines that cause
2512 2338 automatic calling to kick in, like::
2513 2339
2514 2340 /f x
2515 2341
2516 2342 into::
2517 2343
2518 2344 ------> f(x)
2519 2345
2520 2346 after the user's input prompt. This helps the user understand that the
2521 2347 input line was transformed automatically by IPython.
2522 2348 """
2523 2349 if not self.show_rewritten_input:
2524 2350 return
2525 2351
2526 2352 rw = self.prompt_manager.render('rewrite') + cmd
2527 2353
2528 2354 try:
2529 2355 # plain ascii works better w/ pyreadline, on some machines, so
2530 2356 # we use it and only print uncolored rewrite if we have unicode
2531 2357 rw = str(rw)
2532 2358 print(rw, file=io.stdout)
2533 2359 except UnicodeEncodeError:
2534 2360 print("------> " + cmd)
2535 2361
2536 2362 #-------------------------------------------------------------------------
2537 2363 # Things related to extracting values/expressions from kernel and user_ns
2538 2364 #-------------------------------------------------------------------------
2539 2365
2540 2366 def _user_obj_error(self):
2541 2367 """return simple exception dict
2542 2368
2543 2369 for use in user_expressions
2544 2370 """
2545 2371
2546 2372 etype, evalue, tb = self._get_exc_info()
2547 2373 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2548 2374
2549 2375 exc_info = {
2550 2376 u'status' : 'error',
2551 2377 u'traceback' : stb,
2552 2378 u'ename' : unicode_type(etype.__name__),
2553 2379 u'evalue' : py3compat.safe_unicode(evalue),
2554 2380 }
2555 2381
2556 2382 return exc_info
2557 2383
2558 2384 def _format_user_obj(self, obj):
2559 2385 """format a user object to display dict
2560 2386
2561 2387 for use in user_expressions
2562 2388 """
2563 2389
2564 2390 data, md = self.display_formatter.format(obj)
2565 2391 value = {
2566 2392 'status' : 'ok',
2567 2393 'data' : data,
2568 2394 'metadata' : md,
2569 2395 }
2570 2396 return value
2571 2397
2572 2398 def user_expressions(self, expressions):
2573 2399 """Evaluate a dict of expressions in the user's namespace.
2574 2400
2575 2401 Parameters
2576 2402 ----------
2577 2403 expressions : dict
2578 2404 A dict with string keys and string values. The expression values
2579 2405 should be valid Python expressions, each of which will be evaluated
2580 2406 in the user namespace.
2581 2407
2582 2408 Returns
2583 2409 -------
2584 2410 A dict, keyed like the input expressions dict, with the rich mime-typed
2585 2411 display_data of each value.
2586 2412 """
2587 2413 out = {}
2588 2414 user_ns = self.user_ns
2589 2415 global_ns = self.user_global_ns
2590 2416
2591 2417 for key, expr in iteritems(expressions):
2592 2418 try:
2593 2419 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2594 2420 except:
2595 2421 value = self._user_obj_error()
2596 2422 out[key] = value
2597 2423 return out
2598 2424
2599 2425 #-------------------------------------------------------------------------
2600 2426 # Things related to the running of code
2601 2427 #-------------------------------------------------------------------------
2602 2428
2603 2429 def ex(self, cmd):
2604 2430 """Execute a normal python statement in user namespace."""
2605 2431 with self.builtin_trap:
2606 2432 exec(cmd, self.user_global_ns, self.user_ns)
2607 2433
2608 2434 def ev(self, expr):
2609 2435 """Evaluate python expression expr in user namespace.
2610 2436
2611 2437 Returns the result of evaluation
2612 2438 """
2613 2439 with self.builtin_trap:
2614 2440 return eval(expr, self.user_global_ns, self.user_ns)
2615 2441
2616 2442 def safe_execfile(self, fname, *where, **kw):
2617 2443 """A safe version of the builtin execfile().
2618 2444
2619 2445 This version will never throw an exception, but instead print
2620 2446 helpful error messages to the screen. This only works on pure
2621 2447 Python files with the .py extension.
2622 2448
2623 2449 Parameters
2624 2450 ----------
2625 2451 fname : string
2626 2452 The name of the file to be executed.
2627 2453 where : tuple
2628 2454 One or two namespaces, passed to execfile() as (globals,locals).
2629 2455 If only one is given, it is passed as both.
2630 2456 exit_ignore : bool (False)
2631 2457 If True, then silence SystemExit for non-zero status (it is always
2632 2458 silenced for zero status, as it is so common).
2633 2459 raise_exceptions : bool (False)
2634 2460 If True raise exceptions everywhere. Meant for testing.
2635 2461 shell_futures : bool (False)
2636 2462 If True, the code will share future statements with the interactive
2637 2463 shell. It will both be affected by previous __future__ imports, and
2638 2464 any __future__ imports in the code will affect the shell. If False,
2639 2465 __future__ imports are not shared in either direction.
2640 2466
2641 2467 """
2642 2468 kw.setdefault('exit_ignore', False)
2643 2469 kw.setdefault('raise_exceptions', False)
2644 2470 kw.setdefault('shell_futures', False)
2645 2471
2646 2472 fname = os.path.abspath(os.path.expanduser(fname))
2647 2473
2648 2474 # Make sure we can open the file
2649 2475 try:
2650 2476 with open(fname) as thefile:
2651 2477 pass
2652 2478 except:
2653 2479 warn('Could not open file <%s> for safe execution.' % fname)
2654 2480 return
2655 2481
2656 2482 # Find things also in current directory. This is needed to mimic the
2657 2483 # behavior of running a script from the system command line, where
2658 2484 # Python inserts the script's directory into sys.path
2659 2485 dname = os.path.dirname(fname)
2660 2486
2661 2487 with prepended_to_syspath(dname):
2662 2488 try:
2663 2489 glob, loc = (where + (None, ))[:2]
2664 2490 py3compat.execfile(
2665 2491 fname, glob, loc,
2666 2492 self.compile if kw['shell_futures'] else None)
2667 2493 except SystemExit as status:
2668 2494 # If the call was made with 0 or None exit status (sys.exit(0)
2669 2495 # or sys.exit() ), don't bother showing a traceback, as both of
2670 2496 # these are considered normal by the OS:
2671 2497 # > python -c'import sys;sys.exit(0)'; echo $?
2672 2498 # 0
2673 2499 # > python -c'import sys;sys.exit()'; echo $?
2674 2500 # 0
2675 2501 # For other exit status, we show the exception unless
2676 2502 # explicitly silenced, but only in short form.
2677 2503 if status.code:
2678 2504 if kw['raise_exceptions']:
2679 2505 raise
2680 2506 if not kw['exit_ignore']:
2681 2507 self.showtraceback(exception_only=True)
2682 2508 except:
2683 2509 if kw['raise_exceptions']:
2684 2510 raise
2685 2511 # tb offset is 2 because we wrap execfile
2686 2512 self.showtraceback(tb_offset=2)
2687 2513
2688 2514 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2689 2515 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2690 2516
2691 2517 Parameters
2692 2518 ----------
2693 2519 fname : str
2694 2520 The name of the file to execute. The filename must have a
2695 2521 .ipy or .ipynb extension.
2696 2522 shell_futures : bool (False)
2697 2523 If True, the code will share future statements with the interactive
2698 2524 shell. It will both be affected by previous __future__ imports, and
2699 2525 any __future__ imports in the code will affect the shell. If False,
2700 2526 __future__ imports are not shared in either direction.
2701 2527 raise_exceptions : bool (False)
2702 2528 If True raise exceptions everywhere. Meant for testing.
2703 2529 """
2704 2530 fname = os.path.abspath(os.path.expanduser(fname))
2705 2531
2706 2532 # Make sure we can open the file
2707 2533 try:
2708 2534 with open(fname) as thefile:
2709 2535 pass
2710 2536 except:
2711 2537 warn('Could not open file <%s> for safe execution.' % fname)
2712 2538 return
2713 2539
2714 2540 # Find things also in current directory. This is needed to mimic the
2715 2541 # behavior of running a script from the system command line, where
2716 2542 # Python inserts the script's directory into sys.path
2717 2543 dname = os.path.dirname(fname)
2718 2544
2719 2545 def get_cells():
2720 2546 """generator for sequence of code blocks to run"""
2721 2547 if fname.endswith('.ipynb'):
2722 2548 from nbformat import read
2723 2549 with io_open(fname) as f:
2724 2550 nb = read(f, as_version=4)
2725 2551 if not nb.cells:
2726 2552 return
2727 2553 for cell in nb.cells:
2728 2554 if cell.cell_type == 'code':
2729 2555 yield cell.source
2730 2556 else:
2731 2557 with open(fname) as f:
2732 2558 yield f.read()
2733 2559
2734 2560 with prepended_to_syspath(dname):
2735 2561 try:
2736 2562 for cell in get_cells():
2737 2563 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2738 2564 if raise_exceptions:
2739 2565 result.raise_error()
2740 2566 elif not result.success:
2741 2567 break
2742 2568 except:
2743 2569 if raise_exceptions:
2744 2570 raise
2745 2571 self.showtraceback()
2746 2572 warn('Unknown failure executing file: <%s>' % fname)
2747 2573
2748 2574 def safe_run_module(self, mod_name, where):
2749 2575 """A safe version of runpy.run_module().
2750 2576
2751 2577 This version will never throw an exception, but instead print
2752 2578 helpful error messages to the screen.
2753 2579
2754 2580 `SystemExit` exceptions with status code 0 or None are ignored.
2755 2581
2756 2582 Parameters
2757 2583 ----------
2758 2584 mod_name : string
2759 2585 The name of the module to be executed.
2760 2586 where : dict
2761 2587 The globals namespace.
2762 2588 """
2763 2589 try:
2764 2590 try:
2765 2591 where.update(
2766 2592 runpy.run_module(str(mod_name), run_name="__main__",
2767 2593 alter_sys=True)
2768 2594 )
2769 2595 except SystemExit as status:
2770 2596 if status.code:
2771 2597 raise
2772 2598 except:
2773 2599 self.showtraceback()
2774 2600 warn('Unknown failure executing module: <%s>' % mod_name)
2775 2601
2776 2602 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2777 2603 """Run a complete IPython cell.
2778 2604
2779 2605 Parameters
2780 2606 ----------
2781 2607 raw_cell : str
2782 2608 The code (including IPython code such as %magic functions) to run.
2783 2609 store_history : bool
2784 2610 If True, the raw and translated cell will be stored in IPython's
2785 2611 history. For user code calling back into IPython's machinery, this
2786 2612 should be set to False.
2787 2613 silent : bool
2788 2614 If True, avoid side-effects, such as implicit displayhooks and
2789 2615 and logging. silent=True forces store_history=False.
2790 2616 shell_futures : bool
2791 2617 If True, the code will share future statements with the interactive
2792 2618 shell. It will both be affected by previous __future__ imports, and
2793 2619 any __future__ imports in the code will affect the shell. If False,
2794 2620 __future__ imports are not shared in either direction.
2795 2621
2796 2622 Returns
2797 2623 -------
2798 2624 result : :class:`ExecutionResult`
2799 2625 """
2800 2626 result = ExecutionResult()
2801 2627
2802 2628 if (not raw_cell) or raw_cell.isspace():
2803 2629 return result
2804 2630
2805 2631 if silent:
2806 2632 store_history = False
2807 2633
2808 2634 if store_history:
2809 2635 result.execution_count = self.execution_count
2810 2636
2811 2637 def error_before_exec(value):
2812 2638 result.error_before_exec = value
2813 2639 return result
2814 2640
2815 2641 self.events.trigger('pre_execute')
2816 2642 if not silent:
2817 2643 self.events.trigger('pre_run_cell')
2818 2644
2819 2645 # If any of our input transformation (input_transformer_manager or
2820 2646 # prefilter_manager) raises an exception, we store it in this variable
2821 2647 # so that we can display the error after logging the input and storing
2822 2648 # it in the history.
2823 2649 preprocessing_exc_tuple = None
2824 2650 try:
2825 2651 # Static input transformations
2826 2652 cell = self.input_transformer_manager.transform_cell(raw_cell)
2827 2653 except SyntaxError:
2828 2654 preprocessing_exc_tuple = sys.exc_info()
2829 2655 cell = raw_cell # cell has to exist so it can be stored/logged
2830 2656 else:
2831 2657 if len(cell.splitlines()) == 1:
2832 2658 # Dynamic transformations - only applied for single line commands
2833 2659 with self.builtin_trap:
2834 2660 try:
2835 2661 # use prefilter_lines to handle trailing newlines
2836 2662 # restore trailing newline for ast.parse
2837 2663 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2838 2664 except Exception:
2839 2665 # don't allow prefilter errors to crash IPython
2840 2666 preprocessing_exc_tuple = sys.exc_info()
2841 2667
2842 2668 # Store raw and processed history
2843 2669 if store_history:
2844 2670 self.history_manager.store_inputs(self.execution_count,
2845 2671 cell, raw_cell)
2846 2672 if not silent:
2847 2673 self.logger.log(cell, raw_cell)
2848 2674
2849 2675 # Display the exception if input processing failed.
2850 2676 if preprocessing_exc_tuple is not None:
2851 2677 self.showtraceback(preprocessing_exc_tuple)
2852 2678 if store_history:
2853 2679 self.execution_count += 1
2854 2680 return error_before_exec(preprocessing_exc_tuple[2])
2855 2681
2856 2682 # Our own compiler remembers the __future__ environment. If we want to
2857 2683 # run code with a separate __future__ environment, use the default
2858 2684 # compiler
2859 2685 compiler = self.compile if shell_futures else CachingCompiler()
2860 2686
2861 2687 with self.builtin_trap:
2862 2688 cell_name = self.compile.cache(cell, self.execution_count)
2863 2689
2864 2690 with self.display_trap:
2865 2691 # Compile to bytecode
2866 2692 try:
2867 2693 code_ast = compiler.ast_parse(cell, filename=cell_name)
2868 2694 except IndentationError as e:
2869 2695 self.showindentationerror()
2870 2696 if store_history:
2871 2697 self.execution_count += 1
2872 2698 return error_before_exec(e)
2873 2699 except (OverflowError, SyntaxError, ValueError, TypeError,
2874 2700 MemoryError) as e:
2875 2701 self.showsyntaxerror()
2876 2702 if store_history:
2877 2703 self.execution_count += 1
2878 2704 return error_before_exec(e)
2879 2705
2880 2706 # Apply AST transformations
2881 2707 try:
2882 2708 code_ast = self.transform_ast(code_ast)
2883 2709 except InputRejected as e:
2884 2710 self.showtraceback()
2885 2711 if store_history:
2886 2712 self.execution_count += 1
2887 2713 return error_before_exec(e)
2888 2714
2889 2715 # Give the displayhook a reference to our ExecutionResult so it
2890 2716 # can fill in the output value.
2891 2717 self.displayhook.exec_result = result
2892 2718
2893 2719 # Execute the user code
2894 2720 interactivity = "none" if silent else self.ast_node_interactivity
2895 2721 self.run_ast_nodes(code_ast.body, cell_name,
2896 2722 interactivity=interactivity, compiler=compiler, result=result)
2897 2723
2898 2724 # Reset this so later displayed values do not modify the
2899 2725 # ExecutionResult
2900 2726 self.displayhook.exec_result = None
2901 2727
2902 2728 self.events.trigger('post_execute')
2903 2729 if not silent:
2904 2730 self.events.trigger('post_run_cell')
2905 2731
2906 2732 if store_history:
2907 2733 # Write output to the database. Does nothing unless
2908 2734 # history output logging is enabled.
2909 2735 self.history_manager.store_output(self.execution_count)
2910 2736 # Each cell is a *single* input, regardless of how many lines it has
2911 2737 self.execution_count += 1
2912 2738
2913 2739 return result
2914 2740
2915 2741 def transform_ast(self, node):
2916 2742 """Apply the AST transformations from self.ast_transformers
2917 2743
2918 2744 Parameters
2919 2745 ----------
2920 2746 node : ast.Node
2921 2747 The root node to be transformed. Typically called with the ast.Module
2922 2748 produced by parsing user input.
2923 2749
2924 2750 Returns
2925 2751 -------
2926 2752 An ast.Node corresponding to the node it was called with. Note that it
2927 2753 may also modify the passed object, so don't rely on references to the
2928 2754 original AST.
2929 2755 """
2930 2756 for transformer in self.ast_transformers:
2931 2757 try:
2932 2758 node = transformer.visit(node)
2933 2759 except InputRejected:
2934 2760 # User-supplied AST transformers can reject an input by raising
2935 2761 # an InputRejected. Short-circuit in this case so that we
2936 2762 # don't unregister the transform.
2937 2763 raise
2938 2764 except Exception:
2939 2765 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2940 2766 self.ast_transformers.remove(transformer)
2941 2767
2942 2768 if self.ast_transformers:
2943 2769 ast.fix_missing_locations(node)
2944 2770 return node
2945 2771
2946 2772
2947 2773 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2948 2774 compiler=compile, result=None):
2949 2775 """Run a sequence of AST nodes. The execution mode depends on the
2950 2776 interactivity parameter.
2951 2777
2952 2778 Parameters
2953 2779 ----------
2954 2780 nodelist : list
2955 2781 A sequence of AST nodes to run.
2956 2782 cell_name : str
2957 2783 Will be passed to the compiler as the filename of the cell. Typically
2958 2784 the value returned by ip.compile.cache(cell).
2959 2785 interactivity : str
2960 2786 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2961 2787 run interactively (displaying output from expressions). 'last_expr'
2962 2788 will run the last node interactively only if it is an expression (i.e.
2963 2789 expressions in loops or other blocks are not displayed. Other values
2964 2790 for this parameter will raise a ValueError.
2965 2791 compiler : callable
2966 2792 A function with the same interface as the built-in compile(), to turn
2967 2793 the AST nodes into code objects. Default is the built-in compile().
2968 2794 result : ExecutionResult, optional
2969 2795 An object to store exceptions that occur during execution.
2970 2796
2971 2797 Returns
2972 2798 -------
2973 2799 True if an exception occurred while running code, False if it finished
2974 2800 running.
2975 2801 """
2976 2802 if not nodelist:
2977 2803 return
2978 2804
2979 2805 if interactivity == 'last_expr':
2980 2806 if isinstance(nodelist[-1], ast.Expr):
2981 2807 interactivity = "last"
2982 2808 else:
2983 2809 interactivity = "none"
2984 2810
2985 2811 if interactivity == 'none':
2986 2812 to_run_exec, to_run_interactive = nodelist, []
2987 2813 elif interactivity == 'last':
2988 2814 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2989 2815 elif interactivity == 'all':
2990 2816 to_run_exec, to_run_interactive = [], nodelist
2991 2817 else:
2992 2818 raise ValueError("Interactivity was %r" % interactivity)
2993 2819
2994 2820 exec_count = self.execution_count
2995 2821
2996 2822 try:
2997 2823 for i, node in enumerate(to_run_exec):
2998 2824 mod = ast.Module([node])
2999 2825 code = compiler(mod, cell_name, "exec")
3000 2826 if self.run_code(code, result):
3001 2827 return True
3002 2828
3003 2829 for i, node in enumerate(to_run_interactive):
3004 2830 mod = ast.Interactive([node])
3005 2831 code = compiler(mod, cell_name, "single")
3006 2832 if self.run_code(code, result):
3007 2833 return True
3008 2834
3009 2835 # Flush softspace
3010 2836 if softspace(sys.stdout, 0):
3011 2837 print()
3012 2838
3013 2839 except:
3014 2840 # It's possible to have exceptions raised here, typically by
3015 2841 # compilation of odd code (such as a naked 'return' outside a
3016 2842 # function) that did parse but isn't valid. Typically the exception
3017 2843 # is a SyntaxError, but it's safest just to catch anything and show
3018 2844 # the user a traceback.
3019 2845
3020 2846 # We do only one try/except outside the loop to minimize the impact
3021 2847 # on runtime, and also because if any node in the node list is
3022 2848 # broken, we should stop execution completely.
3023 2849 if result:
3024 2850 result.error_before_exec = sys.exc_info()[1]
3025 2851 self.showtraceback()
3026 2852 return True
3027 2853
3028 2854 return False
3029 2855
3030 2856 def run_code(self, code_obj, result=None):
3031 2857 """Execute a code object.
3032 2858
3033 2859 When an exception occurs, self.showtraceback() is called to display a
3034 2860 traceback.
3035 2861
3036 2862 Parameters
3037 2863 ----------
3038 2864 code_obj : code object
3039 2865 A compiled code object, to be executed
3040 2866 result : ExecutionResult, optional
3041 2867 An object to store exceptions that occur during execution.
3042 2868
3043 2869 Returns
3044 2870 -------
3045 2871 False : successful execution.
3046 2872 True : an error occurred.
3047 2873 """
3048 2874 # Set our own excepthook in case the user code tries to call it
3049 2875 # directly, so that the IPython crash handler doesn't get triggered
3050 2876 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
3051 2877
3052 2878 # we save the original sys.excepthook in the instance, in case config
3053 2879 # code (such as magics) needs access to it.
3054 2880 self.sys_excepthook = old_excepthook
3055 2881 outflag = 1 # happens in more places, so it's easier as default
3056 2882 try:
3057 2883 try:
3058 2884 self.hooks.pre_run_code_hook()
3059 2885 #rprint('Running code', repr(code_obj)) # dbg
3060 2886 exec(code_obj, self.user_global_ns, self.user_ns)
3061 2887 finally:
3062 2888 # Reset our crash handler in place
3063 2889 sys.excepthook = old_excepthook
3064 2890 except SystemExit as e:
3065 2891 if result is not None:
3066 2892 result.error_in_exec = e
3067 2893 self.showtraceback(exception_only=True)
3068 2894 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
3069 2895 except self.custom_exceptions:
3070 2896 etype, value, tb = sys.exc_info()
3071 2897 if result is not None:
3072 2898 result.error_in_exec = value
3073 2899 self.CustomTB(etype, value, tb)
3074 2900 except:
3075 2901 if result is not None:
3076 2902 result.error_in_exec = sys.exc_info()[1]
3077 2903 self.showtraceback()
3078 2904 else:
3079 2905 outflag = 0
3080 2906 return outflag
3081 2907
3082 2908 # For backwards compatibility
3083 2909 runcode = run_code
3084 2910
3085 2911 #-------------------------------------------------------------------------
3086 2912 # Things related to GUI support and pylab
3087 2913 #-------------------------------------------------------------------------
3088 2914
3089 2915 def enable_gui(self, gui=None):
3090 2916 raise NotImplementedError('Implement enable_gui in a subclass')
3091 2917
3092 2918 def enable_matplotlib(self, gui=None):
3093 2919 """Enable interactive matplotlib and inline figure support.
3094 2920
3095 2921 This takes the following steps:
3096 2922
3097 2923 1. select the appropriate eventloop and matplotlib backend
3098 2924 2. set up matplotlib for interactive use with that backend
3099 2925 3. configure formatters for inline figure display
3100 2926 4. enable the selected gui eventloop
3101 2927
3102 2928 Parameters
3103 2929 ----------
3104 2930 gui : optional, string
3105 2931 If given, dictates the choice of matplotlib GUI backend to use
3106 2932 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3107 2933 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3108 2934 matplotlib (as dictated by the matplotlib build-time options plus the
3109 2935 user's matplotlibrc configuration file). Note that not all backends
3110 2936 make sense in all contexts, for example a terminal ipython can't
3111 2937 display figures inline.
3112 2938 """
3113 2939 from IPython.core import pylabtools as pt
3114 2940 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
3115 2941
3116 2942 if gui != 'inline':
3117 2943 # If we have our first gui selection, store it
3118 2944 if self.pylab_gui_select is None:
3119 2945 self.pylab_gui_select = gui
3120 2946 # Otherwise if they are different
3121 2947 elif gui != self.pylab_gui_select:
3122 2948 print ('Warning: Cannot change to a different GUI toolkit: %s.'
3123 2949 ' Using %s instead.' % (gui, self.pylab_gui_select))
3124 2950 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
3125 2951
3126 2952 pt.activate_matplotlib(backend)
3127 2953 pt.configure_inline_support(self, backend)
3128 2954
3129 2955 # Now we must activate the gui pylab wants to use, and fix %run to take
3130 2956 # plot updates into account
3131 2957 self.enable_gui(gui)
3132 2958 self.magics_manager.registry['ExecutionMagics'].default_runner = \
3133 2959 pt.mpl_runner(self.safe_execfile)
3134 2960
3135 2961 return gui, backend
3136 2962
3137 2963 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
3138 2964 """Activate pylab support at runtime.
3139 2965
3140 2966 This turns on support for matplotlib, preloads into the interactive
3141 2967 namespace all of numpy and pylab, and configures IPython to correctly
3142 2968 interact with the GUI event loop. The GUI backend to be used can be
3143 2969 optionally selected with the optional ``gui`` argument.
3144 2970
3145 2971 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
3146 2972
3147 2973 Parameters
3148 2974 ----------
3149 2975 gui : optional, string
3150 2976 If given, dictates the choice of matplotlib GUI backend to use
3151 2977 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3152 2978 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3153 2979 matplotlib (as dictated by the matplotlib build-time options plus the
3154 2980 user's matplotlibrc configuration file). Note that not all backends
3155 2981 make sense in all contexts, for example a terminal ipython can't
3156 2982 display figures inline.
3157 2983 import_all : optional, bool, default: True
3158 2984 Whether to do `from numpy import *` and `from pylab import *`
3159 2985 in addition to module imports.
3160 2986 welcome_message : deprecated
3161 2987 This argument is ignored, no welcome message will be displayed.
3162 2988 """
3163 2989 from IPython.core.pylabtools import import_pylab
3164 2990
3165 2991 gui, backend = self.enable_matplotlib(gui)
3166 2992
3167 2993 # We want to prevent the loading of pylab to pollute the user's
3168 2994 # namespace as shown by the %who* magics, so we execute the activation
3169 2995 # code in an empty namespace, and we update *both* user_ns and
3170 2996 # user_ns_hidden with this information.
3171 2997 ns = {}
3172 2998 import_pylab(ns, import_all)
3173 2999 # warn about clobbered names
3174 3000 ignored = {"__builtins__"}
3175 3001 both = set(ns).intersection(self.user_ns).difference(ignored)
3176 3002 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3177 3003 self.user_ns.update(ns)
3178 3004 self.user_ns_hidden.update(ns)
3179 3005 return gui, backend, clobbered
3180 3006
3181 3007 #-------------------------------------------------------------------------
3182 3008 # Utilities
3183 3009 #-------------------------------------------------------------------------
3184 3010
3185 3011 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3186 3012 """Expand python variables in a string.
3187 3013
3188 3014 The depth argument indicates how many frames above the caller should
3189 3015 be walked to look for the local namespace where to expand variables.
3190 3016
3191 3017 The global namespace for expansion is always the user's interactive
3192 3018 namespace.
3193 3019 """
3194 3020 ns = self.user_ns.copy()
3195 3021 try:
3196 3022 frame = sys._getframe(depth+1)
3197 3023 except ValueError:
3198 3024 # This is thrown if there aren't that many frames on the stack,
3199 3025 # e.g. if a script called run_line_magic() directly.
3200 3026 pass
3201 3027 else:
3202 3028 ns.update(frame.f_locals)
3203 3029
3204 3030 try:
3205 3031 # We have to use .vformat() here, because 'self' is a valid and common
3206 3032 # name, and expanding **ns for .format() would make it collide with
3207 3033 # the 'self' argument of the method.
3208 3034 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3209 3035 except Exception:
3210 3036 # if formatter couldn't format, just let it go untransformed
3211 3037 pass
3212 3038 return cmd
3213 3039
3214 3040 def mktempfile(self, data=None, prefix='ipython_edit_'):
3215 3041 """Make a new tempfile and return its filename.
3216 3042
3217 3043 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3218 3044 but it registers the created filename internally so ipython cleans it up
3219 3045 at exit time.
3220 3046
3221 3047 Optional inputs:
3222 3048
3223 3049 - data(None): if data is given, it gets written out to the temp file
3224 3050 immediately, and the file is closed again."""
3225 3051
3226 3052 dirname = tempfile.mkdtemp(prefix=prefix)
3227 3053 self.tempdirs.append(dirname)
3228 3054
3229 3055 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3230 3056 os.close(handle) # On Windows, there can only be one open handle on a file
3231 3057 self.tempfiles.append(filename)
3232 3058
3233 3059 if data:
3234 3060 tmp_file = open(filename,'w')
3235 3061 tmp_file.write(data)
3236 3062 tmp_file.close()
3237 3063 return filename
3238 3064
3239 3065 # TODO: This should be removed when Term is refactored.
3240 3066 def write(self,data):
3241 3067 """Write a string to the default output"""
3242 3068 io.stdout.write(data)
3243 3069
3244 3070 # TODO: This should be removed when Term is refactored.
3245 3071 def write_err(self,data):
3246 3072 """Write a string to the default error output"""
3247 3073 io.stderr.write(data)
3248 3074
3249 3075 def ask_yes_no(self, prompt, default=None, interrupt=None):
3250 3076 if self.quiet:
3251 3077 return True
3252 3078 return ask_yes_no(prompt,default,interrupt)
3253 3079
3254 3080 def show_usage(self):
3255 3081 """Show a usage message"""
3256 3082 page.page(IPython.core.usage.interactive_usage)
3257 3083
3258 3084 def extract_input_lines(self, range_str, raw=False):
3259 3085 """Return as a string a set of input history slices.
3260 3086
3261 3087 Parameters
3262 3088 ----------
3263 3089 range_str : string
3264 3090 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3265 3091 since this function is for use by magic functions which get their
3266 3092 arguments as strings. The number before the / is the session
3267 3093 number: ~n goes n back from the current session.
3268 3094
3269 3095 raw : bool, optional
3270 3096 By default, the processed input is used. If this is true, the raw
3271 3097 input history is used instead.
3272 3098
3273 3099 Notes
3274 3100 -----
3275 3101
3276 3102 Slices can be described with two notations:
3277 3103
3278 3104 * ``N:M`` -> standard python form, means including items N...(M-1).
3279 3105 * ``N-M`` -> include items N..M (closed endpoint).
3280 3106 """
3281 3107 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3282 3108 return "\n".join(x for _, _, x in lines)
3283 3109
3284 3110 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3285 3111 """Get a code string from history, file, url, or a string or macro.
3286 3112
3287 3113 This is mainly used by magic functions.
3288 3114
3289 3115 Parameters
3290 3116 ----------
3291 3117
3292 3118 target : str
3293 3119
3294 3120 A string specifying code to retrieve. This will be tried respectively
3295 3121 as: ranges of input history (see %history for syntax), url,
3296 3122 correspnding .py file, filename, or an expression evaluating to a
3297 3123 string or Macro in the user namespace.
3298 3124
3299 3125 raw : bool
3300 3126 If true (default), retrieve raw history. Has no effect on the other
3301 3127 retrieval mechanisms.
3302 3128
3303 3129 py_only : bool (default False)
3304 3130 Only try to fetch python code, do not try alternative methods to decode file
3305 3131 if unicode fails.
3306 3132
3307 3133 Returns
3308 3134 -------
3309 3135 A string of code.
3310 3136
3311 3137 ValueError is raised if nothing is found, and TypeError if it evaluates
3312 3138 to an object of another type. In each case, .args[0] is a printable
3313 3139 message.
3314 3140 """
3315 3141 code = self.extract_input_lines(target, raw=raw) # Grab history
3316 3142 if code:
3317 3143 return code
3318 3144 utarget = unquote_filename(target)
3319 3145 try:
3320 3146 if utarget.startswith(('http://', 'https://')):
3321 3147 return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie)
3322 3148 except UnicodeDecodeError:
3323 3149 if not py_only :
3324 3150 # Deferred import
3325 3151 try:
3326 3152 from urllib.request import urlopen # Py3
3327 3153 except ImportError:
3328 3154 from urllib import urlopen
3329 3155 response = urlopen(target)
3330 3156 return response.read().decode('latin1')
3331 3157 raise ValueError(("'%s' seem to be unreadable.") % utarget)
3332 3158
3333 3159 potential_target = [target]
3334 3160 try :
3335 3161 potential_target.insert(0,get_py_filename(target))
3336 3162 except IOError:
3337 3163 pass
3338 3164
3339 3165 for tgt in potential_target :
3340 3166 if os.path.isfile(tgt): # Read file
3341 3167 try :
3342 3168 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3343 3169 except UnicodeDecodeError :
3344 3170 if not py_only :
3345 3171 with io_open(tgt,'r', encoding='latin1') as f :
3346 3172 return f.read()
3347 3173 raise ValueError(("'%s' seem to be unreadable.") % target)
3348 3174 elif os.path.isdir(os.path.expanduser(tgt)):
3349 3175 raise ValueError("'%s' is a directory, not a regular file." % target)
3350 3176
3351 3177 if search_ns:
3352 3178 # Inspect namespace to load object source
3353 3179 object_info = self.object_inspect(target, detail_level=1)
3354 3180 if object_info['found'] and object_info['source']:
3355 3181 return object_info['source']
3356 3182
3357 3183 try: # User namespace
3358 3184 codeobj = eval(target, self.user_ns)
3359 3185 except Exception:
3360 3186 raise ValueError(("'%s' was not found in history, as a file, url, "
3361 3187 "nor in the user namespace.") % target)
3362 3188
3363 3189 if isinstance(codeobj, string_types):
3364 3190 return codeobj
3365 3191 elif isinstance(codeobj, Macro):
3366 3192 return codeobj.value
3367 3193
3368 3194 raise TypeError("%s is neither a string nor a macro." % target,
3369 3195 codeobj)
3370 3196
3371 3197 #-------------------------------------------------------------------------
3372 3198 # Things related to IPython exiting
3373 3199 #-------------------------------------------------------------------------
3374 3200 def atexit_operations(self):
3375 3201 """This will be executed at the time of exit.
3376 3202
3377 3203 Cleanup operations and saving of persistent data that is done
3378 3204 unconditionally by IPython should be performed here.
3379 3205
3380 3206 For things that may depend on startup flags or platform specifics (such
3381 3207 as having readline or not), register a separate atexit function in the
3382 3208 code that has the appropriate information, rather than trying to
3383 3209 clutter
3384 3210 """
3385 3211 # Close the history session (this stores the end time and line count)
3386 3212 # this must be *before* the tempfile cleanup, in case of temporary
3387 3213 # history db
3388 3214 self.history_manager.end_session()
3389 3215
3390 3216 # Cleanup all tempfiles and folders left around
3391 3217 for tfile in self.tempfiles:
3392 3218 try:
3393 3219 os.unlink(tfile)
3394 3220 except OSError:
3395 3221 pass
3396 3222
3397 3223 for tdir in self.tempdirs:
3398 3224 try:
3399 3225 os.rmdir(tdir)
3400 3226 except OSError:
3401 3227 pass
3402 3228
3403 3229 # Clear all user namespaces to release all references cleanly.
3404 3230 self.reset(new_session=False)
3405 3231
3406 3232 # Run user hooks
3407 3233 self.hooks.shutdown_hook()
3408 3234
3409 3235 def cleanup(self):
3410 3236 self.restore_sys_module_state()
3411 3237
3412 3238
3413 3239 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3414 3240 """An abstract base class for InteractiveShell."""
3415 3241
3416 3242 InteractiveShellABC.register(InteractiveShell)
@@ -1,640 +1,807 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Subclass of InteractiveShell for terminal based frontends."""
3 3
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2011 The IPython Development Team
8 #
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
12
13 #-----------------------------------------------------------------------------
14 # Imports
15 #-----------------------------------------------------------------------------
4 # Copyright (c) IPython Development Team.
5 # Distributed under the terms of the Modified BSD License.
6
16 7 from __future__ import print_function
17 8
18 9 import bdb
19 10 import os
20 11 import sys
21 12
22 13 from IPython.core.error import TryNext, UsageError
23 14 from IPython.core.usage import interactive_usage
24 from IPython.core.inputsplitter import IPythonInputSplitter
15 from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC
25 16 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
26 17 from IPython.core.magic import Magics, magics_class, line_magic
27 18 from IPython.lib.clipboard import ClipboardEmpty
19 from IPython.utils.contexts import NoOpContext
20 from IPython.utils.decorators import undoc
28 21 from IPython.utils.encoding import get_stream_enc
29 22 from IPython.utils import py3compat
30 23 from IPython.utils.terminal import toggle_set_term_title, set_term_title
31 24 from IPython.utils.process import abbrev_cwd
32 25 from IPython.utils.warn import warn, error
33 26 from IPython.utils.text import num_ini_spaces, SList, strip_email_quotes
34 27 from traitlets import Integer, CBool, Unicode
35 28
36 #-----------------------------------------------------------------------------
37 # Utilities
38 #-----------------------------------------------------------------------------
39 29
40 30 def get_default_editor():
41 31 try:
42 32 ed = os.environ['EDITOR']
43 33 if not py3compat.PY3:
44 34 ed = ed.decode()
45 35 return ed
46 36 except KeyError:
47 37 pass
48 38 except UnicodeError:
49 39 warn("$EDITOR environment variable is not pure ASCII. Using platform "
50 40 "default editor.")
51 41
52 42 if os.name == 'posix':
53 43 return 'vi' # the only one guaranteed to be there!
54 44 else:
55 45 return 'notepad' # same in Windows!
56 46
57 47 def get_pasted_lines(sentinel, l_input=py3compat.input, quiet=False):
58 48 """ Yield pasted lines until the user enters the given sentinel value.
59 49 """
60 50 if not quiet:
61 51 print("Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \
62 52 % sentinel)
63 53 prompt = ":"
64 54 else:
65 55 prompt = ""
66 56 while True:
67 57 try:
68 58 l = py3compat.str_to_unicode(l_input(prompt))
69 59 if l == sentinel:
70 60 return
71 61 else:
72 62 yield l
73 63 except EOFError:
74 64 print('<EOF>')
75 65 return
76 66
67 @undoc
68 def no_op(*a, **kw): pass
69
70
71 class ReadlineNoRecord(object):
72 """Context manager to execute some code, then reload readline history
73 so that interactive input to the code doesn't appear when pressing up."""
74 def __init__(self, shell):
75 self.shell = shell
76 self._nested_level = 0
77
78 def __enter__(self):
79 if self._nested_level == 0:
80 try:
81 self.orig_length = self.current_length()
82 self.readline_tail = self.get_readline_tail()
83 except (AttributeError, IndexError): # Can fail with pyreadline
84 self.orig_length, self.readline_tail = 999999, []
85 self._nested_level += 1
86
87 def __exit__(self, type, value, traceback):
88 self._nested_level -= 1
89 if self._nested_level == 0:
90 # Try clipping the end if it's got longer
91 try:
92 e = self.current_length() - self.orig_length
93 if e > 0:
94 for _ in range(e):
95 self.shell.readline.remove_history_item(self.orig_length)
96
97 # If it still doesn't match, just reload readline history.
98 if self.current_length() != self.orig_length \
99 or self.get_readline_tail() != self.readline_tail:
100 self.shell.refill_readline_hist()
101 except (AttributeError, IndexError):
102 pass
103 # Returning False will cause exceptions to propagate
104 return False
105
106 def current_length(self):
107 return self.shell.readline.get_current_history_length()
108
109 def get_readline_tail(self, n=10):
110 """Get the last n items in readline history."""
111 end = self.shell.readline.get_current_history_length() + 1
112 start = max(end-n, 1)
113 ghi = self.shell.readline.get_history_item
114 return [ghi(x) for x in range(start, end)]
77 115
78 #------------------------------------------------------------------------
79 # Terminal-specific magics
80 #------------------------------------------------------------------------
81 116
82 117 @magics_class
83 118 class TerminalMagics(Magics):
84 119 def __init__(self, shell):
85 120 super(TerminalMagics, self).__init__(shell)
86 121 self.input_splitter = IPythonInputSplitter()
87 122
88 123 def store_or_execute(self, block, name):
89 124 """ Execute a block, or store it in a variable, per the user's request.
90 125 """
91 126 if name:
92 127 # If storing it for further editing
93 128 self.shell.user_ns[name] = SList(block.splitlines())
94 129 print("Block assigned to '%s'" % name)
95 130 else:
96 131 b = self.preclean_input(block)
97 132 self.shell.user_ns['pasted_block'] = b
98 133 self.shell.using_paste_magics = True
99 134 try:
100 135 self.shell.run_cell(b)
101 136 finally:
102 137 self.shell.using_paste_magics = False
103 138
104 139 def preclean_input(self, block):
105 140 lines = block.splitlines()
106 141 while lines and not lines[0].strip():
107 142 lines = lines[1:]
108 143 return strip_email_quotes('\n'.join(lines))
109 144
110 145 def rerun_pasted(self, name='pasted_block'):
111 146 """ Rerun a previously pasted command.
112 147 """
113 148 b = self.shell.user_ns.get(name)
114 149
115 150 # Sanity checks
116 151 if b is None:
117 152 raise UsageError('No previous pasted block available')
118 153 if not isinstance(b, py3compat.string_types):
119 154 raise UsageError(
120 155 "Variable 'pasted_block' is not a string, can't execute")
121 156
122 157 print("Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)))
123 158 self.shell.run_cell(b)
124 159
125 160 @line_magic
126 161 def autoindent(self, parameter_s = ''):
127 162 """Toggle autoindent on/off (if available)."""
128 163
129 164 self.shell.set_autoindent()
130 165 print("Automatic indentation is:",['OFF','ON'][self.shell.autoindent])
131 166
132 167 @line_magic
133 168 def cpaste(self, parameter_s=''):
134 169 """Paste & execute a pre-formatted code block from clipboard.
135 170
136 171 You must terminate the block with '--' (two minus-signs) or Ctrl-D
137 172 alone on the line. You can also provide your own sentinel with '%paste
138 173 -s %%' ('%%' is the new sentinel for this operation).
139 174
140 175 The block is dedented prior to execution to enable execution of method
141 176 definitions. '>' and '+' characters at the beginning of a line are
142 177 ignored, to allow pasting directly from e-mails, diff files and
143 178 doctests (the '...' continuation prompt is also stripped). The
144 179 executed block is also assigned to variable named 'pasted_block' for
145 180 later editing with '%edit pasted_block'.
146 181
147 182 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
148 183 This assigns the pasted block to variable 'foo' as string, without
149 184 dedenting or executing it (preceding >>> and + is still stripped)
150 185
151 186 '%cpaste -r' re-executes the block previously entered by cpaste.
152 187 '%cpaste -q' suppresses any additional output messages.
153 188
154 189 Do not be alarmed by garbled output on Windows (it's a readline bug).
155 190 Just press enter and type -- (and press enter again) and the block
156 191 will be what was just pasted.
157 192
158 193 IPython statements (magics, shell escapes) are not supported (yet).
159 194
160 195 See also
161 196 --------
162 197 paste: automatically pull code from clipboard.
163 198
164 199 Examples
165 200 --------
166 201 ::
167 202
168 203 In [8]: %cpaste
169 204 Pasting code; enter '--' alone on the line to stop.
170 205 :>>> a = ["world!", "Hello"]
171 206 :>>> print " ".join(sorted(a))
172 207 :--
173 208 Hello world!
174 209 """
175 210 opts, name = self.parse_options(parameter_s, 'rqs:', mode='string')
176 211 if 'r' in opts:
177 212 self.rerun_pasted()
178 213 return
179 214
180 215 quiet = ('q' in opts)
181 216
182 217 sentinel = opts.get('s', u'--')
183 218 block = '\n'.join(get_pasted_lines(sentinel, quiet=quiet))
184 219 self.store_or_execute(block, name)
185 220
186 221 @line_magic
187 222 def paste(self, parameter_s=''):
188 223 """Paste & execute a pre-formatted code block from clipboard.
189 224
190 225 The text is pulled directly from the clipboard without user
191 226 intervention and printed back on the screen before execution (unless
192 227 the -q flag is given to force quiet mode).
193 228
194 229 The block is dedented prior to execution to enable execution of method
195 230 definitions. '>' and '+' characters at the beginning of a line are
196 231 ignored, to allow pasting directly from e-mails, diff files and
197 232 doctests (the '...' continuation prompt is also stripped). The
198 233 executed block is also assigned to variable named 'pasted_block' for
199 234 later editing with '%edit pasted_block'.
200 235
201 236 You can also pass a variable name as an argument, e.g. '%paste foo'.
202 237 This assigns the pasted block to variable 'foo' as string, without
203 238 executing it (preceding >>> and + is still stripped).
204 239
205 240 Options:
206 241
207 242 -r: re-executes the block previously entered by cpaste.
208 243
209 244 -q: quiet mode: do not echo the pasted text back to the terminal.
210 245
211 246 IPython statements (magics, shell escapes) are not supported (yet).
212 247
213 248 See also
214 249 --------
215 250 cpaste: manually paste code into terminal until you mark its end.
216 251 """
217 252 opts, name = self.parse_options(parameter_s, 'rq', mode='string')
218 253 if 'r' in opts:
219 254 self.rerun_pasted()
220 255 return
221 256 try:
222 257 block = self.shell.hooks.clipboard_get()
223 258 except TryNext as clipboard_exc:
224 259 message = getattr(clipboard_exc, 'args')
225 260 if message:
226 261 error(message[0])
227 262 else:
228 263 error('Could not get text from the clipboard.')
229 264 return
230 265 except ClipboardEmpty:
231 266 raise UsageError("The clipboard appears to be empty")
232 267
233 268 # By default, echo back to terminal unless quiet mode is requested
234 269 if 'q' not in opts:
235 270 write = self.shell.write
236 271 write(self.shell.pycolorize(block))
237 272 if not block.endswith('\n'):
238 273 write('\n')
239 274 write("## -- End pasted text --\n")
240 275
241 276 self.store_or_execute(block, name)
242 277
243 278 # Class-level: add a '%cls' magic only on Windows
244 279 if sys.platform == 'win32':
245 280 @line_magic
246 281 def cls(self, s):
247 282 """Clear screen.
248 283 """
249 284 os.system("cls")
250 285
251 #-----------------------------------------------------------------------------
252 # Main class
253 #-----------------------------------------------------------------------------
254 286
255 287 class TerminalInteractiveShell(InteractiveShell):
256 288
257 289 autoedit_syntax = CBool(False, config=True,
258 290 help="auto editing of files with syntax errors.")
259 291 confirm_exit = CBool(True, config=True,
260 292 help="""
261 293 Set to confirm when you try to exit IPython with an EOF (Control-D
262 294 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
263 295 you can force a direct exit without any confirmation.""",
264 296 )
265 297 # This display_banner only controls whether or not self.show_banner()
266 298 # is called when mainloop/interact are called. The default is False
267 299 # because for the terminal based application, the banner behavior
268 300 # is controlled by the application.
269 301 display_banner = CBool(False) # This isn't configurable!
270 302 embedded = CBool(False)
271 303 embedded_active = CBool(False)
272 304 editor = Unicode(get_default_editor(), config=True,
273 305 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
274 306 )
275 307 pager = Unicode('less', config=True,
276 308 help="The shell program to be used for paging.")
277 309
278 310 screen_length = Integer(0, config=True,
279 311 help=
280 312 """Number of lines of your screen, used to control printing of very
281 313 long strings. Strings longer than this number of lines will be sent
282 314 through a pager instead of directly printed. The default value for
283 315 this is 0, which means IPython will auto-detect your screen size every
284 316 time it needs to print certain potentially long strings (this doesn't
285 317 change the behavior of the 'print' keyword, it's only triggered
286 318 internally). If for some reason this isn't working well (it needs
287 319 curses support), specify it yourself. Otherwise don't change the
288 320 default.""",
289 321 )
290 322 term_title = CBool(False, config=True,
291 323 help="Enable auto setting the terminal title."
292 324 )
293 325 usage = Unicode(interactive_usage)
294 326
295 327 # This `using_paste_magics` is used to detect whether the code is being
296 328 # executed via paste magics functions
297 329 using_paste_magics = CBool(False)
298 330
299 331 # In the terminal, GUI control is done via PyOS_InputHook
300 332 @staticmethod
301 333 def enable_gui(gui=None, app=None):
302 334 """Switch amongst GUI input hooks by name.
303 335 """
304 336 # Deferred import
305 337 from IPython.lib.inputhook import enable_gui as real_enable_gui
306 338 try:
307 339 return real_enable_gui(gui, app)
308 340 except ValueError as e:
309 341 raise UsageError("%s" % e)
310 342
311 343 system = InteractiveShell.system_raw
312 344
313 345 #-------------------------------------------------------------------------
314 346 # Overrides of init stages
315 347 #-------------------------------------------------------------------------
316 348
317 349 def init_display_formatter(self):
318 350 super(TerminalInteractiveShell, self).init_display_formatter()
319 351 # terminal only supports plaintext
320 352 self.display_formatter.active_types = ['text/plain']
321 353
322 354 #-------------------------------------------------------------------------
355 # Things related to readline
356 #-------------------------------------------------------------------------
357
358 def init_readline(self):
359 """Command history completion/saving/reloading."""
360
361 if self.readline_use:
362 import IPython.utils.rlineimpl as readline
363
364 self.rl_next_input = None
365 self.rl_do_indent = False
366
367 if not self.readline_use or not readline.have_readline:
368 self.readline = None
369 # Set a number of methods that depend on readline to be no-op
370 self.readline_no_record = NoOpContext()
371 self.set_readline_completer = no_op
372 self.set_custom_completer = no_op
373 if self.readline_use:
374 warn('Readline services not available or not loaded.')
375 else:
376 self.has_readline = True
377 self.readline = readline
378 sys.modules['readline'] = readline
379
380 # Platform-specific configuration
381 if os.name == 'nt':
382 # FIXME - check with Frederick to see if we can harmonize
383 # naming conventions with pyreadline to avoid this
384 # platform-dependent check
385 self.readline_startup_hook = readline.set_pre_input_hook
386 else:
387 self.readline_startup_hook = readline.set_startup_hook
388
389 # Readline config order:
390 # - IPython config (default value)
391 # - custom inputrc
392 # - IPython config (user customized)
393
394 # load IPython config before inputrc if default
395 # skip if libedit because parse_and_bind syntax is different
396 if not self._custom_readline_config and not readline.uses_libedit:
397 for rlcommand in self.readline_parse_and_bind:
398 readline.parse_and_bind(rlcommand)
399
400 # Load user's initrc file (readline config)
401 # Or if libedit is used, load editrc.
402 inputrc_name = os.environ.get('INPUTRC')
403 if inputrc_name is None:
404 inputrc_name = '.inputrc'
405 if readline.uses_libedit:
406 inputrc_name = '.editrc'
407 inputrc_name = os.path.join(self.home_dir, inputrc_name)
408 if os.path.isfile(inputrc_name):
409 try:
410 readline.read_init_file(inputrc_name)
411 except:
412 warn('Problems reading readline initialization file <%s>'
413 % inputrc_name)
414
415 # load IPython config after inputrc if user has customized
416 if self._custom_readline_config:
417 for rlcommand in self.readline_parse_and_bind:
418 readline.parse_and_bind(rlcommand)
419
420 # Remove some chars from the delimiters list. If we encounter
421 # unicode chars, discard them.
422 delims = readline.get_completer_delims()
423 if not py3compat.PY3:
424 delims = delims.encode("ascii", "ignore")
425 for d in self.readline_remove_delims:
426 delims = delims.replace(d, "")
427 delims = delims.replace(ESC_MAGIC, '')
428 readline.set_completer_delims(delims)
429 # Store these so we can restore them if something like rpy2 modifies
430 # them.
431 self.readline_delims = delims
432 # otherwise we end up with a monster history after a while:
433 readline.set_history_length(self.history_length)
434
435 self.refill_readline_hist()
436 self.readline_no_record = ReadlineNoRecord(self)
437
438 # Configure auto-indent for all platforms
439 self.set_autoindent(self.autoindent)
440
441 def init_completer(self):
442 super(TerminalInteractiveShell, self).init_completer()
443
444 # Only configure readline if we truly are using readline.
445 if self.has_readline:
446 self.set_readline_completer()
447
448 def set_readline_completer(self):
449 """Reset readline's completer to be our own."""
450 self.readline.set_completer(self.Completer.rlcomplete)
451
452
453 def pre_readline(self):
454 """readline hook to be used at the start of each line.
455
456 It handles auto-indent and text from set_next_input."""
457
458 if self.rl_do_indent:
459 self.readline.insert_text(self._indent_current_str())
460 if self.rl_next_input is not None:
461 self.readline.insert_text(self.rl_next_input)
462 self.rl_next_input = None
463
464 def refill_readline_hist(self):
465 # Load the last 1000 lines from history
466 self.readline.clear_history()
467 stdin_encoding = sys.stdin.encoding or "utf-8"
468 last_cell = u""
469 for _, _, cell in self.history_manager.get_tail(self.history_load_length,
470 include_latest=True):
471 # Ignore blank lines and consecutive duplicates
472 cell = cell.rstrip()
473 if cell and (cell != last_cell):
474 try:
475 if self.multiline_history:
476 self.readline.add_history(py3compat.unicode_to_str(cell,
477 stdin_encoding))
478 else:
479 for line in cell.splitlines():
480 self.readline.add_history(py3compat.unicode_to_str(line,
481 stdin_encoding))
482 last_cell = cell
483
484 except TypeError:
485 # The history DB can get corrupted so it returns strings
486 # containing null bytes, which readline objects to.
487 continue
488
489 #-------------------------------------------------------------------------
323 490 # Things related to the terminal
324 491 #-------------------------------------------------------------------------
325 492
326 493 @property
327 494 def usable_screen_length(self):
328 495 if self.screen_length == 0:
329 496 return 0
330 497 else:
331 498 num_lines_bot = self.separate_in.count('\n')+1
332 499 return self.screen_length - num_lines_bot
333 500
334 501 def _term_title_changed(self, name, new_value):
335 502 self.init_term_title()
336 503
337 504 def init_term_title(self):
338 505 # Enable or disable the terminal title.
339 506 if self.term_title:
340 507 toggle_set_term_title(True)
341 508 set_term_title('IPython: ' + abbrev_cwd())
342 509 else:
343 510 toggle_set_term_title(False)
344 511
345 512 #-------------------------------------------------------------------------
346 513 # Things related to aliases
347 514 #-------------------------------------------------------------------------
348 515
349 516 def init_alias(self):
350 517 # The parent class defines aliases that can be safely used with any
351 518 # frontend.
352 519 super(TerminalInteractiveShell, self).init_alias()
353 520
354 521 # Now define aliases that only make sense on the terminal, because they
355 522 # need direct access to the console in a way that we can't emulate in
356 523 # GUI or web frontend
357 524 if os.name == 'posix':
358 525 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
359 526 ('man', 'man')]
360 527 else :
361 528 aliases = []
362 529
363 530 for name, cmd in aliases:
364 531 self.alias_manager.soft_define_alias(name, cmd)
365 532
366 533 #-------------------------------------------------------------------------
367 534 # Mainloop and code execution logic
368 535 #-------------------------------------------------------------------------
369 536
370 537 def mainloop(self, display_banner=None):
371 538 """Start the mainloop.
372 539
373 540 If an optional banner argument is given, it will override the
374 541 internally created default banner.
375 542 """
376 543
377 544 with self.builtin_trap, self.display_trap:
378 545
379 546 while 1:
380 547 try:
381 548 self.interact(display_banner=display_banner)
382 549 #self.interact_with_readline()
383 550 # XXX for testing of a readline-decoupled repl loop, call
384 551 # interact_with_readline above
385 552 break
386 553 except KeyboardInterrupt:
387 554 # this should not be necessary, but KeyboardInterrupt
388 555 # handling seems rather unpredictable...
389 556 self.write("\nKeyboardInterrupt in interact()\n")
390 557
391 558 def _replace_rlhist_multiline(self, source_raw, hlen_before_cell):
392 559 """Store multiple lines as a single entry in history"""
393 560
394 561 # do nothing without readline or disabled multiline
395 562 if not self.has_readline or not self.multiline_history:
396 563 return hlen_before_cell
397 564
398 565 # windows rl has no remove_history_item
399 566 if not hasattr(self.readline, "remove_history_item"):
400 567 return hlen_before_cell
401 568
402 569 # skip empty cells
403 570 if not source_raw.rstrip():
404 571 return hlen_before_cell
405 572
406 573 # nothing changed do nothing, e.g. when rl removes consecutive dups
407 574 hlen = self.readline.get_current_history_length()
408 575 if hlen == hlen_before_cell:
409 576 return hlen_before_cell
410 577
411 578 for i in range(hlen - hlen_before_cell):
412 579 self.readline.remove_history_item(hlen - i - 1)
413 580 stdin_encoding = get_stream_enc(sys.stdin, 'utf-8')
414 581 self.readline.add_history(py3compat.unicode_to_str(source_raw.rstrip(),
415 582 stdin_encoding))
416 583 return self.readline.get_current_history_length()
417 584
418 585 def interact(self, display_banner=None):
419 586 """Closely emulate the interactive Python console."""
420 587
421 588 # batch run -> do not interact
422 589 if self.exit_now:
423 590 return
424 591
425 592 if display_banner is None:
426 593 display_banner = self.display_banner
427 594
428 595 if isinstance(display_banner, py3compat.string_types):
429 596 self.show_banner(display_banner)
430 597 elif display_banner:
431 598 self.show_banner()
432 599
433 600 more = False
434 601
435 602 if self.has_readline:
436 603 self.readline_startup_hook(self.pre_readline)
437 604 hlen_b4_cell = self.readline.get_current_history_length()
438 605 else:
439 606 hlen_b4_cell = 0
440 607 # exit_now is set by a call to %Exit or %Quit, through the
441 608 # ask_exit callback.
442 609
443 610 while not self.exit_now:
444 611 self.hooks.pre_prompt_hook()
445 612 if more:
446 613 try:
447 614 prompt = self.prompt_manager.render('in2')
448 615 except:
449 616 self.showtraceback()
450 617 if self.autoindent:
451 618 self.rl_do_indent = True
452 619
453 620 else:
454 621 try:
455 622 prompt = self.separate_in + self.prompt_manager.render('in')
456 623 except:
457 624 self.showtraceback()
458 625 try:
459 626 line = self.raw_input(prompt)
460 627 if self.exit_now:
461 628 # quick exit on sys.std[in|out] close
462 629 break
463 630 if self.autoindent:
464 631 self.rl_do_indent = False
465 632
466 633 except KeyboardInterrupt:
467 634 #double-guard against keyboardinterrupts during kbdint handling
468 635 try:
469 636 self.write('\n' + self.get_exception_only())
470 637 source_raw = self.input_splitter.raw_reset()
471 638 hlen_b4_cell = \
472 639 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
473 640 more = False
474 641 except KeyboardInterrupt:
475 642 pass
476 643 except EOFError:
477 644 if self.autoindent:
478 645 self.rl_do_indent = False
479 646 if self.has_readline:
480 647 self.readline_startup_hook(None)
481 648 self.write('\n')
482 649 self.exit()
483 650 except bdb.BdbQuit:
484 651 warn('The Python debugger has exited with a BdbQuit exception.\n'
485 652 'Because of how pdb handles the stack, it is impossible\n'
486 653 'for IPython to properly format this particular exception.\n'
487 654 'IPython will resume normal operation.')
488 655 except:
489 656 # exceptions here are VERY RARE, but they can be triggered
490 657 # asynchronously by signal handlers, for example.
491 658 self.showtraceback()
492 659 else:
493 660 try:
494 661 self.input_splitter.push(line)
495 662 more = self.input_splitter.push_accepts_more()
496 663 except SyntaxError:
497 664 # Run the code directly - run_cell takes care of displaying
498 665 # the exception.
499 666 more = False
500 667 if (self.SyntaxTB.last_syntax_error and
501 668 self.autoedit_syntax):
502 669 self.edit_syntax_error()
503 670 if not more:
504 671 source_raw = self.input_splitter.raw_reset()
505 672 self.run_cell(source_raw, store_history=True)
506 673 hlen_b4_cell = \
507 674 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
508 675
509 676 # Turn off the exit flag, so the mainloop can be restarted if desired
510 677 self.exit_now = False
511 678
512 679 def raw_input(self, prompt=''):
513 680 """Write a prompt and read a line.
514 681
515 682 The returned line does not include the trailing newline.
516 683 When the user enters the EOF key sequence, EOFError is raised.
517 684
518 685 Parameters
519 686 ----------
520 687
521 688 prompt : str, optional
522 689 A string to be printed to prompt the user.
523 690 """
524 691 # raw_input expects str, but we pass it unicode sometimes
525 692 prompt = py3compat.cast_bytes_py2(prompt)
526 693
527 694 try:
528 695 line = py3compat.cast_unicode_py2(self.raw_input_original(prompt))
529 696 except ValueError:
530 697 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
531 698 " or sys.stdout.close()!\nExiting IPython!\n")
532 699 self.ask_exit()
533 700 return ""
534 701
535 702 # Try to be reasonably smart about not re-indenting pasted input more
536 703 # than necessary. We do this by trimming out the auto-indent initial
537 704 # spaces, if the user's actual input started itself with whitespace.
538 705 if self.autoindent:
539 706 if num_ini_spaces(line) > self.indent_current_nsp:
540 707 line = line[self.indent_current_nsp:]
541 708 self.indent_current_nsp = 0
542 709
543 710 return line
544 711
545 712 #-------------------------------------------------------------------------
546 713 # Methods to support auto-editing of SyntaxErrors.
547 714 #-------------------------------------------------------------------------
548 715
549 716 def edit_syntax_error(self):
550 717 """The bottom half of the syntax error handler called in the main loop.
551 718
552 719 Loop until syntax error is fixed or user cancels.
553 720 """
554 721
555 722 while self.SyntaxTB.last_syntax_error:
556 723 # copy and clear last_syntax_error
557 724 err = self.SyntaxTB.clear_err_state()
558 725 if not self._should_recompile(err):
559 726 return
560 727 try:
561 728 # may set last_syntax_error again if a SyntaxError is raised
562 729 self.safe_execfile(err.filename,self.user_ns)
563 730 except:
564 731 self.showtraceback()
565 732 else:
566 733 try:
567 734 f = open(err.filename)
568 735 try:
569 736 # This should be inside a display_trap block and I
570 737 # think it is.
571 738 sys.displayhook(f.read())
572 739 finally:
573 740 f.close()
574 741 except:
575 742 self.showtraceback()
576 743
577 744 def _should_recompile(self,e):
578 745 """Utility routine for edit_syntax_error"""
579 746
580 747 if e.filename in ('<ipython console>','<input>','<string>',
581 748 '<console>','<BackgroundJob compilation>',
582 749 None):
583 750
584 751 return False
585 752 try:
586 753 if (self.autoedit_syntax and
587 754 not self.ask_yes_no('Return to editor to correct syntax error? '
588 755 '[Y/n] ','y')):
589 756 return False
590 757 except EOFError:
591 758 return False
592 759
593 760 def int0(x):
594 761 try:
595 762 return int(x)
596 763 except TypeError:
597 764 return 0
598 765 # always pass integer line and offset values to editor hook
599 766 try:
600 767 self.hooks.fix_error_editor(e.filename,
601 768 int0(e.lineno),int0(e.offset),e.msg)
602 769 except TryNext:
603 770 warn('Could not open editor')
604 771 return False
605 772 return True
606 773
607 774 #-------------------------------------------------------------------------
608 775 # Things related to exiting
609 776 #-------------------------------------------------------------------------
610 777
611 778 def ask_exit(self):
612 779 """ Ask the shell to exit. Can be overiden and used as a callback. """
613 780 self.exit_now = True
614 781
615 782 def exit(self):
616 783 """Handle interactive exit.
617 784
618 785 This method calls the ask_exit callback."""
619 786 if self.confirm_exit:
620 787 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
621 788 self.ask_exit()
622 789 else:
623 790 self.ask_exit()
624 791
625 792 #-------------------------------------------------------------------------
626 793 # Things related to magics
627 794 #-------------------------------------------------------------------------
628 795
629 796 def init_magics(self):
630 797 super(TerminalInteractiveShell, self).init_magics()
631 798 self.register_magics(TerminalMagics)
632 799
633 800 def showindentationerror(self):
634 801 super(TerminalInteractiveShell, self).showindentationerror()
635 802 if not self.using_paste_magics:
636 803 print("If you want to paste code into IPython, try the "
637 804 "%paste and %cpaste magic functions.")
638 805
639 806
640 807 InteractiveShellABC.register(TerminalInteractiveShell)
@@ -1,71 +1,64 b''
1 1 # encoding: utf-8
2 """Miscellaneous context managers.
2 3 """
3 Context managers for temporarily updating dictionaries.
4 4
5 Authors:
6
7 * Bradley Froehle
8 """
9
10 #-----------------------------------------------------------------------------
11 # Copyright (C) 2012 The IPython Development Team
12 #
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
15 #-----------------------------------------------------------------------------
16
17 #-----------------------------------------------------------------------------
18 # Code
19 #-----------------------------------------------------------------------------
5 # Copyright (c) IPython Development Team.
6 # Distributed under the terms of the Modified BSD License.
20 7
21 8 class preserve_keys(object):
22 9 """Preserve a set of keys in a dictionary.
23 10
24 11 Upon entering the context manager the current values of the keys
25 12 will be saved. Upon exiting, the dictionary will be updated to
26 13 restore the original value of the preserved keys. Preserved keys
27 14 which did not exist when entering the context manager will be
28 15 deleted.
29 16
30 17 Examples
31 18 --------
32 19
33 20 >>> d = {'a': 1, 'b': 2, 'c': 3}
34 21 >>> with preserve_keys(d, 'b', 'c', 'd'):
35 22 ... del d['a']
36 23 ... del d['b'] # will be reset to 2
37 24 ... d['c'] = None # will be reset to 3
38 25 ... d['d'] = 4 # will be deleted
39 26 ... d['e'] = 5
40 27 ... print(sorted(d.items()))
41 28 ...
42 29 [('c', None), ('d', 4), ('e', 5)]
43 30 >>> print(sorted(d.items()))
44 31 [('b', 2), ('c', 3), ('e', 5)]
45 32 """
46 33
47 34 def __init__(self, dictionary, *keys):
48 35 self.dictionary = dictionary
49 36 self.keys = keys
50 37
51 38 def __enter__(self):
52 39 # Actions to perform upon exiting.
53 40 to_delete = []
54 41 to_update = {}
55 42
56 43 d = self.dictionary
57 44 for k in self.keys:
58 45 if k in d:
59 46 to_update[k] = d[k]
60 47 else:
61 48 to_delete.append(k)
62 49
63 50 self.to_delete = to_delete
64 51 self.to_update = to_update
65 52
66 53 def __exit__(self, *exc_info):
67 54 d = self.dictionary
68 55
69 56 for k in self.to_delete:
70 57 d.pop(k, None)
71 58 d.update(self.to_update)
59
60
61 class NoOpContext(object):
62 """Context manager that does nothing."""
63 def __enter__(self): pass
64 def __exit__(self, type, value, traceback): pass
General Comments 0
You need to be logged in to leave comments. Login now