##// END OF EJS Templates
remove rest of readline, pass II
Matthias Bussonnier -
Show More
@@ -1,3253 +1,3241 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 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.debugger import Pdb
46 46 from IPython.core.display_trap import DisplayTrap
47 47 from IPython.core.displayhook import DisplayHook
48 48 from IPython.core.displaypub import DisplayPublisher
49 49 from IPython.core.error import InputRejected, UsageError
50 50 from IPython.core.extensions import ExtensionManager
51 51 from IPython.core.formatters import DisplayFormatter
52 52 from IPython.core.history import HistoryManager
53 53 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
54 54 from IPython.core.logger import Logger
55 55 from IPython.core.macro import Macro
56 56 from IPython.core.payload import PayloadManager
57 57 from IPython.core.prefilter import PrefilterManager
58 58 from IPython.core.profiledir import ProfileDir
59 59 from IPython.core.usage import default_banner
60 60 from IPython.testing.skipdoctest import skip_doctest_py2, 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
66 65 from IPython.utils.decorators import undoc
67 66 from IPython.utils.io import ask_yes_no
68 67 from IPython.utils.ipstruct import Struct
69 68 from IPython.paths import get_ipython_dir
70 69 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
71 70 from IPython.utils.process import system, getoutput
72 71 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
73 72 with_metaclass, iteritems)
74 73 from IPython.utils.strdispatch import StrDispatch
75 74 from IPython.utils.syspathcontext import prepended_to_syspath
76 75 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
77 76 from IPython.utils.tempdir import TemporaryDirectory
78 77 from traitlets import (
79 78 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
80 79 observe, default,
81 80 )
82 81 from warnings import warn
83 82 from logging import error
84 83 import IPython.core.hooks
85 84
86 85 try:
87 86 import docrepr.sphinxify as sphx
88 87
89 88 def sphinxify(doc):
90 89 with TemporaryDirectory() as dirname:
91 90 return {
92 91 'text/html': sphx.sphinxify(doc, dirname),
93 92 'text/plain': doc
94 93 }
95 94 except ImportError:
96 95 sphinxify = None
97 96
98 97
99 98 class ProvisionalWarning(DeprecationWarning):
100 99 """
101 100 Warning class for unstable features
102 101 """
103 102 pass
104 103
105 104 #-----------------------------------------------------------------------------
106 105 # Globals
107 106 #-----------------------------------------------------------------------------
108 107
109 108 # compiled regexps for autoindent management
110 109 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
111 110
112 111 #-----------------------------------------------------------------------------
113 112 # Utilities
114 113 #-----------------------------------------------------------------------------
115 114
116 115 @undoc
117 116 def softspace(file, newvalue):
118 117 """Copied from code.py, to remove the dependency"""
119 118
120 119 oldvalue = 0
121 120 try:
122 121 oldvalue = file.softspace
123 122 except AttributeError:
124 123 pass
125 124 try:
126 125 file.softspace = newvalue
127 126 except (AttributeError, TypeError):
128 127 # "attribute-less object" or "read-only attributes"
129 128 pass
130 129 return oldvalue
131 130
132 131 @undoc
133 132 def no_op(*a, **kw): pass
134 133
135 134
136 135 class SpaceInInput(Exception): pass
137 136
138 137
139 138 def get_default_colors():
140 139 "DEPRECATED"
141 140 warn('get_default_color is Deprecated, and is `Neutral` on all platforms.',
142 141 DeprecationWarning, stacklevel=2)
143 142 return 'Neutral'
144 143
145 144
146 145 class SeparateUnicode(Unicode):
147 146 r"""A Unicode subclass to validate separate_in, separate_out, etc.
148 147
149 148 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
150 149 """
151 150
152 151 def validate(self, obj, value):
153 152 if value == '0': value = ''
154 153 value = value.replace('\\n','\n')
155 154 return super(SeparateUnicode, self).validate(obj, value)
156 155
157 156
158 157 @undoc
159 158 class DummyMod(object):
160 159 """A dummy module used for IPython's interactive module when
161 160 a namespace must be assigned to the module's __dict__."""
162 161 pass
163 162
164 163
165 164 class ExecutionResult(object):
166 165 """The result of a call to :meth:`InteractiveShell.run_cell`
167 166
168 167 Stores information about what took place.
169 168 """
170 169 execution_count = None
171 170 error_before_exec = None
172 171 error_in_exec = None
173 172 result = None
174 173
175 174 @property
176 175 def success(self):
177 176 return (self.error_before_exec is None) and (self.error_in_exec is None)
178 177
179 178 def raise_error(self):
180 179 """Reraises error if `success` is `False`, otherwise does nothing"""
181 180 if self.error_before_exec is not None:
182 181 raise self.error_before_exec
183 182 if self.error_in_exec is not None:
184 183 raise self.error_in_exec
185 184
186 185 def __repr__(self):
187 186 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
188 187 (self.__class__.__qualname__, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
189 188
190 189
191 190 class InteractiveShell(SingletonConfigurable):
192 191 """An enhanced, interactive shell for Python."""
193 192
194 193 _instance = None
195 194
196 195 ast_transformers = List([], help=
197 196 """
198 197 A list of ast.NodeTransformer subclass instances, which will be applied
199 198 to user input before code is run.
200 199 """
201 200 ).tag(config=True)
202 201
203 202 autocall = Enum((0,1,2), default_value=0, help=
204 203 """
205 204 Make IPython automatically call any callable object even if you didn't
206 205 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
207 206 automatically. The value can be '0' to disable the feature, '1' for
208 207 'smart' autocall, where it is not applied if there are no more
209 208 arguments on the line, and '2' for 'full' autocall, where all callable
210 209 objects are automatically called (even if no arguments are present).
211 210 """
212 211 ).tag(config=True)
213 212 # TODO: remove all autoindent logic and put into frontends.
214 213 # We can't do this yet because even runlines uses the autoindent.
215 214 autoindent = Bool(True, help=
216 215 """
217 216 Autoindent IPython code entered interactively.
218 217 """
219 218 ).tag(config=True)
220 219
221 220 automagic = Bool(True, help=
222 221 """
223 222 Enable magic commands to be called without the leading %.
224 223 """
225 224 ).tag(config=True)
226 225
227 226 banner1 = Unicode(default_banner,
228 227 help="""The part of the banner to be printed before the profile"""
229 228 ).tag(config=True)
230 229 banner2 = Unicode('',
231 230 help="""The part of the banner to be printed after the profile"""
232 231 ).tag(config=True)
233 232
234 233 cache_size = Integer(1000, help=
235 234 """
236 235 Set the size of the output cache. The default is 1000, you can
237 236 change it permanently in your config file. Setting it to 0 completely
238 237 disables the caching system, and the minimum value accepted is 20 (if
239 238 you provide a value less than 20, it is reset to 0 and a warning is
240 239 issued). This limit is defined because otherwise you'll spend more
241 240 time re-flushing a too small cache than working
242 241 """
243 242 ).tag(config=True)
244 243 color_info = Bool(True, help=
245 244 """
246 245 Use colors for displaying information about objects. Because this
247 246 information is passed through a pager (like 'less'), and some pagers
248 247 get confused with color codes, this capability can be turned off.
249 248 """
250 249 ).tag(config=True)
251 250 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
252 251 default_value='Neutral',
253 252 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
254 253 ).tag(config=True)
255 254 debug = Bool(False).tag(config=True)
256 255 deep_reload = Bool(False, help=
257 256 """
258 257 **Deprecated**
259 258
260 259 Will be removed in IPython 6.0
261 260
262 261 Enable deep (recursive) reloading by default. IPython can use the
263 262 deep_reload module which reloads changes in modules recursively (it
264 263 replaces the reload() function, so you don't need to change anything to
265 264 use it). `deep_reload` forces a full reload of modules whose code may
266 265 have changed, which the default reload() function does not. When
267 266 deep_reload is off, IPython will use the normal reload(), but
268 267 deep_reload will still be available as dreload().
269 268 """
270 269 ).tag(config=True)
271 270 disable_failing_post_execute = Bool(False,
272 271 help="Don't call post-execute functions that have failed in the past."
273 272 ).tag(config=True)
274 273 display_formatter = Instance(DisplayFormatter, allow_none=True)
275 274 displayhook_class = Type(DisplayHook)
276 275 display_pub_class = Type(DisplayPublisher)
277 276
278 277 sphinxify_docstring = Bool(False, help=
279 278 """
280 279 Enables rich html representation of docstrings. (This requires the
281 280 docrepr module).
282 281 """).tag(config=True)
283 282
284 283 @observe("sphinxify_docstring")
285 284 def _sphinxify_docstring_changed(self, change):
286 285 if change['new']:
287 286 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
288 287
289 288 enable_html_pager = Bool(False, help=
290 289 """
291 290 (Provisional API) enables html representation in mime bundles sent
292 291 to pagers.
293 292 """).tag(config=True)
294 293
295 294 @observe("enable_html_pager")
296 295 def _enable_html_pager_changed(self, change):
297 296 if change['new']:
298 297 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
299 298
300 299 data_pub_class = None
301 300
302 301 exit_now = Bool(False)
303 302 exiter = Instance(ExitAutocall)
304 303 @default('exiter')
305 304 def _exiter_default(self):
306 305 return ExitAutocall(self)
307 306 # Monotonically increasing execution counter
308 307 execution_count = Integer(1)
309 308 filename = Unicode("<ipython console>")
310 309 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
311 310
312 311 # Input splitter, to transform input line by line and detect when a block
313 312 # is ready to be executed.
314 313 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
315 314 (), {'line_input_checker': True})
316 315
317 316 # This InputSplitter instance is used to transform completed cells before
318 317 # running them. It allows cell magics to contain blank lines.
319 318 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
320 319 (), {'line_input_checker': False})
321 320
322 321 logstart = Bool(False, help=
323 322 """
324 323 Start logging to the default log file in overwrite mode.
325 324 Use `logappend` to specify a log file to **append** logs to.
326 325 """
327 326 ).tag(config=True)
328 327 logfile = Unicode('', help=
329 328 """
330 329 The name of the logfile to use.
331 330 """
332 331 ).tag(config=True)
333 332 logappend = Unicode('', help=
334 333 """
335 334 Start logging to the given file in append mode.
336 335 Use `logfile` to specify a log file to **overwrite** logs to.
337 336 """
338 337 ).tag(config=True)
339 338 object_info_string_level = Enum((0,1,2), default_value=0,
340 339 ).tag(config=True)
341 340 pdb = Bool(False, help=
342 341 """
343 342 Automatically call the pdb debugger after every exception.
344 343 """
345 344 ).tag(config=True)
346 345 display_page = Bool(False,
347 346 help="""If True, anything that would be passed to the pager
348 347 will be displayed as regular output instead."""
349 348 ).tag(config=True)
350 349
351 350 # deprecated prompt traits:
352 351
353 352 prompt_in1 = Unicode('In [\\#]: ',
354 353 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
355 354 ).tag(config=True)
356 355 prompt_in2 = Unicode(' .\\D.: ',
357 356 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
358 357 ).tag(config=True)
359 358 prompt_out = Unicode('Out[\\#]: ',
360 359 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
361 360 ).tag(config=True)
362 361 prompts_pad_left = Bool(True,
363 362 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
364 363 ).tag(config=True)
365 364
366 365 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
367 366 def _prompt_trait_changed(self, change):
368 367 name = change['name']
369 368 warn("InteractiveShell.{name} is deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly.".format(
370 369 name=name)
371 370 )
372 371 # protect against weird cases where self.config may not exist:
373 372
374 373 show_rewritten_input = Bool(True,
375 374 help="Show rewritten input, e.g. for autocall."
376 375 ).tag(config=True)
377 376
378 377 quiet = Bool(False).tag(config=True)
379 378
380 379 history_length = Integer(10000,
381 380 help='Total length of command history'
382 381 ).tag(config=True)
383 382
384 383 history_load_length = Integer(1000, help=
385 384 """
386 385 The number of saved history entries to be loaded
387 386 into the history buffer at startup.
388 387 """
389 388 ).tag(config=True)
390 389
391 390 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
392 391 default_value='last_expr',
393 392 help="""
394 393 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
395 394 run interactively (displaying output from expressions)."""
396 395 ).tag(config=True)
397 396
398 397 # TODO: this part of prompt management should be moved to the frontends.
399 398 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
400 399 separate_in = SeparateUnicode('\n').tag(config=True)
401 400 separate_out = SeparateUnicode('').tag(config=True)
402 401 separate_out2 = SeparateUnicode('').tag(config=True)
403 402 wildcards_case_sensitive = Bool(True).tag(config=True)
404 403 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
405 404 default_value='Context').tag(config=True)
406 405
407 406 # Subcomponents of InteractiveShell
408 407 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
409 408 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
410 409 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
411 410 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
412 411 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
413 412 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
414 413 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
415 414 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
416 415
417 416 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
418 417 @property
419 418 def profile(self):
420 419 if self.profile_dir is not None:
421 420 name = os.path.basename(self.profile_dir.location)
422 421 return name.replace('profile_','')
423 422
424 423
425 424 # Private interface
426 425 _post_execute = Dict()
427 426
428 427 # Tracks any GUI loop loaded for pylab
429 428 pylab_gui_select = None
430 429
431 430 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
432 431
433 432 def __init__(self, ipython_dir=None, profile_dir=None,
434 433 user_module=None, user_ns=None,
435 434 custom_exceptions=((), None), **kwargs):
436 435
437 436 # This is where traits with a config_key argument are updated
438 437 # from the values on config.
439 438 super(InteractiveShell, self).__init__(**kwargs)
440 439 if 'PromptManager' in self.config:
441 440 warn('As of IPython 5.0 `PromptManager` config will have no effect'
442 441 ' and has been replaced by TerminalInteractiveShell.prompts_class')
443 442 self.configurables = [self]
444 443
445 444 # These are relatively independent and stateless
446 445 self.init_ipython_dir(ipython_dir)
447 446 self.init_profile_dir(profile_dir)
448 447 self.init_instance_attrs()
449 448 self.init_environment()
450 449
451 450 # Check if we're in a virtualenv, and set up sys.path.
452 451 self.init_virtualenv()
453 452
454 453 # Create namespaces (user_ns, user_global_ns, etc.)
455 454 self.init_create_namespaces(user_module, user_ns)
456 455 # This has to be done after init_create_namespaces because it uses
457 456 # something in self.user_ns, but before init_sys_modules, which
458 457 # is the first thing to modify sys.
459 458 # TODO: When we override sys.stdout and sys.stderr before this class
460 459 # is created, we are saving the overridden ones here. Not sure if this
461 460 # is what we want to do.
462 461 self.save_sys_module_state()
463 462 self.init_sys_modules()
464 463
465 464 # While we're trying to have each part of the code directly access what
466 465 # it needs without keeping redundant references to objects, we have too
467 466 # much legacy code that expects ip.db to exist.
468 467 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
469 468
470 469 self.init_history()
471 470 self.init_encoding()
472 471 self.init_prefilter()
473 472
474 473 self.init_syntax_highlighting()
475 474 self.init_hooks()
476 475 self.init_events()
477 476 self.init_pushd_popd_magic()
478 477 # self.init_traceback_handlers use to be here, but we moved it below
479 478 # because it and init_io have to come after init_readline.
480 479 self.init_user_ns()
481 480 self.init_logger()
482 481 self.init_builtins()
483 482
484 483 # The following was in post_config_initialization
485 484 self.init_inspector()
486 485 # init_readline() must come before init_io(), because init_io uses
487 486 # readline related things.
488 487 self.init_readline()
489 488 # We save this here in case user code replaces raw_input, but it needs
490 489 # to be after init_readline(), because PyPy's readline works by replacing
491 490 # raw_input.
492 491 if py3compat.PY3:
493 492 self.raw_input_original = input
494 493 else:
495 494 self.raw_input_original = raw_input
496 495 # init_completer must come after init_readline, because it needs to
497 496 # know whether readline is present or not system-wide to configure the
498 497 # completers, since the completion machinery can now operate
499 498 # independently of readline (e.g. over the network)
500 499 self.init_completer()
501 500 # TODO: init_io() needs to happen before init_traceback handlers
502 501 # because the traceback handlers hardcode the stdout/stderr streams.
503 502 # This logic in in debugger.Pdb and should eventually be changed.
504 503 self.init_io()
505 504 self.init_traceback_handlers(custom_exceptions)
506 505 self.init_prompts()
507 506 self.init_display_formatter()
508 507 self.init_display_pub()
509 508 self.init_data_pub()
510 509 self.init_displayhook()
511 510 self.init_magics()
512 511 self.init_alias()
513 512 self.init_logstart()
514 513 self.init_pdb()
515 514 self.init_extension_manager()
516 515 self.init_payload()
517 516 self.init_deprecation_warnings()
518 517 self.hooks.late_startup_hook()
519 518 self.events.trigger('shell_initialized', self)
520 519 atexit.register(self.atexit_operations)
521 520
522 521 def get_ipython(self):
523 522 """Return the currently running IPython instance."""
524 523 return self
525 524
526 525 #-------------------------------------------------------------------------
527 526 # Trait changed handlers
528 527 #-------------------------------------------------------------------------
529 528 @observe('ipython_dir')
530 529 def _ipython_dir_changed(self, change):
531 530 ensure_dir_exists(change['new'])
532 531
533 532 def set_autoindent(self,value=None):
534 533 """Set the autoindent flag.
535 534
536 535 If called with no arguments, it acts as a toggle."""
537 536 if value is None:
538 537 self.autoindent = not self.autoindent
539 538 else:
540 539 self.autoindent = value
541 540
542 541 #-------------------------------------------------------------------------
543 542 # init_* methods called by __init__
544 543 #-------------------------------------------------------------------------
545 544
546 545 def init_ipython_dir(self, ipython_dir):
547 546 if ipython_dir is not None:
548 547 self.ipython_dir = ipython_dir
549 548 return
550 549
551 550 self.ipython_dir = get_ipython_dir()
552 551
553 552 def init_profile_dir(self, profile_dir):
554 553 if profile_dir is not None:
555 554 self.profile_dir = profile_dir
556 555 return
557 556 self.profile_dir =\
558 557 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
559 558
560 559 def init_instance_attrs(self):
561 560 self.more = False
562 561
563 562 # command compiler
564 563 self.compile = CachingCompiler()
565 564
566 565 # Make an empty namespace, which extension writers can rely on both
567 566 # existing and NEVER being used by ipython itself. This gives them a
568 567 # convenient location for storing additional information and state
569 568 # their extensions may require, without fear of collisions with other
570 569 # ipython names that may develop later.
571 570 self.meta = Struct()
572 571
573 572 # Temporary files used for various purposes. Deleted at exit.
574 573 self.tempfiles = []
575 574 self.tempdirs = []
576 575
577 # Keep track of readline usage (later set by init_readline)
578 self.has_readline = False
579
580 576 # keep track of where we started running (mainly for crash post-mortem)
581 577 # This is not being used anywhere currently.
582 578 self.starting_dir = py3compat.getcwd()
583 579
584 580 # Indentation management
585 581 self.indent_current_nsp = 0
586 582
587 583 # Dict to track post-execution functions that have been registered
588 584 self._post_execute = {}
589 585
590 586 def init_environment(self):
591 587 """Any changes we need to make to the user's environment."""
592 588 pass
593 589
594 590 def init_encoding(self):
595 591 # Get system encoding at startup time. Certain terminals (like Emacs
596 592 # under Win32 have it set to None, and we need to have a known valid
597 593 # encoding to use in the raw_input() method
598 594 try:
599 595 self.stdin_encoding = sys.stdin.encoding or 'ascii'
600 596 except AttributeError:
601 597 self.stdin_encoding = 'ascii'
602 598
603 599 def init_syntax_highlighting(self):
604 600 # Python source parser/formatter for syntax highlighting
605 601 pyformat = PyColorize.Parser().format
606 602 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
607 603
608 604 def refresh_style(self):
609 605 # No-op here, used in subclass
610 606 pass
611 607
612 608 def init_pushd_popd_magic(self):
613 609 # for pushd/popd management
614 610 self.home_dir = get_home_dir()
615 611
616 612 self.dir_stack = []
617 613
618 614 def init_logger(self):
619 615 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
620 616 logmode='rotate')
621 617
622 618 def init_logstart(self):
623 619 """Initialize logging in case it was requested at the command line.
624 620 """
625 621 if self.logappend:
626 622 self.magic('logstart %s append' % self.logappend)
627 623 elif self.logfile:
628 624 self.magic('logstart %s' % self.logfile)
629 625 elif self.logstart:
630 626 self.magic('logstart')
631 627
632 628 def init_deprecation_warnings(self):
633 629 """
634 630 register default filter for deprecation warning.
635 631
636 632 This will allow deprecation warning of function used interactively to show
637 633 warning to users, and still hide deprecation warning from libraries import.
638 634 """
639 635 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
640 636
641 637 def init_builtins(self):
642 638 # A single, static flag that we set to True. Its presence indicates
643 639 # that an IPython shell has been created, and we make no attempts at
644 640 # removing on exit or representing the existence of more than one
645 641 # IPython at a time.
646 642 builtin_mod.__dict__['__IPYTHON__'] = True
647 643
648 644 self.builtin_trap = BuiltinTrap(shell=self)
649 645
650 646 def init_inspector(self):
651 647 # Object inspector
652 648 self.inspector = oinspect.Inspector(oinspect.InspectColors,
653 649 PyColorize.ANSICodeColors,
654 650 'NoColor',
655 651 self.object_info_string_level)
656 652
657 653 def init_io(self):
658 654 # This will just use sys.stdout and sys.stderr. If you want to
659 655 # override sys.stdout and sys.stderr themselves, you need to do that
660 656 # *before* instantiating this class, because io holds onto
661 657 # references to the underlying streams.
662 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
663 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
664 else:
665 io.stdout = io.IOStream(sys.stdout)
666 io.stderr = io.IOStream(sys.stderr)
658 io.stdout = io.IOStream(sys.stdout)
659 io.stderr = io.IOStream(sys.stderr)
667 660
668 661 def init_prompts(self):
669 662 # Set system prompts, so that scripts can decide if they are running
670 663 # interactively.
671 664 sys.ps1 = 'In : '
672 665 sys.ps2 = '...: '
673 666 sys.ps3 = 'Out: '
674 667
675 668 def init_display_formatter(self):
676 669 self.display_formatter = DisplayFormatter(parent=self)
677 670 self.configurables.append(self.display_formatter)
678 671
679 672 def init_display_pub(self):
680 673 self.display_pub = self.display_pub_class(parent=self)
681 674 self.configurables.append(self.display_pub)
682 675
683 676 def init_data_pub(self):
684 677 if not self.data_pub_class:
685 678 self.data_pub = None
686 679 return
687 680 self.data_pub = self.data_pub_class(parent=self)
688 681 self.configurables.append(self.data_pub)
689 682
690 683 def init_displayhook(self):
691 684 # Initialize displayhook, set in/out prompts and printing system
692 685 self.displayhook = self.displayhook_class(
693 686 parent=self,
694 687 shell=self,
695 688 cache_size=self.cache_size,
696 689 )
697 690 self.configurables.append(self.displayhook)
698 691 # This is a context manager that installs/revmoes the displayhook at
699 692 # the appropriate time.
700 693 self.display_trap = DisplayTrap(hook=self.displayhook)
701 694
702 695 def init_virtualenv(self):
703 696 """Add a virtualenv to sys.path so the user can import modules from it.
704 697 This isn't perfect: it doesn't use the Python interpreter with which the
705 698 virtualenv was built, and it ignores the --no-site-packages option. A
706 699 warning will appear suggesting the user installs IPython in the
707 700 virtualenv, but for many cases, it probably works well enough.
708 701
709 702 Adapted from code snippets online.
710 703
711 704 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
712 705 """
713 706 if 'VIRTUAL_ENV' not in os.environ:
714 707 # Not in a virtualenv
715 708 return
716 709
717 710 # venv detection:
718 711 # stdlib venv may symlink sys.executable, so we can't use realpath.
719 712 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
720 713 # So we just check every item in the symlink tree (generally <= 3)
721 714 p = os.path.normcase(sys.executable)
722 715 paths = [p]
723 716 while os.path.islink(p):
724 717 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
725 718 paths.append(p)
726 719 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
727 720 if any(p.startswith(p_venv) for p in paths):
728 721 # Running properly in the virtualenv, don't need to do anything
729 722 return
730 723
731 724 warn("Attempting to work in a virtualenv. If you encounter problems, please "
732 725 "install IPython inside the virtualenv.")
733 726 if sys.platform == "win32":
734 727 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
735 728 else:
736 729 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
737 730 'python%d.%d' % sys.version_info[:2], 'site-packages')
738 731
739 732 import site
740 733 sys.path.insert(0, virtual_env)
741 734 site.addsitedir(virtual_env)
742 735
743 736 #-------------------------------------------------------------------------
744 737 # Things related to injections into the sys module
745 738 #-------------------------------------------------------------------------
746 739
747 740 def save_sys_module_state(self):
748 741 """Save the state of hooks in the sys module.
749 742
750 743 This has to be called after self.user_module is created.
751 744 """
752 745 self._orig_sys_module_state = {'stdin': sys.stdin,
753 746 'stdout': sys.stdout,
754 747 'stderr': sys.stderr,
755 748 'excepthook': sys.excepthook}
756 749 self._orig_sys_modules_main_name = self.user_module.__name__
757 750 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
758 751
759 752 def restore_sys_module_state(self):
760 753 """Restore the state of the sys module."""
761 754 try:
762 755 for k, v in iteritems(self._orig_sys_module_state):
763 756 setattr(sys, k, v)
764 757 except AttributeError:
765 758 pass
766 759 # Reset what what done in self.init_sys_modules
767 760 if self._orig_sys_modules_main_mod is not None:
768 761 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
769 762
770 763 #-------------------------------------------------------------------------
771 764 # Things related to the banner
772 765 #-------------------------------------------------------------------------
773 766
774 767 @property
775 768 def banner(self):
776 769 banner = self.banner1
777 770 if self.profile and self.profile != 'default':
778 771 banner += '\nIPython profile: %s\n' % self.profile
779 772 if self.banner2:
780 773 banner += '\n' + self.banner2
781 774 return banner
782 775
783 776 def show_banner(self, banner=None):
784 777 if banner is None:
785 778 banner = self.banner
786 779 sys.stdout.write(banner)
787 780
788 781 #-------------------------------------------------------------------------
789 782 # Things related to hooks
790 783 #-------------------------------------------------------------------------
791 784
792 785 def init_hooks(self):
793 786 # hooks holds pointers used for user-side customizations
794 787 self.hooks = Struct()
795 788
796 789 self.strdispatchers = {}
797 790
798 791 # Set all default hooks, defined in the IPython.hooks module.
799 792 hooks = IPython.core.hooks
800 793 for hook_name in hooks.__all__:
801 794 # default hooks have priority 100, i.e. low; user hooks should have
802 795 # 0-100 priority
803 796 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
804 797
805 798 if self.display_page:
806 799 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
807 800
808 801 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
809 802 _warn_deprecated=True):
810 803 """set_hook(name,hook) -> sets an internal IPython hook.
811 804
812 805 IPython exposes some of its internal API as user-modifiable hooks. By
813 806 adding your function to one of these hooks, you can modify IPython's
814 807 behavior to call at runtime your own routines."""
815 808
816 809 # At some point in the future, this should validate the hook before it
817 810 # accepts it. Probably at least check that the hook takes the number
818 811 # of args it's supposed to.
819 812
820 813 f = types.MethodType(hook,self)
821 814
822 815 # check if the hook is for strdispatcher first
823 816 if str_key is not None:
824 817 sdp = self.strdispatchers.get(name, StrDispatch())
825 818 sdp.add_s(str_key, f, priority )
826 819 self.strdispatchers[name] = sdp
827 820 return
828 821 if re_key is not None:
829 822 sdp = self.strdispatchers.get(name, StrDispatch())
830 823 sdp.add_re(re.compile(re_key), f, priority )
831 824 self.strdispatchers[name] = sdp
832 825 return
833 826
834 827 dp = getattr(self.hooks, name, None)
835 828 if name not in IPython.core.hooks.__all__:
836 829 print("Warning! Hook '%s' is not one of %s" % \
837 830 (name, IPython.core.hooks.__all__ ))
838 831
839 832 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
840 833 alternative = IPython.core.hooks.deprecated[name]
841 834 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
842 835
843 836 if not dp:
844 837 dp = IPython.core.hooks.CommandChainDispatcher()
845 838
846 839 try:
847 840 dp.add(f,priority)
848 841 except AttributeError:
849 842 # it was not commandchain, plain old func - replace
850 843 dp = f
851 844
852 845 setattr(self.hooks,name, dp)
853 846
854 847 #-------------------------------------------------------------------------
855 848 # Things related to events
856 849 #-------------------------------------------------------------------------
857 850
858 851 def init_events(self):
859 852 self.events = EventManager(self, available_events)
860 853
861 854 self.events.register("pre_execute", self._clear_warning_registry)
862 855
863 856 def register_post_execute(self, func):
864 857 """DEPRECATED: Use ip.events.register('post_run_cell', func)
865 858
866 859 Register a function for calling after code execution.
867 860 """
868 861 warn("ip.register_post_execute is deprecated, use "
869 862 "ip.events.register('post_run_cell', func) instead.")
870 863 self.events.register('post_run_cell', func)
871 864
872 865 def _clear_warning_registry(self):
873 866 # clear the warning registry, so that different code blocks with
874 867 # overlapping line number ranges don't cause spurious suppression of
875 868 # warnings (see gh-6611 for details)
876 869 if "__warningregistry__" in self.user_global_ns:
877 870 del self.user_global_ns["__warningregistry__"]
878 871
879 872 #-------------------------------------------------------------------------
880 873 # Things related to the "main" module
881 874 #-------------------------------------------------------------------------
882 875
883 876 def new_main_mod(self, filename, modname):
884 877 """Return a new 'main' module object for user code execution.
885 878
886 879 ``filename`` should be the path of the script which will be run in the
887 880 module. Requests with the same filename will get the same module, with
888 881 its namespace cleared.
889 882
890 883 ``modname`` should be the module name - normally either '__main__' or
891 884 the basename of the file without the extension.
892 885
893 886 When scripts are executed via %run, we must keep a reference to their
894 887 __main__ module around so that Python doesn't
895 888 clear it, rendering references to module globals useless.
896 889
897 890 This method keeps said reference in a private dict, keyed by the
898 891 absolute path of the script. This way, for multiple executions of the
899 892 same script we only keep one copy of the namespace (the last one),
900 893 thus preventing memory leaks from old references while allowing the
901 894 objects from the last execution to be accessible.
902 895 """
903 896 filename = os.path.abspath(filename)
904 897 try:
905 898 main_mod = self._main_mod_cache[filename]
906 899 except KeyError:
907 900 main_mod = self._main_mod_cache[filename] = types.ModuleType(
908 901 py3compat.cast_bytes_py2(modname),
909 902 doc="Module created for script run in IPython")
910 903 else:
911 904 main_mod.__dict__.clear()
912 905 main_mod.__name__ = modname
913 906
914 907 main_mod.__file__ = filename
915 908 # It seems pydoc (and perhaps others) needs any module instance to
916 909 # implement a __nonzero__ method
917 910 main_mod.__nonzero__ = lambda : True
918 911
919 912 return main_mod
920 913
921 914 def clear_main_mod_cache(self):
922 915 """Clear the cache of main modules.
923 916
924 917 Mainly for use by utilities like %reset.
925 918
926 919 Examples
927 920 --------
928 921
929 922 In [15]: import IPython
930 923
931 924 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
932 925
933 926 In [17]: len(_ip._main_mod_cache) > 0
934 927 Out[17]: True
935 928
936 929 In [18]: _ip.clear_main_mod_cache()
937 930
938 931 In [19]: len(_ip._main_mod_cache) == 0
939 932 Out[19]: True
940 933 """
941 934 self._main_mod_cache.clear()
942 935
943 936 #-------------------------------------------------------------------------
944 937 # Things related to debugging
945 938 #-------------------------------------------------------------------------
946 939
947 940 def init_pdb(self):
948 941 # Set calling of pdb on exceptions
949 942 # self.call_pdb is a property
950 943 self.call_pdb = self.pdb
951 944
952 945 def _get_call_pdb(self):
953 946 return self._call_pdb
954 947
955 948 def _set_call_pdb(self,val):
956 949
957 950 if val not in (0,1,False,True):
958 951 raise ValueError('new call_pdb value must be boolean')
959 952
960 953 # store value in instance
961 954 self._call_pdb = val
962 955
963 956 # notify the actual exception handlers
964 957 self.InteractiveTB.call_pdb = val
965 958
966 959 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
967 960 'Control auto-activation of pdb at exceptions')
968 961
969 962 def debugger(self,force=False):
970 963 """Call the pdb debugger.
971 964
972 965 Keywords:
973 966
974 967 - force(False): by default, this routine checks the instance call_pdb
975 968 flag and does not actually invoke the debugger if the flag is false.
976 969 The 'force' option forces the debugger to activate even if the flag
977 970 is false.
978 971 """
979 972
980 973 if not (force or self.call_pdb):
981 974 return
982 975
983 976 if not hasattr(sys,'last_traceback'):
984 977 error('No traceback has been produced, nothing to debug.')
985 978 return
986 979
987
988 with self.readline_no_record:
989 self.InteractiveTB.debugger(force=True)
980 self.InteractiveTB.debugger(force=True)
990 981
991 982 #-------------------------------------------------------------------------
992 983 # Things related to IPython's various namespaces
993 984 #-------------------------------------------------------------------------
994 985 default_user_namespaces = True
995 986
996 987 def init_create_namespaces(self, user_module=None, user_ns=None):
997 988 # Create the namespace where the user will operate. user_ns is
998 989 # normally the only one used, and it is passed to the exec calls as
999 990 # the locals argument. But we do carry a user_global_ns namespace
1000 991 # given as the exec 'globals' argument, This is useful in embedding
1001 992 # situations where the ipython shell opens in a context where the
1002 993 # distinction between locals and globals is meaningful. For
1003 994 # non-embedded contexts, it is just the same object as the user_ns dict.
1004 995
1005 996 # FIXME. For some strange reason, __builtins__ is showing up at user
1006 997 # level as a dict instead of a module. This is a manual fix, but I
1007 998 # should really track down where the problem is coming from. Alex
1008 999 # Schmolck reported this problem first.
1009 1000
1010 1001 # A useful post by Alex Martelli on this topic:
1011 1002 # Re: inconsistent value from __builtins__
1012 1003 # Von: Alex Martelli <aleaxit@yahoo.com>
1013 1004 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1014 1005 # Gruppen: comp.lang.python
1015 1006
1016 1007 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1017 1008 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1018 1009 # > <type 'dict'>
1019 1010 # > >>> print type(__builtins__)
1020 1011 # > <type 'module'>
1021 1012 # > Is this difference in return value intentional?
1022 1013
1023 1014 # Well, it's documented that '__builtins__' can be either a dictionary
1024 1015 # or a module, and it's been that way for a long time. Whether it's
1025 1016 # intentional (or sensible), I don't know. In any case, the idea is
1026 1017 # that if you need to access the built-in namespace directly, you
1027 1018 # should start with "import __builtin__" (note, no 's') which will
1028 1019 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1029 1020
1030 1021 # These routines return a properly built module and dict as needed by
1031 1022 # the rest of the code, and can also be used by extension writers to
1032 1023 # generate properly initialized namespaces.
1033 1024 if (user_ns is not None) or (user_module is not None):
1034 1025 self.default_user_namespaces = False
1035 1026 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1036 1027
1037 1028 # A record of hidden variables we have added to the user namespace, so
1038 1029 # we can list later only variables defined in actual interactive use.
1039 1030 self.user_ns_hidden = {}
1040 1031
1041 1032 # Now that FakeModule produces a real module, we've run into a nasty
1042 1033 # problem: after script execution (via %run), the module where the user
1043 1034 # code ran is deleted. Now that this object is a true module (needed
1044 1035 # so doctest and other tools work correctly), the Python module
1045 1036 # teardown mechanism runs over it, and sets to None every variable
1046 1037 # present in that module. Top-level references to objects from the
1047 1038 # script survive, because the user_ns is updated with them. However,
1048 1039 # calling functions defined in the script that use other things from
1049 1040 # the script will fail, because the function's closure had references
1050 1041 # to the original objects, which are now all None. So we must protect
1051 1042 # these modules from deletion by keeping a cache.
1052 1043 #
1053 1044 # To avoid keeping stale modules around (we only need the one from the
1054 1045 # last run), we use a dict keyed with the full path to the script, so
1055 1046 # only the last version of the module is held in the cache. Note,
1056 1047 # however, that we must cache the module *namespace contents* (their
1057 1048 # __dict__). Because if we try to cache the actual modules, old ones
1058 1049 # (uncached) could be destroyed while still holding references (such as
1059 1050 # those held by GUI objects that tend to be long-lived)>
1060 1051 #
1061 1052 # The %reset command will flush this cache. See the cache_main_mod()
1062 1053 # and clear_main_mod_cache() methods for details on use.
1063 1054
1064 1055 # This is the cache used for 'main' namespaces
1065 1056 self._main_mod_cache = {}
1066 1057
1067 1058 # A table holding all the namespaces IPython deals with, so that
1068 1059 # introspection facilities can search easily.
1069 1060 self.ns_table = {'user_global':self.user_module.__dict__,
1070 1061 'user_local':self.user_ns,
1071 1062 'builtin':builtin_mod.__dict__
1072 1063 }
1073 1064
1074 1065 @property
1075 1066 def user_global_ns(self):
1076 1067 return self.user_module.__dict__
1077 1068
1078 1069 def prepare_user_module(self, user_module=None, user_ns=None):
1079 1070 """Prepare the module and namespace in which user code will be run.
1080 1071
1081 1072 When IPython is started normally, both parameters are None: a new module
1082 1073 is created automatically, and its __dict__ used as the namespace.
1083 1074
1084 1075 If only user_module is provided, its __dict__ is used as the namespace.
1085 1076 If only user_ns is provided, a dummy module is created, and user_ns
1086 1077 becomes the global namespace. If both are provided (as they may be
1087 1078 when embedding), user_ns is the local namespace, and user_module
1088 1079 provides the global namespace.
1089 1080
1090 1081 Parameters
1091 1082 ----------
1092 1083 user_module : module, optional
1093 1084 The current user module in which IPython is being run. If None,
1094 1085 a clean module will be created.
1095 1086 user_ns : dict, optional
1096 1087 A namespace in which to run interactive commands.
1097 1088
1098 1089 Returns
1099 1090 -------
1100 1091 A tuple of user_module and user_ns, each properly initialised.
1101 1092 """
1102 1093 if user_module is None and user_ns is not None:
1103 1094 user_ns.setdefault("__name__", "__main__")
1104 1095 user_module = DummyMod()
1105 1096 user_module.__dict__ = user_ns
1106 1097
1107 1098 if user_module is None:
1108 1099 user_module = types.ModuleType("__main__",
1109 1100 doc="Automatically created module for IPython interactive environment")
1110 1101
1111 1102 # We must ensure that __builtin__ (without the final 's') is always
1112 1103 # available and pointing to the __builtin__ *module*. For more details:
1113 1104 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1114 1105 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1115 1106 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1116 1107
1117 1108 if user_ns is None:
1118 1109 user_ns = user_module.__dict__
1119 1110
1120 1111 return user_module, user_ns
1121 1112
1122 1113 def init_sys_modules(self):
1123 1114 # We need to insert into sys.modules something that looks like a
1124 1115 # module but which accesses the IPython namespace, for shelve and
1125 1116 # pickle to work interactively. Normally they rely on getting
1126 1117 # everything out of __main__, but for embedding purposes each IPython
1127 1118 # instance has its own private namespace, so we can't go shoving
1128 1119 # everything into __main__.
1129 1120
1130 1121 # note, however, that we should only do this for non-embedded
1131 1122 # ipythons, which really mimic the __main__.__dict__ with their own
1132 1123 # namespace. Embedded instances, on the other hand, should not do
1133 1124 # this because they need to manage the user local/global namespaces
1134 1125 # only, but they live within a 'normal' __main__ (meaning, they
1135 1126 # shouldn't overtake the execution environment of the script they're
1136 1127 # embedded in).
1137 1128
1138 1129 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1139 1130 main_name = self.user_module.__name__
1140 1131 sys.modules[main_name] = self.user_module
1141 1132
1142 1133 def init_user_ns(self):
1143 1134 """Initialize all user-visible namespaces to their minimum defaults.
1144 1135
1145 1136 Certain history lists are also initialized here, as they effectively
1146 1137 act as user namespaces.
1147 1138
1148 1139 Notes
1149 1140 -----
1150 1141 All data structures here are only filled in, they are NOT reset by this
1151 1142 method. If they were not empty before, data will simply be added to
1152 1143 therm.
1153 1144 """
1154 1145 # This function works in two parts: first we put a few things in
1155 1146 # user_ns, and we sync that contents into user_ns_hidden so that these
1156 1147 # initial variables aren't shown by %who. After the sync, we add the
1157 1148 # rest of what we *do* want the user to see with %who even on a new
1158 1149 # session (probably nothing, so they really only see their own stuff)
1159 1150
1160 1151 # The user dict must *always* have a __builtin__ reference to the
1161 1152 # Python standard __builtin__ namespace, which must be imported.
1162 1153 # This is so that certain operations in prompt evaluation can be
1163 1154 # reliably executed with builtins. Note that we can NOT use
1164 1155 # __builtins__ (note the 's'), because that can either be a dict or a
1165 1156 # module, and can even mutate at runtime, depending on the context
1166 1157 # (Python makes no guarantees on it). In contrast, __builtin__ is
1167 1158 # always a module object, though it must be explicitly imported.
1168 1159
1169 1160 # For more details:
1170 1161 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1171 1162 ns = dict()
1172 1163
1173 1164 # make global variables for user access to the histories
1174 1165 ns['_ih'] = self.history_manager.input_hist_parsed
1175 1166 ns['_oh'] = self.history_manager.output_hist
1176 1167 ns['_dh'] = self.history_manager.dir_hist
1177 1168
1178 1169 ns['_sh'] = shadowns
1179 1170
1180 1171 # user aliases to input and output histories. These shouldn't show up
1181 1172 # in %who, as they can have very large reprs.
1182 1173 ns['In'] = self.history_manager.input_hist_parsed
1183 1174 ns['Out'] = self.history_manager.output_hist
1184 1175
1185 1176 # Store myself as the public api!!!
1186 1177 ns['get_ipython'] = self.get_ipython
1187 1178
1188 1179 ns['exit'] = self.exiter
1189 1180 ns['quit'] = self.exiter
1190 1181
1191 1182 # Sync what we've added so far to user_ns_hidden so these aren't seen
1192 1183 # by %who
1193 1184 self.user_ns_hidden.update(ns)
1194 1185
1195 1186 # Anything put into ns now would show up in %who. Think twice before
1196 1187 # putting anything here, as we really want %who to show the user their
1197 1188 # stuff, not our variables.
1198 1189
1199 1190 # Finally, update the real user's namespace
1200 1191 self.user_ns.update(ns)
1201 1192
1202 1193 @property
1203 1194 def all_ns_refs(self):
1204 1195 """Get a list of references to all the namespace dictionaries in which
1205 1196 IPython might store a user-created object.
1206 1197
1207 1198 Note that this does not include the displayhook, which also caches
1208 1199 objects from the output."""
1209 1200 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1210 1201 [m.__dict__ for m in self._main_mod_cache.values()]
1211 1202
1212 1203 def reset(self, new_session=True):
1213 1204 """Clear all internal namespaces, and attempt to release references to
1214 1205 user objects.
1215 1206
1216 1207 If new_session is True, a new history session will be opened.
1217 1208 """
1218 1209 # Clear histories
1219 1210 self.history_manager.reset(new_session)
1220 1211 # Reset counter used to index all histories
1221 1212 if new_session:
1222 1213 self.execution_count = 1
1223 1214
1224 1215 # Flush cached output items
1225 1216 if self.displayhook.do_full_cache:
1226 1217 self.displayhook.flush()
1227 1218
1228 1219 # The main execution namespaces must be cleared very carefully,
1229 1220 # skipping the deletion of the builtin-related keys, because doing so
1230 1221 # would cause errors in many object's __del__ methods.
1231 1222 if self.user_ns is not self.user_global_ns:
1232 1223 self.user_ns.clear()
1233 1224 ns = self.user_global_ns
1234 1225 drop_keys = set(ns.keys())
1235 1226 drop_keys.discard('__builtin__')
1236 1227 drop_keys.discard('__builtins__')
1237 1228 drop_keys.discard('__name__')
1238 1229 for k in drop_keys:
1239 1230 del ns[k]
1240 1231
1241 1232 self.user_ns_hidden.clear()
1242 1233
1243 1234 # Restore the user namespaces to minimal usability
1244 1235 self.init_user_ns()
1245 1236
1246 1237 # Restore the default and user aliases
1247 1238 self.alias_manager.clear_aliases()
1248 1239 self.alias_manager.init_aliases()
1249 1240
1250 1241 # Flush the private list of module references kept for script
1251 1242 # execution protection
1252 1243 self.clear_main_mod_cache()
1253 1244
1254 1245 def del_var(self, varname, by_name=False):
1255 1246 """Delete a variable from the various namespaces, so that, as
1256 1247 far as possible, we're not keeping any hidden references to it.
1257 1248
1258 1249 Parameters
1259 1250 ----------
1260 1251 varname : str
1261 1252 The name of the variable to delete.
1262 1253 by_name : bool
1263 1254 If True, delete variables with the given name in each
1264 1255 namespace. If False (default), find the variable in the user
1265 1256 namespace, and delete references to it.
1266 1257 """
1267 1258 if varname in ('__builtin__', '__builtins__'):
1268 1259 raise ValueError("Refusing to delete %s" % varname)
1269 1260
1270 1261 ns_refs = self.all_ns_refs
1271 1262
1272 1263 if by_name: # Delete by name
1273 1264 for ns in ns_refs:
1274 1265 try:
1275 1266 del ns[varname]
1276 1267 except KeyError:
1277 1268 pass
1278 1269 else: # Delete by object
1279 1270 try:
1280 1271 obj = self.user_ns[varname]
1281 1272 except KeyError:
1282 1273 raise NameError("name '%s' is not defined" % varname)
1283 1274 # Also check in output history
1284 1275 ns_refs.append(self.history_manager.output_hist)
1285 1276 for ns in ns_refs:
1286 1277 to_delete = [n for n, o in iteritems(ns) if o is obj]
1287 1278 for name in to_delete:
1288 1279 del ns[name]
1289 1280
1290 1281 # displayhook keeps extra references, but not in a dictionary
1291 1282 for name in ('_', '__', '___'):
1292 1283 if getattr(self.displayhook, name) is obj:
1293 1284 setattr(self.displayhook, name, None)
1294 1285
1295 1286 def reset_selective(self, regex=None):
1296 1287 """Clear selective variables from internal namespaces based on a
1297 1288 specified regular expression.
1298 1289
1299 1290 Parameters
1300 1291 ----------
1301 1292 regex : string or compiled pattern, optional
1302 1293 A regular expression pattern that will be used in searching
1303 1294 variable names in the users namespaces.
1304 1295 """
1305 1296 if regex is not None:
1306 1297 try:
1307 1298 m = re.compile(regex)
1308 1299 except TypeError:
1309 1300 raise TypeError('regex must be a string or compiled pattern')
1310 1301 # Search for keys in each namespace that match the given regex
1311 1302 # If a match is found, delete the key/value pair.
1312 1303 for ns in self.all_ns_refs:
1313 1304 for var in ns:
1314 1305 if m.search(var):
1315 1306 del ns[var]
1316 1307
1317 1308 def push(self, variables, interactive=True):
1318 1309 """Inject a group of variables into the IPython user namespace.
1319 1310
1320 1311 Parameters
1321 1312 ----------
1322 1313 variables : dict, str or list/tuple of str
1323 1314 The variables to inject into the user's namespace. If a dict, a
1324 1315 simple update is done. If a str, the string is assumed to have
1325 1316 variable names separated by spaces. A list/tuple of str can also
1326 1317 be used to give the variable names. If just the variable names are
1327 1318 give (list/tuple/str) then the variable values looked up in the
1328 1319 callers frame.
1329 1320 interactive : bool
1330 1321 If True (default), the variables will be listed with the ``who``
1331 1322 magic.
1332 1323 """
1333 1324 vdict = None
1334 1325
1335 1326 # We need a dict of name/value pairs to do namespace updates.
1336 1327 if isinstance(variables, dict):
1337 1328 vdict = variables
1338 1329 elif isinstance(variables, string_types+(list, tuple)):
1339 1330 if isinstance(variables, string_types):
1340 1331 vlist = variables.split()
1341 1332 else:
1342 1333 vlist = variables
1343 1334 vdict = {}
1344 1335 cf = sys._getframe(1)
1345 1336 for name in vlist:
1346 1337 try:
1347 1338 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1348 1339 except:
1349 1340 print('Could not get variable %s from %s' %
1350 1341 (name,cf.f_code.co_name))
1351 1342 else:
1352 1343 raise ValueError('variables must be a dict/str/list/tuple')
1353 1344
1354 1345 # Propagate variables to user namespace
1355 1346 self.user_ns.update(vdict)
1356 1347
1357 1348 # And configure interactive visibility
1358 1349 user_ns_hidden = self.user_ns_hidden
1359 1350 if interactive:
1360 1351 for name in vdict:
1361 1352 user_ns_hidden.pop(name, None)
1362 1353 else:
1363 1354 user_ns_hidden.update(vdict)
1364 1355
1365 1356 def drop_by_id(self, variables):
1366 1357 """Remove a dict of variables from the user namespace, if they are the
1367 1358 same as the values in the dictionary.
1368 1359
1369 1360 This is intended for use by extensions: variables that they've added can
1370 1361 be taken back out if they are unloaded, without removing any that the
1371 1362 user has overwritten.
1372 1363
1373 1364 Parameters
1374 1365 ----------
1375 1366 variables : dict
1376 1367 A dictionary mapping object names (as strings) to the objects.
1377 1368 """
1378 1369 for name, obj in iteritems(variables):
1379 1370 if name in self.user_ns and self.user_ns[name] is obj:
1380 1371 del self.user_ns[name]
1381 1372 self.user_ns_hidden.pop(name, None)
1382 1373
1383 1374 #-------------------------------------------------------------------------
1384 1375 # Things related to object introspection
1385 1376 #-------------------------------------------------------------------------
1386 1377
1387 1378 def _ofind(self, oname, namespaces=None):
1388 1379 """Find an object in the available namespaces.
1389 1380
1390 1381 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1391 1382
1392 1383 Has special code to detect magic functions.
1393 1384 """
1394 1385 oname = oname.strip()
1395 1386 #print '1- oname: <%r>' % oname # dbg
1396 1387 if not oname.startswith(ESC_MAGIC) and \
1397 1388 not oname.startswith(ESC_MAGIC2) and \
1398 1389 not py3compat.isidentifier(oname, dotted=True):
1399 1390 return dict(found=False)
1400 1391
1401 1392 if namespaces is None:
1402 1393 # Namespaces to search in:
1403 1394 # Put them in a list. The order is important so that we
1404 1395 # find things in the same order that Python finds them.
1405 1396 namespaces = [ ('Interactive', self.user_ns),
1406 1397 ('Interactive (global)', self.user_global_ns),
1407 1398 ('Python builtin', builtin_mod.__dict__),
1408 1399 ]
1409 1400
1410 1401 # initialize results to 'null'
1411 1402 found = False; obj = None; ospace = None;
1412 1403 ismagic = False; isalias = False; parent = None
1413 1404
1414 1405 # We need to special-case 'print', which as of python2.6 registers as a
1415 1406 # function but should only be treated as one if print_function was
1416 1407 # loaded with a future import. In this case, just bail.
1417 1408 if (oname == 'print' and not py3compat.PY3 and not \
1418 1409 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1419 1410 return {'found':found, 'obj':obj, 'namespace':ospace,
1420 1411 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1421 1412
1422 1413 # Look for the given name by splitting it in parts. If the head is
1423 1414 # found, then we look for all the remaining parts as members, and only
1424 1415 # declare success if we can find them all.
1425 1416 oname_parts = oname.split('.')
1426 1417 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1427 1418 for nsname,ns in namespaces:
1428 1419 try:
1429 1420 obj = ns[oname_head]
1430 1421 except KeyError:
1431 1422 continue
1432 1423 else:
1433 1424 #print 'oname_rest:', oname_rest # dbg
1434 1425 for idx, part in enumerate(oname_rest):
1435 1426 try:
1436 1427 parent = obj
1437 1428 # The last part is looked up in a special way to avoid
1438 1429 # descriptor invocation as it may raise or have side
1439 1430 # effects.
1440 1431 if idx == len(oname_rest) - 1:
1441 1432 obj = self._getattr_property(obj, part)
1442 1433 else:
1443 1434 obj = getattr(obj, part)
1444 1435 except:
1445 1436 # Blanket except b/c some badly implemented objects
1446 1437 # allow __getattr__ to raise exceptions other than
1447 1438 # AttributeError, which then crashes IPython.
1448 1439 break
1449 1440 else:
1450 1441 # If we finish the for loop (no break), we got all members
1451 1442 found = True
1452 1443 ospace = nsname
1453 1444 break # namespace loop
1454 1445
1455 1446 # Try to see if it's magic
1456 1447 if not found:
1457 1448 obj = None
1458 1449 if oname.startswith(ESC_MAGIC2):
1459 1450 oname = oname.lstrip(ESC_MAGIC2)
1460 1451 obj = self.find_cell_magic(oname)
1461 1452 elif oname.startswith(ESC_MAGIC):
1462 1453 oname = oname.lstrip(ESC_MAGIC)
1463 1454 obj = self.find_line_magic(oname)
1464 1455 else:
1465 1456 # search without prefix, so run? will find %run?
1466 1457 obj = self.find_line_magic(oname)
1467 1458 if obj is None:
1468 1459 obj = self.find_cell_magic(oname)
1469 1460 if obj is not None:
1470 1461 found = True
1471 1462 ospace = 'IPython internal'
1472 1463 ismagic = True
1473 1464 isalias = isinstance(obj, Alias)
1474 1465
1475 1466 # Last try: special-case some literals like '', [], {}, etc:
1476 1467 if not found and oname_head in ["''",'""','[]','{}','()']:
1477 1468 obj = eval(oname_head)
1478 1469 found = True
1479 1470 ospace = 'Interactive'
1480 1471
1481 1472 return {'found':found, 'obj':obj, 'namespace':ospace,
1482 1473 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1483 1474
1484 1475 @staticmethod
1485 1476 def _getattr_property(obj, attrname):
1486 1477 """Property-aware getattr to use in object finding.
1487 1478
1488 1479 If attrname represents a property, return it unevaluated (in case it has
1489 1480 side effects or raises an error.
1490 1481
1491 1482 """
1492 1483 if not isinstance(obj, type):
1493 1484 try:
1494 1485 # `getattr(type(obj), attrname)` is not guaranteed to return
1495 1486 # `obj`, but does so for property:
1496 1487 #
1497 1488 # property.__get__(self, None, cls) -> self
1498 1489 #
1499 1490 # The universal alternative is to traverse the mro manually
1500 1491 # searching for attrname in class dicts.
1501 1492 attr = getattr(type(obj), attrname)
1502 1493 except AttributeError:
1503 1494 pass
1504 1495 else:
1505 1496 # This relies on the fact that data descriptors (with both
1506 1497 # __get__ & __set__ magic methods) take precedence over
1507 1498 # instance-level attributes:
1508 1499 #
1509 1500 # class A(object):
1510 1501 # @property
1511 1502 # def foobar(self): return 123
1512 1503 # a = A()
1513 1504 # a.__dict__['foobar'] = 345
1514 1505 # a.foobar # == 123
1515 1506 #
1516 1507 # So, a property may be returned right away.
1517 1508 if isinstance(attr, property):
1518 1509 return attr
1519 1510
1520 1511 # Nothing helped, fall back.
1521 1512 return getattr(obj, attrname)
1522 1513
1523 1514 def _object_find(self, oname, namespaces=None):
1524 1515 """Find an object and return a struct with info about it."""
1525 1516 return Struct(self._ofind(oname, namespaces))
1526 1517
1527 1518 def _inspect(self, meth, oname, namespaces=None, **kw):
1528 1519 """Generic interface to the inspector system.
1529 1520
1530 1521 This function is meant to be called by pdef, pdoc & friends.
1531 1522 """
1532 1523 info = self._object_find(oname, namespaces)
1533 1524 docformat = sphinxify if self.sphinxify_docstring else None
1534 1525 if info.found:
1535 1526 pmethod = getattr(self.inspector, meth)
1536 1527 # TODO: only apply format_screen to the plain/text repr of the mime
1537 1528 # bundle.
1538 1529 formatter = format_screen if info.ismagic else docformat
1539 1530 if meth == 'pdoc':
1540 1531 pmethod(info.obj, oname, formatter)
1541 1532 elif meth == 'pinfo':
1542 1533 pmethod(info.obj, oname, formatter, info,
1543 1534 enable_html_pager=self.enable_html_pager, **kw)
1544 1535 else:
1545 1536 pmethod(info.obj, oname)
1546 1537 else:
1547 1538 print('Object `%s` not found.' % oname)
1548 1539 return 'not found' # so callers can take other action
1549 1540
1550 1541 def object_inspect(self, oname, detail_level=0):
1551 1542 """Get object info about oname"""
1552 1543 with self.builtin_trap:
1553 1544 info = self._object_find(oname)
1554 1545 if info.found:
1555 1546 return self.inspector.info(info.obj, oname, info=info,
1556 1547 detail_level=detail_level
1557 1548 )
1558 1549 else:
1559 1550 return oinspect.object_info(name=oname, found=False)
1560 1551
1561 1552 def object_inspect_text(self, oname, detail_level=0):
1562 1553 """Get object info as formatted text"""
1563 1554 return self.object_inspect_mime(oname, detail_level)['text/plain']
1564 1555
1565 1556 def object_inspect_mime(self, oname, detail_level=0):
1566 1557 """Get object info as a mimebundle of formatted representations.
1567 1558
1568 1559 A mimebundle is a dictionary, keyed by mime-type.
1569 1560 It must always have the key `'text/plain'`.
1570 1561 """
1571 1562 with self.builtin_trap:
1572 1563 info = self._object_find(oname)
1573 1564 if info.found:
1574 1565 return self.inspector._get_info(info.obj, oname, info=info,
1575 1566 detail_level=detail_level
1576 1567 )
1577 1568 else:
1578 1569 raise KeyError(oname)
1579 1570
1580 1571 #-------------------------------------------------------------------------
1581 1572 # Things related to history management
1582 1573 #-------------------------------------------------------------------------
1583 1574
1584 1575 def init_history(self):
1585 1576 """Sets up the command history, and starts regular autosaves."""
1586 1577 self.history_manager = HistoryManager(shell=self, parent=self)
1587 1578 self.configurables.append(self.history_manager)
1588 1579
1589 1580 #-------------------------------------------------------------------------
1590 1581 # Things related to exception handling and tracebacks (not debugging)
1591 1582 #-------------------------------------------------------------------------
1592 1583
1593 1584 debugger_cls = Pdb
1594 1585
1595 1586 def init_traceback_handlers(self, custom_exceptions):
1596 1587 # Syntax error handler.
1597 1588 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1598 1589
1599 1590 # The interactive one is initialized with an offset, meaning we always
1600 1591 # want to remove the topmost item in the traceback, which is our own
1601 1592 # internal code. Valid modes: ['Plain','Context','Verbose']
1602 1593 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1603 1594 color_scheme='NoColor',
1604 1595 tb_offset = 1,
1605 1596 check_cache=check_linecache_ipython,
1606 1597 debugger_cls=self.debugger_cls)
1607 1598
1608 1599 # The instance will store a pointer to the system-wide exception hook,
1609 1600 # so that runtime code (such as magics) can access it. This is because
1610 1601 # during the read-eval loop, it may get temporarily overwritten.
1611 1602 self.sys_excepthook = sys.excepthook
1612 1603
1613 1604 # and add any custom exception handlers the user may have specified
1614 1605 self.set_custom_exc(*custom_exceptions)
1615 1606
1616 1607 # Set the exception mode
1617 1608 self.InteractiveTB.set_mode(mode=self.xmode)
1618 1609
1619 1610 def set_custom_exc(self, exc_tuple, handler):
1620 1611 """set_custom_exc(exc_tuple, handler)
1621 1612
1622 1613 Set a custom exception handler, which will be called if any of the
1623 1614 exceptions in exc_tuple occur in the mainloop (specifically, in the
1624 1615 run_code() method).
1625 1616
1626 1617 Parameters
1627 1618 ----------
1628 1619
1629 1620 exc_tuple : tuple of exception classes
1630 1621 A *tuple* of exception classes, for which to call the defined
1631 1622 handler. It is very important that you use a tuple, and NOT A
1632 1623 LIST here, because of the way Python's except statement works. If
1633 1624 you only want to trap a single exception, use a singleton tuple::
1634 1625
1635 1626 exc_tuple == (MyCustomException,)
1636 1627
1637 1628 handler : callable
1638 1629 handler must have the following signature::
1639 1630
1640 1631 def my_handler(self, etype, value, tb, tb_offset=None):
1641 1632 ...
1642 1633 return structured_traceback
1643 1634
1644 1635 Your handler must return a structured traceback (a list of strings),
1645 1636 or None.
1646 1637
1647 1638 This will be made into an instance method (via types.MethodType)
1648 1639 of IPython itself, and it will be called if any of the exceptions
1649 1640 listed in the exc_tuple are caught. If the handler is None, an
1650 1641 internal basic one is used, which just prints basic info.
1651 1642
1652 1643 To protect IPython from crashes, if your handler ever raises an
1653 1644 exception or returns an invalid result, it will be immediately
1654 1645 disabled.
1655 1646
1656 1647 WARNING: by putting in your own exception handler into IPython's main
1657 1648 execution loop, you run a very good chance of nasty crashes. This
1658 1649 facility should only be used if you really know what you are doing."""
1659 1650
1660 1651 assert type(exc_tuple)==type(()) , \
1661 1652 "The custom exceptions must be given AS A TUPLE."
1662 1653
1663 1654 def dummy_handler(self, etype, value, tb, tb_offset=None):
1664 1655 print('*** Simple custom exception handler ***')
1665 1656 print('Exception type :',etype)
1666 1657 print('Exception value:',value)
1667 1658 print('Traceback :',tb)
1668 1659 #print 'Source code :','\n'.join(self.buffer)
1669 1660
1670 1661 def validate_stb(stb):
1671 1662 """validate structured traceback return type
1672 1663
1673 1664 return type of CustomTB *should* be a list of strings, but allow
1674 1665 single strings or None, which are harmless.
1675 1666
1676 1667 This function will *always* return a list of strings,
1677 1668 and will raise a TypeError if stb is inappropriate.
1678 1669 """
1679 1670 msg = "CustomTB must return list of strings, not %r" % stb
1680 1671 if stb is None:
1681 1672 return []
1682 1673 elif isinstance(stb, string_types):
1683 1674 return [stb]
1684 1675 elif not isinstance(stb, list):
1685 1676 raise TypeError(msg)
1686 1677 # it's a list
1687 1678 for line in stb:
1688 1679 # check every element
1689 1680 if not isinstance(line, string_types):
1690 1681 raise TypeError(msg)
1691 1682 return stb
1692 1683
1693 1684 if handler is None:
1694 1685 wrapped = dummy_handler
1695 1686 else:
1696 1687 def wrapped(self,etype,value,tb,tb_offset=None):
1697 1688 """wrap CustomTB handler, to protect IPython from user code
1698 1689
1699 1690 This makes it harder (but not impossible) for custom exception
1700 1691 handlers to crash IPython.
1701 1692 """
1702 1693 try:
1703 1694 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1704 1695 return validate_stb(stb)
1705 1696 except:
1706 1697 # clear custom handler immediately
1707 1698 self.set_custom_exc((), None)
1708 1699 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1709 1700 # show the exception in handler first
1710 1701 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1711 1702 print(self.InteractiveTB.stb2text(stb))
1712 1703 print("The original exception:")
1713 1704 stb = self.InteractiveTB.structured_traceback(
1714 1705 (etype,value,tb), tb_offset=tb_offset
1715 1706 )
1716 1707 return stb
1717 1708
1718 1709 self.CustomTB = types.MethodType(wrapped,self)
1719 1710 self.custom_exceptions = exc_tuple
1720 1711
1721 1712 def excepthook(self, etype, value, tb):
1722 1713 """One more defense for GUI apps that call sys.excepthook.
1723 1714
1724 1715 GUI frameworks like wxPython trap exceptions and call
1725 1716 sys.excepthook themselves. I guess this is a feature that
1726 1717 enables them to keep running after exceptions that would
1727 1718 otherwise kill their mainloop. This is a bother for IPython
1728 1719 which excepts to catch all of the program exceptions with a try:
1729 1720 except: statement.
1730 1721
1731 1722 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1732 1723 any app directly invokes sys.excepthook, it will look to the user like
1733 1724 IPython crashed. In order to work around this, we can disable the
1734 1725 CrashHandler and replace it with this excepthook instead, which prints a
1735 1726 regular traceback using our InteractiveTB. In this fashion, apps which
1736 1727 call sys.excepthook will generate a regular-looking exception from
1737 1728 IPython, and the CrashHandler will only be triggered by real IPython
1738 1729 crashes.
1739 1730
1740 1731 This hook should be used sparingly, only in places which are not likely
1741 1732 to be true IPython errors.
1742 1733 """
1743 1734 self.showtraceback((etype, value, tb), tb_offset=0)
1744 1735
1745 1736 def _get_exc_info(self, exc_tuple=None):
1746 1737 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1747 1738
1748 1739 Ensures sys.last_type,value,traceback hold the exc_info we found,
1749 1740 from whichever source.
1750 1741
1751 1742 raises ValueError if none of these contain any information
1752 1743 """
1753 1744 if exc_tuple is None:
1754 1745 etype, value, tb = sys.exc_info()
1755 1746 else:
1756 1747 etype, value, tb = exc_tuple
1757 1748
1758 1749 if etype is None:
1759 1750 if hasattr(sys, 'last_type'):
1760 1751 etype, value, tb = sys.last_type, sys.last_value, \
1761 1752 sys.last_traceback
1762 1753
1763 1754 if etype is None:
1764 1755 raise ValueError("No exception to find")
1765 1756
1766 1757 # Now store the exception info in sys.last_type etc.
1767 1758 # WARNING: these variables are somewhat deprecated and not
1768 1759 # necessarily safe to use in a threaded environment, but tools
1769 1760 # like pdb depend on their existence, so let's set them. If we
1770 1761 # find problems in the field, we'll need to revisit their use.
1771 1762 sys.last_type = etype
1772 1763 sys.last_value = value
1773 1764 sys.last_traceback = tb
1774 1765
1775 1766 return etype, value, tb
1776 1767
1777 1768 def show_usage_error(self, exc):
1778 1769 """Show a short message for UsageErrors
1779 1770
1780 1771 These are special exceptions that shouldn't show a traceback.
1781 1772 """
1782 1773 print("UsageError: %s" % exc, file=sys.stderr)
1783 1774
1784 1775 def get_exception_only(self, exc_tuple=None):
1785 1776 """
1786 1777 Return as a string (ending with a newline) the exception that
1787 1778 just occurred, without any traceback.
1788 1779 """
1789 1780 etype, value, tb = self._get_exc_info(exc_tuple)
1790 1781 msg = traceback.format_exception_only(etype, value)
1791 1782 return ''.join(msg)
1792 1783
1793 1784 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1794 1785 exception_only=False):
1795 1786 """Display the exception that just occurred.
1796 1787
1797 1788 If nothing is known about the exception, this is the method which
1798 1789 should be used throughout the code for presenting user tracebacks,
1799 1790 rather than directly invoking the InteractiveTB object.
1800 1791
1801 1792 A specific showsyntaxerror() also exists, but this method can take
1802 1793 care of calling it if needed, so unless you are explicitly catching a
1803 1794 SyntaxError exception, don't try to analyze the stack manually and
1804 1795 simply call this method."""
1805 1796
1806 1797 try:
1807 1798 try:
1808 1799 etype, value, tb = self._get_exc_info(exc_tuple)
1809 1800 except ValueError:
1810 1801 print('No traceback available to show.', file=sys.stderr)
1811 1802 return
1812 1803
1813 1804 if issubclass(etype, SyntaxError):
1814 1805 # Though this won't be called by syntax errors in the input
1815 1806 # line, there may be SyntaxError cases with imported code.
1816 1807 self.showsyntaxerror(filename)
1817 1808 elif etype is UsageError:
1818 1809 self.show_usage_error(value)
1819 1810 else:
1820 1811 if exception_only:
1821 1812 stb = ['An exception has occurred, use %tb to see '
1822 1813 'the full traceback.\n']
1823 1814 stb.extend(self.InteractiveTB.get_exception_only(etype,
1824 1815 value))
1825 1816 else:
1826 1817 try:
1827 1818 # Exception classes can customise their traceback - we
1828 1819 # use this in IPython.parallel for exceptions occurring
1829 1820 # in the engines. This should return a list of strings.
1830 1821 stb = value._render_traceback_()
1831 1822 except Exception:
1832 1823 stb = self.InteractiveTB.structured_traceback(etype,
1833 1824 value, tb, tb_offset=tb_offset)
1834 1825
1835 1826 self._showtraceback(etype, value, stb)
1836 1827 if self.call_pdb:
1837 1828 # drop into debugger
1838 1829 self.debugger(force=True)
1839 1830 return
1840 1831
1841 1832 # Actually show the traceback
1842 1833 self._showtraceback(etype, value, stb)
1843 1834
1844 1835 except KeyboardInterrupt:
1845 1836 print('\n' + self.get_exception_only(), file=sys.stderr)
1846 1837
1847 1838 def _showtraceback(self, etype, evalue, stb):
1848 1839 """Actually show a traceback.
1849 1840
1850 1841 Subclasses may override this method to put the traceback on a different
1851 1842 place, like a side channel.
1852 1843 """
1853 1844 print(self.InteractiveTB.stb2text(stb))
1854 1845
1855 1846 def showsyntaxerror(self, filename=None):
1856 1847 """Display the syntax error that just occurred.
1857 1848
1858 1849 This doesn't display a stack trace because there isn't one.
1859 1850
1860 1851 If a filename is given, it is stuffed in the exception instead
1861 1852 of what was there before (because Python's parser always uses
1862 1853 "<string>" when reading from a string).
1863 1854 """
1864 1855 etype, value, last_traceback = self._get_exc_info()
1865 1856
1866 1857 if filename and issubclass(etype, SyntaxError):
1867 1858 try:
1868 1859 value.filename = filename
1869 1860 except:
1870 1861 # Not the format we expect; leave it alone
1871 1862 pass
1872 1863
1873 1864 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1874 1865 self._showtraceback(etype, value, stb)
1875 1866
1876 1867 # This is overridden in TerminalInteractiveShell to show a message about
1877 1868 # the %paste magic.
1878 1869 def showindentationerror(self):
1879 1870 """Called by run_cell when there's an IndentationError in code entered
1880 1871 at the prompt.
1881 1872
1882 1873 This is overridden in TerminalInteractiveShell to show a message about
1883 1874 the %paste magic."""
1884 1875 self.showsyntaxerror()
1885 1876
1886 1877 #-------------------------------------------------------------------------
1887 1878 # Things related to readline
1888 1879 #-------------------------------------------------------------------------
1889 1880
1890 1881 def init_readline(self):
1891 1882 """Moved to terminal subclass, here only to simplify the init logic."""
1892 self.readline = None
1893 1883 # Set a number of methods that depend on readline to be no-op
1894 self.readline_no_record = NoOpContext()
1895 self.set_readline_completer = no_op
1896 1884 self.set_custom_completer = no_op
1897 1885
1898 1886 @skip_doctest
1899 1887 def set_next_input(self, s, replace=False):
1900 1888 """ Sets the 'default' input string for the next command line.
1901 1889
1902 1890 Example::
1903 1891
1904 1892 In [1]: _ip.set_next_input("Hello Word")
1905 1893 In [2]: Hello Word_ # cursor is here
1906 1894 """
1907 1895 self.rl_next_input = py3compat.cast_bytes_py2(s)
1908 1896
1909 1897 def _indent_current_str(self):
1910 1898 """return the current level of indentation as a string"""
1911 1899 return self.input_splitter.indent_spaces * ' '
1912 1900
1913 1901 #-------------------------------------------------------------------------
1914 1902 # Things related to text completion
1915 1903 #-------------------------------------------------------------------------
1916 1904
1917 1905 def init_completer(self):
1918 1906 """Initialize the completion machinery.
1919 1907
1920 1908 This creates completion machinery that can be used by client code,
1921 1909 either interactively in-process (typically triggered by the readline
1922 1910 library), programmatically (such as in test suites) or out-of-process
1923 1911 (typically over the network by remote frontends).
1924 1912 """
1925 1913 from IPython.core.completer import IPCompleter
1926 1914 from IPython.core.completerlib import (module_completer,
1927 1915 magic_run_completer, cd_completer, reset_completer)
1928 1916
1929 1917 self.Completer = IPCompleter(shell=self,
1930 1918 namespace=self.user_ns,
1931 1919 global_namespace=self.user_global_ns,
1932 use_readline=self.has_readline,
1920 use_readline=False,
1933 1921 parent=self,
1934 1922 )
1935 1923 self.configurables.append(self.Completer)
1936 1924
1937 1925 # Add custom completers to the basic ones built into IPCompleter
1938 1926 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1939 1927 self.strdispatchers['complete_command'] = sdisp
1940 1928 self.Completer.custom_completers = sdisp
1941 1929
1942 1930 self.set_hook('complete_command', module_completer, str_key = 'import')
1943 1931 self.set_hook('complete_command', module_completer, str_key = 'from')
1944 1932 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1945 1933 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1946 1934 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1947 1935 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1948 1936
1949 1937
1950 1938 @skip_doctest_py2
1951 1939 def complete(self, text, line=None, cursor_pos=None):
1952 1940 """Return the completed text and a list of completions.
1953 1941
1954 1942 Parameters
1955 1943 ----------
1956 1944
1957 1945 text : string
1958 1946 A string of text to be completed on. It can be given as empty and
1959 1947 instead a line/position pair are given. In this case, the
1960 1948 completer itself will split the line like readline does.
1961 1949
1962 1950 line : string, optional
1963 1951 The complete line that text is part of.
1964 1952
1965 1953 cursor_pos : int, optional
1966 1954 The position of the cursor on the input line.
1967 1955
1968 1956 Returns
1969 1957 -------
1970 1958 text : string
1971 1959 The actual text that was completed.
1972 1960
1973 1961 matches : list
1974 1962 A sorted list with all possible completions.
1975 1963
1976 1964 The optional arguments allow the completion to take more context into
1977 1965 account, and are part of the low-level completion API.
1978 1966
1979 1967 This is a wrapper around the completion mechanism, similar to what
1980 1968 readline does at the command line when the TAB key is hit. By
1981 1969 exposing it as a method, it can be used by other non-readline
1982 1970 environments (such as GUIs) for text completion.
1983 1971
1984 1972 Simple usage example:
1985 1973
1986 1974 In [1]: x = 'hello'
1987 1975
1988 1976 In [2]: _ip.complete('x.l')
1989 1977 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1990 1978 """
1991 1979
1992 1980 # Inject names into __builtin__ so we can complete on the added names.
1993 1981 with self.builtin_trap:
1994 1982 return self.Completer.complete(text, line, cursor_pos)
1995 1983
1996 1984 def set_custom_completer(self, completer, pos=0):
1997 1985 """Adds a new custom completer function.
1998 1986
1999 1987 The position argument (defaults to 0) is the index in the completers
2000 1988 list where you want the completer to be inserted."""
2001 1989
2002 1990 newcomp = types.MethodType(completer,self.Completer)
2003 1991 self.Completer.matchers.insert(pos,newcomp)
2004 1992
2005 1993 def set_completer_frame(self, frame=None):
2006 1994 """Set the frame of the completer."""
2007 1995 if frame:
2008 1996 self.Completer.namespace = frame.f_locals
2009 1997 self.Completer.global_namespace = frame.f_globals
2010 1998 else:
2011 1999 self.Completer.namespace = self.user_ns
2012 2000 self.Completer.global_namespace = self.user_global_ns
2013 2001
2014 2002 #-------------------------------------------------------------------------
2015 2003 # Things related to magics
2016 2004 #-------------------------------------------------------------------------
2017 2005
2018 2006 def init_magics(self):
2019 2007 from IPython.core import magics as m
2020 2008 self.magics_manager = magic.MagicsManager(shell=self,
2021 2009 parent=self,
2022 2010 user_magics=m.UserMagics(self))
2023 2011 self.configurables.append(self.magics_manager)
2024 2012
2025 2013 # Expose as public API from the magics manager
2026 2014 self.register_magics = self.magics_manager.register
2027 2015
2028 2016 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2029 2017 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2030 2018 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2031 2019 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2032 2020 )
2033 2021
2034 2022 # Register Magic Aliases
2035 2023 mman = self.magics_manager
2036 2024 # FIXME: magic aliases should be defined by the Magics classes
2037 2025 # or in MagicsManager, not here
2038 2026 mman.register_alias('ed', 'edit')
2039 2027 mman.register_alias('hist', 'history')
2040 2028 mman.register_alias('rep', 'recall')
2041 2029 mman.register_alias('SVG', 'svg', 'cell')
2042 2030 mman.register_alias('HTML', 'html', 'cell')
2043 2031 mman.register_alias('file', 'writefile', 'cell')
2044 2032
2045 2033 # FIXME: Move the color initialization to the DisplayHook, which
2046 2034 # should be split into a prompt manager and displayhook. We probably
2047 2035 # even need a centralize colors management object.
2048 2036 self.magic('colors %s' % self.colors)
2049 2037
2050 2038 # Defined here so that it's included in the documentation
2051 2039 @functools.wraps(magic.MagicsManager.register_function)
2052 2040 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2053 2041 self.magics_manager.register_function(func,
2054 2042 magic_kind=magic_kind, magic_name=magic_name)
2055 2043
2056 2044 def run_line_magic(self, magic_name, line):
2057 2045 """Execute the given line magic.
2058 2046
2059 2047 Parameters
2060 2048 ----------
2061 2049 magic_name : str
2062 2050 Name of the desired magic function, without '%' prefix.
2063 2051
2064 2052 line : str
2065 2053 The rest of the input line as a single string.
2066 2054 """
2067 2055 fn = self.find_line_magic(magic_name)
2068 2056 if fn is None:
2069 2057 cm = self.find_cell_magic(magic_name)
2070 2058 etpl = "Line magic function `%%%s` not found%s."
2071 2059 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2072 2060 'did you mean that instead?)' % magic_name )
2073 2061 error(etpl % (magic_name, extra))
2074 2062 else:
2075 2063 # Note: this is the distance in the stack to the user's frame.
2076 2064 # This will need to be updated if the internal calling logic gets
2077 2065 # refactored, or else we'll be expanding the wrong variables.
2078 2066 stack_depth = 2
2079 2067 magic_arg_s = self.var_expand(line, stack_depth)
2080 2068 # Put magic args in a list so we can call with f(*a) syntax
2081 2069 args = [magic_arg_s]
2082 2070 kwargs = {}
2083 2071 # Grab local namespace if we need it:
2084 2072 if getattr(fn, "needs_local_scope", False):
2085 2073 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2086 2074 with self.builtin_trap:
2087 2075 result = fn(*args,**kwargs)
2088 2076 return result
2089 2077
2090 2078 def run_cell_magic(self, magic_name, line, cell):
2091 2079 """Execute the given cell magic.
2092 2080
2093 2081 Parameters
2094 2082 ----------
2095 2083 magic_name : str
2096 2084 Name of the desired magic function, without '%' prefix.
2097 2085
2098 2086 line : str
2099 2087 The rest of the first input line as a single string.
2100 2088
2101 2089 cell : str
2102 2090 The body of the cell as a (possibly multiline) string.
2103 2091 """
2104 2092 fn = self.find_cell_magic(magic_name)
2105 2093 if fn is None:
2106 2094 lm = self.find_line_magic(magic_name)
2107 2095 etpl = "Cell magic `%%{0}` not found{1}."
2108 2096 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2109 2097 'did you mean that instead?)'.format(magic_name))
2110 2098 error(etpl.format(magic_name, extra))
2111 2099 elif cell == '':
2112 2100 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2113 2101 if self.find_line_magic(magic_name) is not None:
2114 2102 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2115 2103 raise UsageError(message)
2116 2104 else:
2117 2105 # Note: this is the distance in the stack to the user's frame.
2118 2106 # This will need to be updated if the internal calling logic gets
2119 2107 # refactored, or else we'll be expanding the wrong variables.
2120 2108 stack_depth = 2
2121 2109 magic_arg_s = self.var_expand(line, stack_depth)
2122 2110 with self.builtin_trap:
2123 2111 result = fn(magic_arg_s, cell)
2124 2112 return result
2125 2113
2126 2114 def find_line_magic(self, magic_name):
2127 2115 """Find and return a line magic by name.
2128 2116
2129 2117 Returns None if the magic isn't found."""
2130 2118 return self.magics_manager.magics['line'].get(magic_name)
2131 2119
2132 2120 def find_cell_magic(self, magic_name):
2133 2121 """Find and return a cell magic by name.
2134 2122
2135 2123 Returns None if the magic isn't found."""
2136 2124 return self.magics_manager.magics['cell'].get(magic_name)
2137 2125
2138 2126 def find_magic(self, magic_name, magic_kind='line'):
2139 2127 """Find and return a magic of the given type by name.
2140 2128
2141 2129 Returns None if the magic isn't found."""
2142 2130 return self.magics_manager.magics[magic_kind].get(magic_name)
2143 2131
2144 2132 def magic(self, arg_s):
2145 2133 """DEPRECATED. Use run_line_magic() instead.
2146 2134
2147 2135 Call a magic function by name.
2148 2136
2149 2137 Input: a string containing the name of the magic function to call and
2150 2138 any additional arguments to be passed to the magic.
2151 2139
2152 2140 magic('name -opt foo bar') is equivalent to typing at the ipython
2153 2141 prompt:
2154 2142
2155 2143 In[1]: %name -opt foo bar
2156 2144
2157 2145 To call a magic without arguments, simply use magic('name').
2158 2146
2159 2147 This provides a proper Python function to call IPython's magics in any
2160 2148 valid Python code you can type at the interpreter, including loops and
2161 2149 compound statements.
2162 2150 """
2163 2151 # TODO: should we issue a loud deprecation warning here?
2164 2152 magic_name, _, magic_arg_s = arg_s.partition(' ')
2165 2153 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2166 2154 return self.run_line_magic(magic_name, magic_arg_s)
2167 2155
2168 2156 #-------------------------------------------------------------------------
2169 2157 # Things related to macros
2170 2158 #-------------------------------------------------------------------------
2171 2159
2172 2160 def define_macro(self, name, themacro):
2173 2161 """Define a new macro
2174 2162
2175 2163 Parameters
2176 2164 ----------
2177 2165 name : str
2178 2166 The name of the macro.
2179 2167 themacro : str or Macro
2180 2168 The action to do upon invoking the macro. If a string, a new
2181 2169 Macro object is created by passing the string to it.
2182 2170 """
2183 2171
2184 2172 from IPython.core import macro
2185 2173
2186 2174 if isinstance(themacro, string_types):
2187 2175 themacro = macro.Macro(themacro)
2188 2176 if not isinstance(themacro, macro.Macro):
2189 2177 raise ValueError('A macro must be a string or a Macro instance.')
2190 2178 self.user_ns[name] = themacro
2191 2179
2192 2180 #-------------------------------------------------------------------------
2193 2181 # Things related to the running of system commands
2194 2182 #-------------------------------------------------------------------------
2195 2183
2196 2184 def system_piped(self, cmd):
2197 2185 """Call the given cmd in a subprocess, piping stdout/err
2198 2186
2199 2187 Parameters
2200 2188 ----------
2201 2189 cmd : str
2202 2190 Command to execute (can not end in '&', as background processes are
2203 2191 not supported. Should not be a command that expects input
2204 2192 other than simple text.
2205 2193 """
2206 2194 if cmd.rstrip().endswith('&'):
2207 2195 # this is *far* from a rigorous test
2208 2196 # We do not support backgrounding processes because we either use
2209 2197 # pexpect or pipes to read from. Users can always just call
2210 2198 # os.system() or use ip.system=ip.system_raw
2211 2199 # if they really want a background process.
2212 2200 raise OSError("Background processes not supported.")
2213 2201
2214 2202 # we explicitly do NOT return the subprocess status code, because
2215 2203 # a non-None value would trigger :func:`sys.displayhook` calls.
2216 2204 # Instead, we store the exit_code in user_ns.
2217 2205 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2218 2206
2219 2207 def system_raw(self, cmd):
2220 2208 """Call the given cmd in a subprocess using os.system on Windows or
2221 2209 subprocess.call using the system shell on other platforms.
2222 2210
2223 2211 Parameters
2224 2212 ----------
2225 2213 cmd : str
2226 2214 Command to execute.
2227 2215 """
2228 2216 cmd = self.var_expand(cmd, depth=1)
2229 2217 # protect os.system from UNC paths on Windows, which it can't handle:
2230 2218 if sys.platform == 'win32':
2231 2219 from IPython.utils._process_win32 import AvoidUNCPath
2232 2220 with AvoidUNCPath() as path:
2233 2221 if path is not None:
2234 2222 cmd = '"pushd %s &&"%s' % (path, cmd)
2235 2223 cmd = py3compat.unicode_to_str(cmd)
2236 2224 try:
2237 2225 ec = os.system(cmd)
2238 2226 except KeyboardInterrupt:
2239 2227 print('\n' + self.get_exception_only(), file=sys.stderr)
2240 2228 ec = -2
2241 2229 else:
2242 2230 cmd = py3compat.unicode_to_str(cmd)
2243 2231 # For posix the result of the subprocess.call() below is an exit
2244 2232 # code, which by convention is zero for success, positive for
2245 2233 # program failure. Exit codes above 128 are reserved for signals,
2246 2234 # and the formula for converting a signal to an exit code is usually
2247 2235 # signal_number+128. To more easily differentiate between exit
2248 2236 # codes and signals, ipython uses negative numbers. For instance
2249 2237 # since control-c is signal 2 but exit code 130, ipython's
2250 2238 # _exit_code variable will read -2. Note that some shells like
2251 2239 # csh and fish don't follow sh/bash conventions for exit codes.
2252 2240 executable = os.environ.get('SHELL', None)
2253 2241 try:
2254 2242 # Use env shell instead of default /bin/sh
2255 2243 ec = subprocess.call(cmd, shell=True, executable=executable)
2256 2244 except KeyboardInterrupt:
2257 2245 # intercept control-C; a long traceback is not useful here
2258 2246 print('\n' + self.get_exception_only(), file=sys.stderr)
2259 2247 ec = 130
2260 2248 if ec > 128:
2261 2249 ec = -(ec - 128)
2262 2250
2263 2251 # We explicitly do NOT return the subprocess status code, because
2264 2252 # a non-None value would trigger :func:`sys.displayhook` calls.
2265 2253 # Instead, we store the exit_code in user_ns. Note the semantics
2266 2254 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2267 2255 # but raising SystemExit(_exit_code) will give status 254!
2268 2256 self.user_ns['_exit_code'] = ec
2269 2257
2270 2258 # use piped system by default, because it is better behaved
2271 2259 system = system_piped
2272 2260
2273 2261 def getoutput(self, cmd, split=True, depth=0):
2274 2262 """Get output (possibly including stderr) from a subprocess.
2275 2263
2276 2264 Parameters
2277 2265 ----------
2278 2266 cmd : str
2279 2267 Command to execute (can not end in '&', as background processes are
2280 2268 not supported.
2281 2269 split : bool, optional
2282 2270 If True, split the output into an IPython SList. Otherwise, an
2283 2271 IPython LSString is returned. These are objects similar to normal
2284 2272 lists and strings, with a few convenience attributes for easier
2285 2273 manipulation of line-based output. You can use '?' on them for
2286 2274 details.
2287 2275 depth : int, optional
2288 2276 How many frames above the caller are the local variables which should
2289 2277 be expanded in the command string? The default (0) assumes that the
2290 2278 expansion variables are in the stack frame calling this function.
2291 2279 """
2292 2280 if cmd.rstrip().endswith('&'):
2293 2281 # this is *far* from a rigorous test
2294 2282 raise OSError("Background processes not supported.")
2295 2283 out = getoutput(self.var_expand(cmd, depth=depth+1))
2296 2284 if split:
2297 2285 out = SList(out.splitlines())
2298 2286 else:
2299 2287 out = LSString(out)
2300 2288 return out
2301 2289
2302 2290 #-------------------------------------------------------------------------
2303 2291 # Things related to aliases
2304 2292 #-------------------------------------------------------------------------
2305 2293
2306 2294 def init_alias(self):
2307 2295 self.alias_manager = AliasManager(shell=self, parent=self)
2308 2296 self.configurables.append(self.alias_manager)
2309 2297
2310 2298 #-------------------------------------------------------------------------
2311 2299 # Things related to extensions
2312 2300 #-------------------------------------------------------------------------
2313 2301
2314 2302 def init_extension_manager(self):
2315 2303 self.extension_manager = ExtensionManager(shell=self, parent=self)
2316 2304 self.configurables.append(self.extension_manager)
2317 2305
2318 2306 #-------------------------------------------------------------------------
2319 2307 # Things related to payloads
2320 2308 #-------------------------------------------------------------------------
2321 2309
2322 2310 def init_payload(self):
2323 2311 self.payload_manager = PayloadManager(parent=self)
2324 2312 self.configurables.append(self.payload_manager)
2325 2313
2326 2314 #-------------------------------------------------------------------------
2327 2315 # Things related to the prefilter
2328 2316 #-------------------------------------------------------------------------
2329 2317
2330 2318 def init_prefilter(self):
2331 2319 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2332 2320 self.configurables.append(self.prefilter_manager)
2333 2321 # Ultimately this will be refactored in the new interpreter code, but
2334 2322 # for now, we should expose the main prefilter method (there's legacy
2335 2323 # code out there that may rely on this).
2336 2324 self.prefilter = self.prefilter_manager.prefilter_lines
2337 2325
2338 2326 def auto_rewrite_input(self, cmd):
2339 2327 """Print to the screen the rewritten form of the user's command.
2340 2328
2341 2329 This shows visual feedback by rewriting input lines that cause
2342 2330 automatic calling to kick in, like::
2343 2331
2344 2332 /f x
2345 2333
2346 2334 into::
2347 2335
2348 2336 ------> f(x)
2349 2337
2350 2338 after the user's input prompt. This helps the user understand that the
2351 2339 input line was transformed automatically by IPython.
2352 2340 """
2353 2341 if not self.show_rewritten_input:
2354 2342 return
2355 2343
2356 2344 # This is overridden in TerminalInteractiveShell to use fancy prompts
2357 2345 print("------> " + cmd)
2358 2346
2359 2347 #-------------------------------------------------------------------------
2360 2348 # Things related to extracting values/expressions from kernel and user_ns
2361 2349 #-------------------------------------------------------------------------
2362 2350
2363 2351 def _user_obj_error(self):
2364 2352 """return simple exception dict
2365 2353
2366 2354 for use in user_expressions
2367 2355 """
2368 2356
2369 2357 etype, evalue, tb = self._get_exc_info()
2370 2358 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2371 2359
2372 2360 exc_info = {
2373 2361 u'status' : 'error',
2374 2362 u'traceback' : stb,
2375 2363 u'ename' : unicode_type(etype.__name__),
2376 2364 u'evalue' : py3compat.safe_unicode(evalue),
2377 2365 }
2378 2366
2379 2367 return exc_info
2380 2368
2381 2369 def _format_user_obj(self, obj):
2382 2370 """format a user object to display dict
2383 2371
2384 2372 for use in user_expressions
2385 2373 """
2386 2374
2387 2375 data, md = self.display_formatter.format(obj)
2388 2376 value = {
2389 2377 'status' : 'ok',
2390 2378 'data' : data,
2391 2379 'metadata' : md,
2392 2380 }
2393 2381 return value
2394 2382
2395 2383 def user_expressions(self, expressions):
2396 2384 """Evaluate a dict of expressions in the user's namespace.
2397 2385
2398 2386 Parameters
2399 2387 ----------
2400 2388 expressions : dict
2401 2389 A dict with string keys and string values. The expression values
2402 2390 should be valid Python expressions, each of which will be evaluated
2403 2391 in the user namespace.
2404 2392
2405 2393 Returns
2406 2394 -------
2407 2395 A dict, keyed like the input expressions dict, with the rich mime-typed
2408 2396 display_data of each value.
2409 2397 """
2410 2398 out = {}
2411 2399 user_ns = self.user_ns
2412 2400 global_ns = self.user_global_ns
2413 2401
2414 2402 for key, expr in iteritems(expressions):
2415 2403 try:
2416 2404 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2417 2405 except:
2418 2406 value = self._user_obj_error()
2419 2407 out[key] = value
2420 2408 return out
2421 2409
2422 2410 #-------------------------------------------------------------------------
2423 2411 # Things related to the running of code
2424 2412 #-------------------------------------------------------------------------
2425 2413
2426 2414 def ex(self, cmd):
2427 2415 """Execute a normal python statement in user namespace."""
2428 2416 with self.builtin_trap:
2429 2417 exec(cmd, self.user_global_ns, self.user_ns)
2430 2418
2431 2419 def ev(self, expr):
2432 2420 """Evaluate python expression expr in user namespace.
2433 2421
2434 2422 Returns the result of evaluation
2435 2423 """
2436 2424 with self.builtin_trap:
2437 2425 return eval(expr, self.user_global_ns, self.user_ns)
2438 2426
2439 2427 def safe_execfile(self, fname, *where, **kw):
2440 2428 """A safe version of the builtin execfile().
2441 2429
2442 2430 This version will never throw an exception, but instead print
2443 2431 helpful error messages to the screen. This only works on pure
2444 2432 Python files with the .py extension.
2445 2433
2446 2434 Parameters
2447 2435 ----------
2448 2436 fname : string
2449 2437 The name of the file to be executed.
2450 2438 where : tuple
2451 2439 One or two namespaces, passed to execfile() as (globals,locals).
2452 2440 If only one is given, it is passed as both.
2453 2441 exit_ignore : bool (False)
2454 2442 If True, then silence SystemExit for non-zero status (it is always
2455 2443 silenced for zero status, as it is so common).
2456 2444 raise_exceptions : bool (False)
2457 2445 If True raise exceptions everywhere. Meant for testing.
2458 2446 shell_futures : bool (False)
2459 2447 If True, the code will share future statements with the interactive
2460 2448 shell. It will both be affected by previous __future__ imports, and
2461 2449 any __future__ imports in the code will affect the shell. If False,
2462 2450 __future__ imports are not shared in either direction.
2463 2451
2464 2452 """
2465 2453 kw.setdefault('exit_ignore', False)
2466 2454 kw.setdefault('raise_exceptions', False)
2467 2455 kw.setdefault('shell_futures', False)
2468 2456
2469 2457 fname = os.path.abspath(os.path.expanduser(fname))
2470 2458
2471 2459 # Make sure we can open the file
2472 2460 try:
2473 2461 with open(fname):
2474 2462 pass
2475 2463 except:
2476 2464 warn('Could not open file <%s> for safe execution.' % fname)
2477 2465 return
2478 2466
2479 2467 # Find things also in current directory. This is needed to mimic the
2480 2468 # behavior of running a script from the system command line, where
2481 2469 # Python inserts the script's directory into sys.path
2482 2470 dname = os.path.dirname(fname)
2483 2471
2484 2472 with prepended_to_syspath(dname):
2485 2473 try:
2486 2474 glob, loc = (where + (None, ))[:2]
2487 2475 py3compat.execfile(
2488 2476 fname, glob, loc,
2489 2477 self.compile if kw['shell_futures'] else None)
2490 2478 except SystemExit as status:
2491 2479 # If the call was made with 0 or None exit status (sys.exit(0)
2492 2480 # or sys.exit() ), don't bother showing a traceback, as both of
2493 2481 # these are considered normal by the OS:
2494 2482 # > python -c'import sys;sys.exit(0)'; echo $?
2495 2483 # 0
2496 2484 # > python -c'import sys;sys.exit()'; echo $?
2497 2485 # 0
2498 2486 # For other exit status, we show the exception unless
2499 2487 # explicitly silenced, but only in short form.
2500 2488 if status.code:
2501 2489 if kw['raise_exceptions']:
2502 2490 raise
2503 2491 if not kw['exit_ignore']:
2504 2492 self.showtraceback(exception_only=True)
2505 2493 except:
2506 2494 if kw['raise_exceptions']:
2507 2495 raise
2508 2496 # tb offset is 2 because we wrap execfile
2509 2497 self.showtraceback(tb_offset=2)
2510 2498
2511 2499 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2512 2500 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2513 2501
2514 2502 Parameters
2515 2503 ----------
2516 2504 fname : str
2517 2505 The name of the file to execute. The filename must have a
2518 2506 .ipy or .ipynb extension.
2519 2507 shell_futures : bool (False)
2520 2508 If True, the code will share future statements with the interactive
2521 2509 shell. It will both be affected by previous __future__ imports, and
2522 2510 any __future__ imports in the code will affect the shell. If False,
2523 2511 __future__ imports are not shared in either direction.
2524 2512 raise_exceptions : bool (False)
2525 2513 If True raise exceptions everywhere. Meant for testing.
2526 2514 """
2527 2515 fname = os.path.abspath(os.path.expanduser(fname))
2528 2516
2529 2517 # Make sure we can open the file
2530 2518 try:
2531 2519 with open(fname):
2532 2520 pass
2533 2521 except:
2534 2522 warn('Could not open file <%s> for safe execution.' % fname)
2535 2523 return
2536 2524
2537 2525 # Find things also in current directory. This is needed to mimic the
2538 2526 # behavior of running a script from the system command line, where
2539 2527 # Python inserts the script's directory into sys.path
2540 2528 dname = os.path.dirname(fname)
2541 2529
2542 2530 def get_cells():
2543 2531 """generator for sequence of code blocks to run"""
2544 2532 if fname.endswith('.ipynb'):
2545 2533 from nbformat import read
2546 2534 with io_open(fname) as f:
2547 2535 nb = read(f, as_version=4)
2548 2536 if not nb.cells:
2549 2537 return
2550 2538 for cell in nb.cells:
2551 2539 if cell.cell_type == 'code':
2552 2540 yield cell.source
2553 2541 else:
2554 2542 with open(fname) as f:
2555 2543 yield f.read()
2556 2544
2557 2545 with prepended_to_syspath(dname):
2558 2546 try:
2559 2547 for cell in get_cells():
2560 2548 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2561 2549 if raise_exceptions:
2562 2550 result.raise_error()
2563 2551 elif not result.success:
2564 2552 break
2565 2553 except:
2566 2554 if raise_exceptions:
2567 2555 raise
2568 2556 self.showtraceback()
2569 2557 warn('Unknown failure executing file: <%s>' % fname)
2570 2558
2571 2559 def safe_run_module(self, mod_name, where):
2572 2560 """A safe version of runpy.run_module().
2573 2561
2574 2562 This version will never throw an exception, but instead print
2575 2563 helpful error messages to the screen.
2576 2564
2577 2565 `SystemExit` exceptions with status code 0 or None are ignored.
2578 2566
2579 2567 Parameters
2580 2568 ----------
2581 2569 mod_name : string
2582 2570 The name of the module to be executed.
2583 2571 where : dict
2584 2572 The globals namespace.
2585 2573 """
2586 2574 try:
2587 2575 try:
2588 2576 where.update(
2589 2577 runpy.run_module(str(mod_name), run_name="__main__",
2590 2578 alter_sys=True)
2591 2579 )
2592 2580 except SystemExit as status:
2593 2581 if status.code:
2594 2582 raise
2595 2583 except:
2596 2584 self.showtraceback()
2597 2585 warn('Unknown failure executing module: <%s>' % mod_name)
2598 2586
2599 2587 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2600 2588 """Run a complete IPython cell.
2601 2589
2602 2590 Parameters
2603 2591 ----------
2604 2592 raw_cell : str
2605 2593 The code (including IPython code such as %magic functions) to run.
2606 2594 store_history : bool
2607 2595 If True, the raw and translated cell will be stored in IPython's
2608 2596 history. For user code calling back into IPython's machinery, this
2609 2597 should be set to False.
2610 2598 silent : bool
2611 2599 If True, avoid side-effects, such as implicit displayhooks and
2612 2600 and logging. silent=True forces store_history=False.
2613 2601 shell_futures : bool
2614 2602 If True, the code will share future statements with the interactive
2615 2603 shell. It will both be affected by previous __future__ imports, and
2616 2604 any __future__ imports in the code will affect the shell. If False,
2617 2605 __future__ imports are not shared in either direction.
2618 2606
2619 2607 Returns
2620 2608 -------
2621 2609 result : :class:`ExecutionResult`
2622 2610 """
2623 2611 result = ExecutionResult()
2624 2612
2625 2613 if (not raw_cell) or raw_cell.isspace():
2626 2614 self.last_execution_succeeded = True
2627 2615 return result
2628 2616
2629 2617 if silent:
2630 2618 store_history = False
2631 2619
2632 2620 if store_history:
2633 2621 result.execution_count = self.execution_count
2634 2622
2635 2623 def error_before_exec(value):
2636 2624 result.error_before_exec = value
2637 2625 self.last_execution_succeeded = False
2638 2626 return result
2639 2627
2640 2628 self.events.trigger('pre_execute')
2641 2629 if not silent:
2642 2630 self.events.trigger('pre_run_cell')
2643 2631
2644 2632 # If any of our input transformation (input_transformer_manager or
2645 2633 # prefilter_manager) raises an exception, we store it in this variable
2646 2634 # so that we can display the error after logging the input and storing
2647 2635 # it in the history.
2648 2636 preprocessing_exc_tuple = None
2649 2637 try:
2650 2638 # Static input transformations
2651 2639 cell = self.input_transformer_manager.transform_cell(raw_cell)
2652 2640 except SyntaxError:
2653 2641 preprocessing_exc_tuple = sys.exc_info()
2654 2642 cell = raw_cell # cell has to exist so it can be stored/logged
2655 2643 else:
2656 2644 if len(cell.splitlines()) == 1:
2657 2645 # Dynamic transformations - only applied for single line commands
2658 2646 with self.builtin_trap:
2659 2647 try:
2660 2648 # use prefilter_lines to handle trailing newlines
2661 2649 # restore trailing newline for ast.parse
2662 2650 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2663 2651 except Exception:
2664 2652 # don't allow prefilter errors to crash IPython
2665 2653 preprocessing_exc_tuple = sys.exc_info()
2666 2654
2667 2655 # Store raw and processed history
2668 2656 if store_history:
2669 2657 self.history_manager.store_inputs(self.execution_count,
2670 2658 cell, raw_cell)
2671 2659 if not silent:
2672 2660 self.logger.log(cell, raw_cell)
2673 2661
2674 2662 # Display the exception if input processing failed.
2675 2663 if preprocessing_exc_tuple is not None:
2676 2664 self.showtraceback(preprocessing_exc_tuple)
2677 2665 if store_history:
2678 2666 self.execution_count += 1
2679 2667 return error_before_exec(preprocessing_exc_tuple[2])
2680 2668
2681 2669 # Our own compiler remembers the __future__ environment. If we want to
2682 2670 # run code with a separate __future__ environment, use the default
2683 2671 # compiler
2684 2672 compiler = self.compile if shell_futures else CachingCompiler()
2685 2673
2686 2674 with self.builtin_trap:
2687 2675 cell_name = self.compile.cache(cell, self.execution_count)
2688 2676
2689 2677 with self.display_trap:
2690 2678 # Compile to bytecode
2691 2679 try:
2692 2680 code_ast = compiler.ast_parse(cell, filename=cell_name)
2693 2681 except self.custom_exceptions as e:
2694 2682 etype, value, tb = sys.exc_info()
2695 2683 self.CustomTB(etype, value, tb)
2696 2684 return error_before_exec(e)
2697 2685 except IndentationError as e:
2698 2686 self.showindentationerror()
2699 2687 if store_history:
2700 2688 self.execution_count += 1
2701 2689 return error_before_exec(e)
2702 2690 except (OverflowError, SyntaxError, ValueError, TypeError,
2703 2691 MemoryError) as e:
2704 2692 self.showsyntaxerror()
2705 2693 if store_history:
2706 2694 self.execution_count += 1
2707 2695 return error_before_exec(e)
2708 2696
2709 2697 # Apply AST transformations
2710 2698 try:
2711 2699 code_ast = self.transform_ast(code_ast)
2712 2700 except InputRejected as e:
2713 2701 self.showtraceback()
2714 2702 if store_history:
2715 2703 self.execution_count += 1
2716 2704 return error_before_exec(e)
2717 2705
2718 2706 # Give the displayhook a reference to our ExecutionResult so it
2719 2707 # can fill in the output value.
2720 2708 self.displayhook.exec_result = result
2721 2709
2722 2710 # Execute the user code
2723 2711 interactivity = "none" if silent else self.ast_node_interactivity
2724 2712 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2725 2713 interactivity=interactivity, compiler=compiler, result=result)
2726 2714
2727 2715 self.last_execution_succeeded = not has_raised
2728 2716
2729 2717 # Reset this so later displayed values do not modify the
2730 2718 # ExecutionResult
2731 2719 self.displayhook.exec_result = None
2732 2720
2733 2721 self.events.trigger('post_execute')
2734 2722 if not silent:
2735 2723 self.events.trigger('post_run_cell')
2736 2724
2737 2725 if store_history:
2738 2726 # Write output to the database. Does nothing unless
2739 2727 # history output logging is enabled.
2740 2728 self.history_manager.store_output(self.execution_count)
2741 2729 # Each cell is a *single* input, regardless of how many lines it has
2742 2730 self.execution_count += 1
2743 2731
2744 2732 return result
2745 2733
2746 2734 def transform_ast(self, node):
2747 2735 """Apply the AST transformations from self.ast_transformers
2748 2736
2749 2737 Parameters
2750 2738 ----------
2751 2739 node : ast.Node
2752 2740 The root node to be transformed. Typically called with the ast.Module
2753 2741 produced by parsing user input.
2754 2742
2755 2743 Returns
2756 2744 -------
2757 2745 An ast.Node corresponding to the node it was called with. Note that it
2758 2746 may also modify the passed object, so don't rely on references to the
2759 2747 original AST.
2760 2748 """
2761 2749 for transformer in self.ast_transformers:
2762 2750 try:
2763 2751 node = transformer.visit(node)
2764 2752 except InputRejected:
2765 2753 # User-supplied AST transformers can reject an input by raising
2766 2754 # an InputRejected. Short-circuit in this case so that we
2767 2755 # don't unregister the transform.
2768 2756 raise
2769 2757 except Exception:
2770 2758 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2771 2759 self.ast_transformers.remove(transformer)
2772 2760
2773 2761 if self.ast_transformers:
2774 2762 ast.fix_missing_locations(node)
2775 2763 return node
2776 2764
2777 2765
2778 2766 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2779 2767 compiler=compile, result=None):
2780 2768 """Run a sequence of AST nodes. The execution mode depends on the
2781 2769 interactivity parameter.
2782 2770
2783 2771 Parameters
2784 2772 ----------
2785 2773 nodelist : list
2786 2774 A sequence of AST nodes to run.
2787 2775 cell_name : str
2788 2776 Will be passed to the compiler as the filename of the cell. Typically
2789 2777 the value returned by ip.compile.cache(cell).
2790 2778 interactivity : str
2791 2779 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2792 2780 run interactively (displaying output from expressions). 'last_expr'
2793 2781 will run the last node interactively only if it is an expression (i.e.
2794 2782 expressions in loops or other blocks are not displayed. Other values
2795 2783 for this parameter will raise a ValueError.
2796 2784 compiler : callable
2797 2785 A function with the same interface as the built-in compile(), to turn
2798 2786 the AST nodes into code objects. Default is the built-in compile().
2799 2787 result : ExecutionResult, optional
2800 2788 An object to store exceptions that occur during execution.
2801 2789
2802 2790 Returns
2803 2791 -------
2804 2792 True if an exception occurred while running code, False if it finished
2805 2793 running.
2806 2794 """
2807 2795 if not nodelist:
2808 2796 return
2809 2797
2810 2798 if interactivity == 'last_expr':
2811 2799 if isinstance(nodelist[-1], ast.Expr):
2812 2800 interactivity = "last"
2813 2801 else:
2814 2802 interactivity = "none"
2815 2803
2816 2804 if interactivity == 'none':
2817 2805 to_run_exec, to_run_interactive = nodelist, []
2818 2806 elif interactivity == 'last':
2819 2807 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2820 2808 elif interactivity == 'all':
2821 2809 to_run_exec, to_run_interactive = [], nodelist
2822 2810 else:
2823 2811 raise ValueError("Interactivity was %r" % interactivity)
2824 2812
2825 2813 try:
2826 2814 for i, node in enumerate(to_run_exec):
2827 2815 mod = ast.Module([node])
2828 2816 code = compiler(mod, cell_name, "exec")
2829 2817 if self.run_code(code, result):
2830 2818 return True
2831 2819
2832 2820 for i, node in enumerate(to_run_interactive):
2833 2821 mod = ast.Interactive([node])
2834 2822 code = compiler(mod, cell_name, "single")
2835 2823 if self.run_code(code, result):
2836 2824 return True
2837 2825
2838 2826 # Flush softspace
2839 2827 if softspace(sys.stdout, 0):
2840 2828 print()
2841 2829
2842 2830 except:
2843 2831 # It's possible to have exceptions raised here, typically by
2844 2832 # compilation of odd code (such as a naked 'return' outside a
2845 2833 # function) that did parse but isn't valid. Typically the exception
2846 2834 # is a SyntaxError, but it's safest just to catch anything and show
2847 2835 # the user a traceback.
2848 2836
2849 2837 # We do only one try/except outside the loop to minimize the impact
2850 2838 # on runtime, and also because if any node in the node list is
2851 2839 # broken, we should stop execution completely.
2852 2840 if result:
2853 2841 result.error_before_exec = sys.exc_info()[1]
2854 2842 self.showtraceback()
2855 2843 return True
2856 2844
2857 2845 return False
2858 2846
2859 2847 def run_code(self, code_obj, result=None):
2860 2848 """Execute a code object.
2861 2849
2862 2850 When an exception occurs, self.showtraceback() is called to display a
2863 2851 traceback.
2864 2852
2865 2853 Parameters
2866 2854 ----------
2867 2855 code_obj : code object
2868 2856 A compiled code object, to be executed
2869 2857 result : ExecutionResult, optional
2870 2858 An object to store exceptions that occur during execution.
2871 2859
2872 2860 Returns
2873 2861 -------
2874 2862 False : successful execution.
2875 2863 True : an error occurred.
2876 2864 """
2877 2865 # Set our own excepthook in case the user code tries to call it
2878 2866 # directly, so that the IPython crash handler doesn't get triggered
2879 2867 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2880 2868
2881 2869 # we save the original sys.excepthook in the instance, in case config
2882 2870 # code (such as magics) needs access to it.
2883 2871 self.sys_excepthook = old_excepthook
2884 2872 outflag = 1 # happens in more places, so it's easier as default
2885 2873 try:
2886 2874 try:
2887 2875 self.hooks.pre_run_code_hook()
2888 2876 #rprint('Running code', repr(code_obj)) # dbg
2889 2877 exec(code_obj, self.user_global_ns, self.user_ns)
2890 2878 finally:
2891 2879 # Reset our crash handler in place
2892 2880 sys.excepthook = old_excepthook
2893 2881 except SystemExit as e:
2894 2882 if result is not None:
2895 2883 result.error_in_exec = e
2896 2884 self.showtraceback(exception_only=True)
2897 2885 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2898 2886 except self.custom_exceptions:
2899 2887 etype, value, tb = sys.exc_info()
2900 2888 if result is not None:
2901 2889 result.error_in_exec = value
2902 2890 self.CustomTB(etype, value, tb)
2903 2891 except:
2904 2892 if result is not None:
2905 2893 result.error_in_exec = sys.exc_info()[1]
2906 2894 self.showtraceback()
2907 2895 else:
2908 2896 outflag = 0
2909 2897 return outflag
2910 2898
2911 2899 # For backwards compatibility
2912 2900 runcode = run_code
2913 2901
2914 2902 #-------------------------------------------------------------------------
2915 2903 # Things related to GUI support and pylab
2916 2904 #-------------------------------------------------------------------------
2917 2905
2918 2906 def enable_gui(self, gui=None):
2919 2907 raise NotImplementedError('Implement enable_gui in a subclass')
2920 2908
2921 2909 def enable_matplotlib(self, gui=None):
2922 2910 """Enable interactive matplotlib and inline figure support.
2923 2911
2924 2912 This takes the following steps:
2925 2913
2926 2914 1. select the appropriate eventloop and matplotlib backend
2927 2915 2. set up matplotlib for interactive use with that backend
2928 2916 3. configure formatters for inline figure display
2929 2917 4. enable the selected gui eventloop
2930 2918
2931 2919 Parameters
2932 2920 ----------
2933 2921 gui : optional, string
2934 2922 If given, dictates the choice of matplotlib GUI backend to use
2935 2923 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2936 2924 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2937 2925 matplotlib (as dictated by the matplotlib build-time options plus the
2938 2926 user's matplotlibrc configuration file). Note that not all backends
2939 2927 make sense in all contexts, for example a terminal ipython can't
2940 2928 display figures inline.
2941 2929 """
2942 2930 from IPython.core import pylabtools as pt
2943 2931 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2944 2932
2945 2933 if gui != 'inline':
2946 2934 # If we have our first gui selection, store it
2947 2935 if self.pylab_gui_select is None:
2948 2936 self.pylab_gui_select = gui
2949 2937 # Otherwise if they are different
2950 2938 elif gui != self.pylab_gui_select:
2951 2939 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2952 2940 ' Using %s instead.' % (gui, self.pylab_gui_select))
2953 2941 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2954 2942
2955 2943 pt.activate_matplotlib(backend)
2956 2944 pt.configure_inline_support(self, backend)
2957 2945
2958 2946 # Now we must activate the gui pylab wants to use, and fix %run to take
2959 2947 # plot updates into account
2960 2948 self.enable_gui(gui)
2961 2949 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2962 2950 pt.mpl_runner(self.safe_execfile)
2963 2951
2964 2952 return gui, backend
2965 2953
2966 2954 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2967 2955 """Activate pylab support at runtime.
2968 2956
2969 2957 This turns on support for matplotlib, preloads into the interactive
2970 2958 namespace all of numpy and pylab, and configures IPython to correctly
2971 2959 interact with the GUI event loop. The GUI backend to be used can be
2972 2960 optionally selected with the optional ``gui`` argument.
2973 2961
2974 2962 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2975 2963
2976 2964 Parameters
2977 2965 ----------
2978 2966 gui : optional, string
2979 2967 If given, dictates the choice of matplotlib GUI backend to use
2980 2968 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2981 2969 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2982 2970 matplotlib (as dictated by the matplotlib build-time options plus the
2983 2971 user's matplotlibrc configuration file). Note that not all backends
2984 2972 make sense in all contexts, for example a terminal ipython can't
2985 2973 display figures inline.
2986 2974 import_all : optional, bool, default: True
2987 2975 Whether to do `from numpy import *` and `from pylab import *`
2988 2976 in addition to module imports.
2989 2977 welcome_message : deprecated
2990 2978 This argument is ignored, no welcome message will be displayed.
2991 2979 """
2992 2980 from IPython.core.pylabtools import import_pylab
2993 2981
2994 2982 gui, backend = self.enable_matplotlib(gui)
2995 2983
2996 2984 # We want to prevent the loading of pylab to pollute the user's
2997 2985 # namespace as shown by the %who* magics, so we execute the activation
2998 2986 # code in an empty namespace, and we update *both* user_ns and
2999 2987 # user_ns_hidden with this information.
3000 2988 ns = {}
3001 2989 import_pylab(ns, import_all)
3002 2990 # warn about clobbered names
3003 2991 ignored = {"__builtins__"}
3004 2992 both = set(ns).intersection(self.user_ns).difference(ignored)
3005 2993 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3006 2994 self.user_ns.update(ns)
3007 2995 self.user_ns_hidden.update(ns)
3008 2996 return gui, backend, clobbered
3009 2997
3010 2998 #-------------------------------------------------------------------------
3011 2999 # Utilities
3012 3000 #-------------------------------------------------------------------------
3013 3001
3014 3002 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3015 3003 """Expand python variables in a string.
3016 3004
3017 3005 The depth argument indicates how many frames above the caller should
3018 3006 be walked to look for the local namespace where to expand variables.
3019 3007
3020 3008 The global namespace for expansion is always the user's interactive
3021 3009 namespace.
3022 3010 """
3023 3011 ns = self.user_ns.copy()
3024 3012 try:
3025 3013 frame = sys._getframe(depth+1)
3026 3014 except ValueError:
3027 3015 # This is thrown if there aren't that many frames on the stack,
3028 3016 # e.g. if a script called run_line_magic() directly.
3029 3017 pass
3030 3018 else:
3031 3019 ns.update(frame.f_locals)
3032 3020
3033 3021 try:
3034 3022 # We have to use .vformat() here, because 'self' is a valid and common
3035 3023 # name, and expanding **ns for .format() would make it collide with
3036 3024 # the 'self' argument of the method.
3037 3025 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3038 3026 except Exception:
3039 3027 # if formatter couldn't format, just let it go untransformed
3040 3028 pass
3041 3029 return cmd
3042 3030
3043 3031 def mktempfile(self, data=None, prefix='ipython_edit_'):
3044 3032 """Make a new tempfile and return its filename.
3045 3033
3046 3034 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3047 3035 but it registers the created filename internally so ipython cleans it up
3048 3036 at exit time.
3049 3037
3050 3038 Optional inputs:
3051 3039
3052 3040 - data(None): if data is given, it gets written out to the temp file
3053 3041 immediately, and the file is closed again."""
3054 3042
3055 3043 dirname = tempfile.mkdtemp(prefix=prefix)
3056 3044 self.tempdirs.append(dirname)
3057 3045
3058 3046 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3059 3047 os.close(handle) # On Windows, there can only be one open handle on a file
3060 3048 self.tempfiles.append(filename)
3061 3049
3062 3050 if data:
3063 3051 tmp_file = open(filename,'w')
3064 3052 tmp_file.write(data)
3065 3053 tmp_file.close()
3066 3054 return filename
3067 3055
3068 3056 @undoc
3069 3057 def write(self,data):
3070 3058 """DEPRECATED: Write a string to the default output"""
3071 3059 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3072 3060 DeprecationWarning, stacklevel=2)
3073 3061 sys.stdout.write(data)
3074 3062
3075 3063 @undoc
3076 3064 def write_err(self,data):
3077 3065 """DEPRECATED: Write a string to the default error output"""
3078 3066 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3079 3067 DeprecationWarning, stacklevel=2)
3080 3068 sys.stderr.write(data)
3081 3069
3082 3070 def ask_yes_no(self, prompt, default=None, interrupt=None):
3083 3071 if self.quiet:
3084 3072 return True
3085 3073 return ask_yes_no(prompt,default,interrupt)
3086 3074
3087 3075 def show_usage(self):
3088 3076 """Show a usage message"""
3089 3077 page.page(IPython.core.usage.interactive_usage)
3090 3078
3091 3079 def extract_input_lines(self, range_str, raw=False):
3092 3080 """Return as a string a set of input history slices.
3093 3081
3094 3082 Parameters
3095 3083 ----------
3096 3084 range_str : string
3097 3085 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3098 3086 since this function is for use by magic functions which get their
3099 3087 arguments as strings. The number before the / is the session
3100 3088 number: ~n goes n back from the current session.
3101 3089
3102 3090 raw : bool, optional
3103 3091 By default, the processed input is used. If this is true, the raw
3104 3092 input history is used instead.
3105 3093
3106 3094 Notes
3107 3095 -----
3108 3096
3109 3097 Slices can be described with two notations:
3110 3098
3111 3099 * ``N:M`` -> standard python form, means including items N...(M-1).
3112 3100 * ``N-M`` -> include items N..M (closed endpoint).
3113 3101 """
3114 3102 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3115 3103 return "\n".join(x for _, _, x in lines)
3116 3104
3117 3105 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3118 3106 """Get a code string from history, file, url, or a string or macro.
3119 3107
3120 3108 This is mainly used by magic functions.
3121 3109
3122 3110 Parameters
3123 3111 ----------
3124 3112
3125 3113 target : str
3126 3114
3127 3115 A string specifying code to retrieve. This will be tried respectively
3128 3116 as: ranges of input history (see %history for syntax), url,
3129 3117 corresponding .py file, filename, or an expression evaluating to a
3130 3118 string or Macro in the user namespace.
3131 3119
3132 3120 raw : bool
3133 3121 If true (default), retrieve raw history. Has no effect on the other
3134 3122 retrieval mechanisms.
3135 3123
3136 3124 py_only : bool (default False)
3137 3125 Only try to fetch python code, do not try alternative methods to decode file
3138 3126 if unicode fails.
3139 3127
3140 3128 Returns
3141 3129 -------
3142 3130 A string of code.
3143 3131
3144 3132 ValueError is raised if nothing is found, and TypeError if it evaluates
3145 3133 to an object of another type. In each case, .args[0] is a printable
3146 3134 message.
3147 3135 """
3148 3136 code = self.extract_input_lines(target, raw=raw) # Grab history
3149 3137 if code:
3150 3138 return code
3151 3139 try:
3152 3140 if target.startswith(('http://', 'https://')):
3153 3141 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3154 3142 except UnicodeDecodeError:
3155 3143 if not py_only :
3156 3144 # Deferred import
3157 3145 try:
3158 3146 from urllib.request import urlopen # Py3
3159 3147 except ImportError:
3160 3148 from urllib import urlopen
3161 3149 response = urlopen(target)
3162 3150 return response.read().decode('latin1')
3163 3151 raise ValueError(("'%s' seem to be unreadable.") % target)
3164 3152
3165 3153 potential_target = [target]
3166 3154 try :
3167 3155 potential_target.insert(0,get_py_filename(target))
3168 3156 except IOError:
3169 3157 pass
3170 3158
3171 3159 for tgt in potential_target :
3172 3160 if os.path.isfile(tgt): # Read file
3173 3161 try :
3174 3162 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3175 3163 except UnicodeDecodeError :
3176 3164 if not py_only :
3177 3165 with io_open(tgt,'r', encoding='latin1') as f :
3178 3166 return f.read()
3179 3167 raise ValueError(("'%s' seem to be unreadable.") % target)
3180 3168 elif os.path.isdir(os.path.expanduser(tgt)):
3181 3169 raise ValueError("'%s' is a directory, not a regular file." % target)
3182 3170
3183 3171 if search_ns:
3184 3172 # Inspect namespace to load object source
3185 3173 object_info = self.object_inspect(target, detail_level=1)
3186 3174 if object_info['found'] and object_info['source']:
3187 3175 return object_info['source']
3188 3176
3189 3177 try: # User namespace
3190 3178 codeobj = eval(target, self.user_ns)
3191 3179 except Exception:
3192 3180 raise ValueError(("'%s' was not found in history, as a file, url, "
3193 3181 "nor in the user namespace.") % target)
3194 3182
3195 3183 if isinstance(codeobj, string_types):
3196 3184 return codeobj
3197 3185 elif isinstance(codeobj, Macro):
3198 3186 return codeobj.value
3199 3187
3200 3188 raise TypeError("%s is neither a string nor a macro." % target,
3201 3189 codeobj)
3202 3190
3203 3191 #-------------------------------------------------------------------------
3204 3192 # Things related to IPython exiting
3205 3193 #-------------------------------------------------------------------------
3206 3194 def atexit_operations(self):
3207 3195 """This will be executed at the time of exit.
3208 3196
3209 3197 Cleanup operations and saving of persistent data that is done
3210 3198 unconditionally by IPython should be performed here.
3211 3199
3212 3200 For things that may depend on startup flags or platform specifics (such
3213 3201 as having readline or not), register a separate atexit function in the
3214 3202 code that has the appropriate information, rather than trying to
3215 3203 clutter
3216 3204 """
3217 3205 # Close the history session (this stores the end time and line count)
3218 3206 # this must be *before* the tempfile cleanup, in case of temporary
3219 3207 # history db
3220 3208 self.history_manager.end_session()
3221 3209
3222 3210 # Cleanup all tempfiles and folders left around
3223 3211 for tfile in self.tempfiles:
3224 3212 try:
3225 3213 os.unlink(tfile)
3226 3214 except OSError:
3227 3215 pass
3228 3216
3229 3217 for tdir in self.tempdirs:
3230 3218 try:
3231 3219 os.rmdir(tdir)
3232 3220 except OSError:
3233 3221 pass
3234 3222
3235 3223 # Clear all user namespaces to release all references cleanly.
3236 3224 self.reset(new_session=False)
3237 3225
3238 3226 # Run user hooks
3239 3227 self.hooks.shutdown_hook()
3240 3228
3241 3229 def cleanup(self):
3242 3230 self.restore_sys_module_state()
3243 3231
3244 3232
3245 3233 # Overridden in terminal subclass to change prompts
3246 3234 def switch_doctest_mode(self, mode):
3247 3235 pass
3248 3236
3249 3237
3250 3238 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3251 3239 """An abstract base class for InteractiveShell."""
3252 3240
3253 3241 InteractiveShellABC.register(InteractiveShell)
@@ -1,1362 +1,1361 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Implementation of execution-related magic functions."""
3 3
4 4 # Copyright (c) IPython Development Team.
5 5 # Distributed under the terms of the Modified BSD License.
6 6
7 7 from __future__ import print_function
8 8 from __future__ import absolute_import
9 9
10 10 import ast
11 11 import bdb
12 12 import gc
13 13 import itertools
14 14 import os
15 15 import sys
16 16 import time
17 17 import timeit
18 18 from pdb import Restart
19 19
20 20 # cProfile was added in Python2.5
21 21 try:
22 22 import cProfile as profile
23 23 import pstats
24 24 except ImportError:
25 25 # profile isn't bundled by default in Debian for license reasons
26 26 try:
27 27 import profile, pstats
28 28 except ImportError:
29 29 profile = pstats = None
30 30
31 31 from IPython.core import debugger, oinspect
32 32 from IPython.core import magic_arguments
33 33 from IPython.core import page
34 34 from IPython.core.error import UsageError
35 35 from IPython.core.macro import Macro
36 36 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
37 37 line_cell_magic, on_off, needs_local_scope)
38 38 from IPython.testing.skipdoctest import skip_doctest
39 39 from IPython.utils import py3compat
40 40 from IPython.utils.py3compat import builtin_mod, iteritems, PY3
41 41 from IPython.utils.contexts import preserve_keys
42 42 from IPython.utils.capture import capture_output
43 43 from IPython.utils.ipstruct import Struct
44 44 from IPython.utils.module_paths import find_mod
45 45 from IPython.utils.path import get_py_filename, shellglob
46 46 from IPython.utils.timing import clock, clock2
47 47 from warnings import warn
48 48 from logging import error
49 49
50 50 if PY3:
51 51 from io import StringIO
52 52 else:
53 53 from StringIO import StringIO
54 54
55 55 #-----------------------------------------------------------------------------
56 56 # Magic implementation classes
57 57 #-----------------------------------------------------------------------------
58 58
59 59
60 60 class TimeitResult(object):
61 61 """
62 62 Object returned by the timeit magic with info about the run.
63 63
64 64 Contains the following attributes :
65 65
66 66 loops: (int) number of loops done per measurement
67 67 repeat: (int) number of times the measurement has been repeated
68 68 best: (float) best execution time / number
69 69 all_runs: (list of float) execution time of each run (in s)
70 70 compile_time: (float) time of statement compilation (s)
71 71
72 72 """
73 73
74 74 def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
75 75 self.loops = loops
76 76 self.repeat = repeat
77 77 self.best = best
78 78 self.worst = worst
79 79 self.all_runs = all_runs
80 80 self.compile_time = compile_time
81 81 self._precision = precision
82 82
83 83 def _repr_pretty_(self, p , cycle):
84 84 if self.loops == 1: # No s at "loops" if only one loop
85 85 unic = u"%d loop, best of %d: %s per loop" % (self.loops, self.repeat,
86 86 _format_time(self.best, self._precision))
87 87 else:
88 88 unic = u"%d loops, best of %d: %s per loop" % (self.loops, self.repeat,
89 89 _format_time(self.best, self._precision))
90 90 p.text(u'<TimeitResult : '+unic+u'>')
91 91
92 92
93 93 class TimeitTemplateFiller(ast.NodeTransformer):
94 94 """Fill in the AST template for timing execution.
95 95
96 96 This is quite closely tied to the template definition, which is in
97 97 :meth:`ExecutionMagics.timeit`.
98 98 """
99 99 def __init__(self, ast_setup, ast_stmt):
100 100 self.ast_setup = ast_setup
101 101 self.ast_stmt = ast_stmt
102 102
103 103 def visit_FunctionDef(self, node):
104 104 "Fill in the setup statement"
105 105 self.generic_visit(node)
106 106 if node.name == "inner":
107 107 node.body[:1] = self.ast_setup.body
108 108
109 109 return node
110 110
111 111 def visit_For(self, node):
112 112 "Fill in the statement to be timed"
113 113 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
114 114 node.body = self.ast_stmt.body
115 115 return node
116 116
117 117
118 118 class Timer(timeit.Timer):
119 119 """Timer class that explicitly uses self.inner
120 120
121 121 which is an undocumented implementation detail of CPython,
122 122 not shared by PyPy.
123 123 """
124 124 # Timer.timeit copied from CPython 3.4.2
125 125 def timeit(self, number=timeit.default_number):
126 126 """Time 'number' executions of the main statement.
127 127
128 128 To be precise, this executes the setup statement once, and
129 129 then returns the time it takes to execute the main statement
130 130 a number of times, as a float measured in seconds. The
131 131 argument is the number of times through the loop, defaulting
132 132 to one million. The main statement, the setup statement and
133 133 the timer function to be used are passed to the constructor.
134 134 """
135 135 it = itertools.repeat(None, number)
136 136 gcold = gc.isenabled()
137 137 gc.disable()
138 138 try:
139 139 timing = self.inner(it, self.timer)
140 140 finally:
141 141 if gcold:
142 142 gc.enable()
143 143 return timing
144 144
145 145
146 146 @magics_class
147 147 class ExecutionMagics(Magics):
148 148 """Magics related to code execution, debugging, profiling, etc.
149 149
150 150 """
151 151
152 152 def __init__(self, shell):
153 153 super(ExecutionMagics, self).__init__(shell)
154 154 if profile is None:
155 155 self.prun = self.profile_missing_notice
156 156 # Default execution function used to actually run user code.
157 157 self.default_runner = None
158 158
159 159 def profile_missing_notice(self, *args, **kwargs):
160 160 error("""\
161 161 The profile module could not be found. It has been removed from the standard
162 162 python packages because of its non-free license. To use profiling, install the
163 163 python-profiler package from non-free.""")
164 164
165 165 @skip_doctest
166 166 @line_cell_magic
167 167 def prun(self, parameter_s='', cell=None):
168 168
169 169 """Run a statement through the python code profiler.
170 170
171 171 Usage, in line mode:
172 172 %prun [options] statement
173 173
174 174 Usage, in cell mode:
175 175 %%prun [options] [statement]
176 176 code...
177 177 code...
178 178
179 179 In cell mode, the additional code lines are appended to the (possibly
180 180 empty) statement in the first line. Cell mode allows you to easily
181 181 profile multiline blocks without having to put them in a separate
182 182 function.
183 183
184 184 The given statement (which doesn't require quote marks) is run via the
185 185 python profiler in a manner similar to the profile.run() function.
186 186 Namespaces are internally managed to work correctly; profile.run
187 187 cannot be used in IPython because it makes certain assumptions about
188 188 namespaces which do not hold under IPython.
189 189
190 190 Options:
191 191
192 192 -l <limit>
193 193 you can place restrictions on what or how much of the
194 194 profile gets printed. The limit value can be:
195 195
196 196 * A string: only information for function names containing this string
197 197 is printed.
198 198
199 199 * An integer: only these many lines are printed.
200 200
201 201 * A float (between 0 and 1): this fraction of the report is printed
202 202 (for example, use a limit of 0.4 to see the topmost 40% only).
203 203
204 204 You can combine several limits with repeated use of the option. For
205 205 example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
206 206 information about class constructors.
207 207
208 208 -r
209 209 return the pstats.Stats object generated by the profiling. This
210 210 object has all the information about the profile in it, and you can
211 211 later use it for further analysis or in other functions.
212 212
213 213 -s <key>
214 214 sort profile by given key. You can provide more than one key
215 215 by using the option several times: '-s key1 -s key2 -s key3...'. The
216 216 default sorting key is 'time'.
217 217
218 218 The following is copied verbatim from the profile documentation
219 219 referenced below:
220 220
221 221 When more than one key is provided, additional keys are used as
222 222 secondary criteria when the there is equality in all keys selected
223 223 before them.
224 224
225 225 Abbreviations can be used for any key names, as long as the
226 226 abbreviation is unambiguous. The following are the keys currently
227 227 defined:
228 228
229 229 ============ =====================
230 230 Valid Arg Meaning
231 231 ============ =====================
232 232 "calls" call count
233 233 "cumulative" cumulative time
234 234 "file" file name
235 235 "module" file name
236 236 "pcalls" primitive call count
237 237 "line" line number
238 238 "name" function name
239 239 "nfl" name/file/line
240 240 "stdname" standard name
241 241 "time" internal time
242 242 ============ =====================
243 243
244 244 Note that all sorts on statistics are in descending order (placing
245 245 most time consuming items first), where as name, file, and line number
246 246 searches are in ascending order (i.e., alphabetical). The subtle
247 247 distinction between "nfl" and "stdname" is that the standard name is a
248 248 sort of the name as printed, which means that the embedded line
249 249 numbers get compared in an odd way. For example, lines 3, 20, and 40
250 250 would (if the file names were the same) appear in the string order
251 251 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
252 252 line numbers. In fact, sort_stats("nfl") is the same as
253 253 sort_stats("name", "file", "line").
254 254
255 255 -T <filename>
256 256 save profile results as shown on screen to a text
257 257 file. The profile is still shown on screen.
258 258
259 259 -D <filename>
260 260 save (via dump_stats) profile statistics to given
261 261 filename. This data is in a format understood by the pstats module, and
262 262 is generated by a call to the dump_stats() method of profile
263 263 objects. The profile is still shown on screen.
264 264
265 265 -q
266 266 suppress output to the pager. Best used with -T and/or -D above.
267 267
268 268 If you want to run complete programs under the profiler's control, use
269 269 ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
270 270 contains profiler specific options as described here.
271 271
272 272 You can read the complete documentation for the profile module with::
273 273
274 274 In [1]: import profile; profile.help()
275 275 """
276 276 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
277 277 list_all=True, posix=False)
278 278 if cell is not None:
279 279 arg_str += '\n' + cell
280 280 arg_str = self.shell.input_splitter.transform_cell(arg_str)
281 281 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
282 282
283 283 def _run_with_profiler(self, code, opts, namespace):
284 284 """
285 285 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
286 286
287 287 Parameters
288 288 ----------
289 289 code : str
290 290 Code to be executed.
291 291 opts : Struct
292 292 Options parsed by `self.parse_options`.
293 293 namespace : dict
294 294 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
295 295
296 296 """
297 297
298 298 # Fill default values for unspecified options:
299 299 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
300 300
301 301 prof = profile.Profile()
302 302 try:
303 303 prof = prof.runctx(code, namespace, namespace)
304 304 sys_exit = ''
305 305 except SystemExit:
306 306 sys_exit = """*** SystemExit exception caught in code being profiled."""
307 307
308 308 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
309 309
310 310 lims = opts.l
311 311 if lims:
312 312 lims = [] # rebuild lims with ints/floats/strings
313 313 for lim in opts.l:
314 314 try:
315 315 lims.append(int(lim))
316 316 except ValueError:
317 317 try:
318 318 lims.append(float(lim))
319 319 except ValueError:
320 320 lims.append(lim)
321 321
322 322 # Trap output.
323 323 stdout_trap = StringIO()
324 324 stats_stream = stats.stream
325 325 try:
326 326 stats.stream = stdout_trap
327 327 stats.print_stats(*lims)
328 328 finally:
329 329 stats.stream = stats_stream
330 330
331 331 output = stdout_trap.getvalue()
332 332 output = output.rstrip()
333 333
334 334 if 'q' not in opts:
335 335 page.page(output)
336 336 print(sys_exit, end=' ')
337 337
338 338 dump_file = opts.D[0]
339 339 text_file = opts.T[0]
340 340 if dump_file:
341 341 prof.dump_stats(dump_file)
342 342 print('\n*** Profile stats marshalled to file',\
343 343 repr(dump_file)+'.',sys_exit)
344 344 if text_file:
345 345 pfile = open(text_file,'w')
346 346 pfile.write(output)
347 347 pfile.close()
348 348 print('\n*** Profile printout saved to text file',\
349 349 repr(text_file)+'.',sys_exit)
350 350
351 351 if 'r' in opts:
352 352 return stats
353 353 else:
354 354 return None
355 355
356 356 @line_magic
357 357 def pdb(self, parameter_s=''):
358 358 """Control the automatic calling of the pdb interactive debugger.
359 359
360 360 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
361 361 argument it works as a toggle.
362 362
363 363 When an exception is triggered, IPython can optionally call the
364 364 interactive pdb debugger after the traceback printout. %pdb toggles
365 365 this feature on and off.
366 366
367 367 The initial state of this feature is set in your configuration
368 368 file (the option is ``InteractiveShell.pdb``).
369 369
370 370 If you want to just activate the debugger AFTER an exception has fired,
371 371 without having to type '%pdb on' and rerunning your code, you can use
372 372 the %debug magic."""
373 373
374 374 par = parameter_s.strip().lower()
375 375
376 376 if par:
377 377 try:
378 378 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
379 379 except KeyError:
380 380 print ('Incorrect argument. Use on/1, off/0, '
381 381 'or nothing for a toggle.')
382 382 return
383 383 else:
384 384 # toggle
385 385 new_pdb = not self.shell.call_pdb
386 386
387 387 # set on the shell
388 388 self.shell.call_pdb = new_pdb
389 389 print('Automatic pdb calling has been turned',on_off(new_pdb))
390 390
391 391 @skip_doctest
392 392 @magic_arguments.magic_arguments()
393 393 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
394 394 help="""
395 395 Set break point at LINE in FILE.
396 396 """
397 397 )
398 398 @magic_arguments.argument('statement', nargs='*',
399 399 help="""
400 400 Code to run in debugger.
401 401 You can omit this in cell magic mode.
402 402 """
403 403 )
404 404 @line_cell_magic
405 405 def debug(self, line='', cell=None):
406 406 """Activate the interactive debugger.
407 407
408 408 This magic command support two ways of activating debugger.
409 409 One is to activate debugger before executing code. This way, you
410 410 can set a break point, to step through the code from the point.
411 411 You can use this mode by giving statements to execute and optionally
412 412 a breakpoint.
413 413
414 414 The other one is to activate debugger in post-mortem mode. You can
415 415 activate this mode simply running %debug without any argument.
416 416 If an exception has just occurred, this lets you inspect its stack
417 417 frames interactively. Note that this will always work only on the last
418 418 traceback that occurred, so you must call this quickly after an
419 419 exception that you wish to inspect has fired, because if another one
420 420 occurs, it clobbers the previous one.
421 421
422 422 If you want IPython to automatically do this on every exception, see
423 423 the %pdb magic for more details.
424 424 """
425 425 args = magic_arguments.parse_argstring(self.debug, line)
426 426
427 427 if not (args.breakpoint or args.statement or cell):
428 428 self._debug_post_mortem()
429 429 else:
430 430 code = "\n".join(args.statement)
431 431 if cell:
432 432 code += "\n" + cell
433 433 self._debug_exec(code, args.breakpoint)
434 434
435 435 def _debug_post_mortem(self):
436 436 self.shell.debugger(force=True)
437 437
438 438 def _debug_exec(self, code, breakpoint):
439 439 if breakpoint:
440 440 (filename, bp_line) = breakpoint.split(':', 1)
441 441 bp_line = int(bp_line)
442 442 else:
443 443 (filename, bp_line) = (None, None)
444 444 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
445 445
446 446 @line_magic
447 447 def tb(self, s):
448 448 """Print the last traceback with the currently active exception mode.
449 449
450 450 See %xmode for changing exception reporting modes."""
451 451 self.shell.showtraceback()
452 452
453 453 @skip_doctest
454 454 @line_magic
455 455 def run(self, parameter_s='', runner=None,
456 456 file_finder=get_py_filename):
457 457 """Run the named file inside IPython as a program.
458 458
459 459 Usage::
460 460
461 461 %run [-n -i -e -G]
462 462 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
463 463 ( -m mod | file ) [args]
464 464
465 465 Parameters after the filename are passed as command-line arguments to
466 466 the program (put in sys.argv). Then, control returns to IPython's
467 467 prompt.
468 468
469 469 This is similar to running at a system prompt ``python file args``,
470 470 but with the advantage of giving you IPython's tracebacks, and of
471 471 loading all variables into your interactive namespace for further use
472 472 (unless -p is used, see below).
473 473
474 474 The file is executed in a namespace initially consisting only of
475 475 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
476 476 sees its environment as if it were being run as a stand-alone program
477 477 (except for sharing global objects such as previously imported
478 478 modules). But after execution, the IPython interactive namespace gets
479 479 updated with all variables defined in the program (except for __name__
480 480 and sys.argv). This allows for very convenient loading of code for
481 481 interactive work, while giving each program a 'clean sheet' to run in.
482 482
483 483 Arguments are expanded using shell-like glob match. Patterns
484 484 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
485 485 tilde '~' will be expanded into user's home directory. Unlike
486 486 real shells, quotation does not suppress expansions. Use
487 487 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
488 488 To completely disable these expansions, you can use -G flag.
489 489
490 490 Options:
491 491
492 492 -n
493 493 __name__ is NOT set to '__main__', but to the running file's name
494 494 without extension (as python does under import). This allows running
495 495 scripts and reloading the definitions in them without calling code
496 496 protected by an ``if __name__ == "__main__"`` clause.
497 497
498 498 -i
499 499 run the file in IPython's namespace instead of an empty one. This
500 500 is useful if you are experimenting with code written in a text editor
501 501 which depends on variables defined interactively.
502 502
503 503 -e
504 504 ignore sys.exit() calls or SystemExit exceptions in the script
505 505 being run. This is particularly useful if IPython is being used to
506 506 run unittests, which always exit with a sys.exit() call. In such
507 507 cases you are interested in the output of the test results, not in
508 508 seeing a traceback of the unittest module.
509 509
510 510 -t
511 511 print timing information at the end of the run. IPython will give
512 512 you an estimated CPU time consumption for your script, which under
513 513 Unix uses the resource module to avoid the wraparound problems of
514 514 time.clock(). Under Unix, an estimate of time spent on system tasks
515 515 is also given (for Windows platforms this is reported as 0.0).
516 516
517 517 If -t is given, an additional ``-N<N>`` option can be given, where <N>
518 518 must be an integer indicating how many times you want the script to
519 519 run. The final timing report will include total and per run results.
520 520
521 521 For example (testing the script uniq_stable.py)::
522 522
523 523 In [1]: run -t uniq_stable
524 524
525 525 IPython CPU timings (estimated):
526 526 User : 0.19597 s.
527 527 System: 0.0 s.
528 528
529 529 In [2]: run -t -N5 uniq_stable
530 530
531 531 IPython CPU timings (estimated):
532 532 Total runs performed: 5
533 533 Times : Total Per run
534 534 User : 0.910862 s, 0.1821724 s.
535 535 System: 0.0 s, 0.0 s.
536 536
537 537 -d
538 538 run your program under the control of pdb, the Python debugger.
539 539 This allows you to execute your program step by step, watch variables,
540 540 etc. Internally, what IPython does is similar to calling::
541 541
542 542 pdb.run('execfile("YOURFILENAME")')
543 543
544 544 with a breakpoint set on line 1 of your file. You can change the line
545 545 number for this automatic breakpoint to be <N> by using the -bN option
546 546 (where N must be an integer). For example::
547 547
548 548 %run -d -b40 myscript
549 549
550 550 will set the first breakpoint at line 40 in myscript.py. Note that
551 551 the first breakpoint must be set on a line which actually does
552 552 something (not a comment or docstring) for it to stop execution.
553 553
554 554 Or you can specify a breakpoint in a different file::
555 555
556 556 %run -d -b myotherfile.py:20 myscript
557 557
558 558 When the pdb debugger starts, you will see a (Pdb) prompt. You must
559 559 first enter 'c' (without quotes) to start execution up to the first
560 560 breakpoint.
561 561
562 562 Entering 'help' gives information about the use of the debugger. You
563 563 can easily see pdb's full documentation with "import pdb;pdb.help()"
564 564 at a prompt.
565 565
566 566 -p
567 567 run program under the control of the Python profiler module (which
568 568 prints a detailed report of execution times, function calls, etc).
569 569
570 570 You can pass other options after -p which affect the behavior of the
571 571 profiler itself. See the docs for %prun for details.
572 572
573 573 In this mode, the program's variables do NOT propagate back to the
574 574 IPython interactive namespace (because they remain in the namespace
575 575 where the profiler executes them).
576 576
577 577 Internally this triggers a call to %prun, see its documentation for
578 578 details on the options available specifically for profiling.
579 579
580 580 There is one special usage for which the text above doesn't apply:
581 581 if the filename ends with .ipy[nb], the file is run as ipython script,
582 582 just as if the commands were written on IPython prompt.
583 583
584 584 -m
585 585 specify module name to load instead of script path. Similar to
586 586 the -m option for the python interpreter. Use this option last if you
587 587 want to combine with other %run options. Unlike the python interpreter
588 588 only source modules are allowed no .pyc or .pyo files.
589 589 For example::
590 590
591 591 %run -m example
592 592
593 593 will run the example module.
594 594
595 595 -G
596 596 disable shell-like glob expansion of arguments.
597 597
598 598 """
599 599
600 600 # get arguments and set sys.argv for program to be run.
601 601 opts, arg_lst = self.parse_options(parameter_s,
602 602 'nidtN:b:pD:l:rs:T:em:G',
603 603 mode='list', list_all=1)
604 604 if "m" in opts:
605 605 modulename = opts["m"][0]
606 606 modpath = find_mod(modulename)
607 607 if modpath is None:
608 608 warn('%r is not a valid modulename on sys.path'%modulename)
609 609 return
610 610 arg_lst = [modpath] + arg_lst
611 611 try:
612 612 filename = file_finder(arg_lst[0])
613 613 except IndexError:
614 614 warn('you must provide at least a filename.')
615 615 print('\n%run:\n', oinspect.getdoc(self.run))
616 616 return
617 617 except IOError as e:
618 618 try:
619 619 msg = str(e)
620 620 except UnicodeError:
621 621 msg = e.message
622 622 error(msg)
623 623 return
624 624
625 625 if filename.lower().endswith(('.ipy', '.ipynb')):
626 626 with preserve_keys(self.shell.user_ns, '__file__'):
627 627 self.shell.user_ns['__file__'] = filename
628 628 self.shell.safe_execfile_ipy(filename)
629 629 return
630 630
631 631 # Control the response to exit() calls made by the script being run
632 632 exit_ignore = 'e' in opts
633 633
634 634 # Make sure that the running script gets a proper sys.argv as if it
635 635 # were run from a system shell.
636 636 save_argv = sys.argv # save it for later restoring
637 637
638 638 if 'G' in opts:
639 639 args = arg_lst[1:]
640 640 else:
641 641 # tilde and glob expansion
642 642 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
643 643
644 644 sys.argv = [filename] + args # put in the proper filename
645 645 # protect sys.argv from potential unicode strings on Python 2:
646 646 if not py3compat.PY3:
647 647 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
648 648
649 649 if 'i' in opts:
650 650 # Run in user's interactive namespace
651 651 prog_ns = self.shell.user_ns
652 652 __name__save = self.shell.user_ns['__name__']
653 653 prog_ns['__name__'] = '__main__'
654 654 main_mod = self.shell.user_module
655 655
656 656 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
657 657 # set the __file__ global in the script's namespace
658 658 # TK: Is this necessary in interactive mode?
659 659 prog_ns['__file__'] = filename
660 660 else:
661 661 # Run in a fresh, empty namespace
662 662 if 'n' in opts:
663 663 name = os.path.splitext(os.path.basename(filename))[0]
664 664 else:
665 665 name = '__main__'
666 666
667 667 # The shell MUST hold a reference to prog_ns so after %run
668 668 # exits, the python deletion mechanism doesn't zero it out
669 669 # (leaving dangling references). See interactiveshell for details
670 670 main_mod = self.shell.new_main_mod(filename, name)
671 671 prog_ns = main_mod.__dict__
672 672
673 673 # pickle fix. See interactiveshell for an explanation. But we need to
674 674 # make sure that, if we overwrite __main__, we replace it at the end
675 675 main_mod_name = prog_ns['__name__']
676 676
677 677 if main_mod_name == '__main__':
678 678 restore_main = sys.modules['__main__']
679 679 else:
680 680 restore_main = False
681 681
682 682 # This needs to be undone at the end to prevent holding references to
683 683 # every single object ever created.
684 684 sys.modules[main_mod_name] = main_mod
685 685
686 686 if 'p' in opts or 'd' in opts:
687 687 if 'm' in opts:
688 688 code = 'run_module(modulename, prog_ns)'
689 689 code_ns = {
690 690 'run_module': self.shell.safe_run_module,
691 691 'prog_ns': prog_ns,
692 692 'modulename': modulename,
693 693 }
694 694 else:
695 695 if 'd' in opts:
696 696 # allow exceptions to raise in debug mode
697 697 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
698 698 else:
699 699 code = 'execfile(filename, prog_ns)'
700 700 code_ns = {
701 701 'execfile': self.shell.safe_execfile,
702 702 'prog_ns': prog_ns,
703 703 'filename': get_py_filename(filename),
704 704 }
705 705
706 706 try:
707 707 stats = None
708 with self.shell.readline_no_record:
709 if 'p' in opts:
710 stats = self._run_with_profiler(code, opts, code_ns)
708 if 'p' in opts:
709 stats = self._run_with_profiler(code, opts, code_ns)
710 else:
711 if 'd' in opts:
712 bp_file, bp_line = parse_breakpoint(
713 opts.get('b', ['1'])[0], filename)
714 self._run_with_debugger(
715 code, code_ns, filename, bp_line, bp_file)
711 716 else:
712 if 'd' in opts:
713 bp_file, bp_line = parse_breakpoint(
714 opts.get('b', ['1'])[0], filename)
715 self._run_with_debugger(
716 code, code_ns, filename, bp_line, bp_file)
717 if 'm' in opts:
718 def run():
719 self.shell.safe_run_module(modulename, prog_ns)
717 720 else:
718 if 'm' in opts:
719 def run():
720 self.shell.safe_run_module(modulename, prog_ns)
721 else:
722 if runner is None:
723 runner = self.default_runner
724 if runner is None:
725 runner = self.shell.safe_execfile
726
727 def run():
728 runner(filename, prog_ns, prog_ns,
729 exit_ignore=exit_ignore)
730
731 if 't' in opts:
732 # timed execution
733 try:
734 nruns = int(opts['N'][0])
735 if nruns < 1:
736 error('Number of runs must be >=1')
737 return
738 except (KeyError):
739 nruns = 1
740 self._run_with_timing(run, nruns)
741 else:
742 # regular execution
743 run()
744
745 if 'i' in opts:
746 self.shell.user_ns['__name__'] = __name__save
747 else:
748 # update IPython interactive namespace
721 if runner is None:
722 runner = self.default_runner
723 if runner is None:
724 runner = self.shell.safe_execfile
725
726 def run():
727 runner(filename, prog_ns, prog_ns,
728 exit_ignore=exit_ignore)
729
730 if 't' in opts:
731 # timed execution
732 try:
733 nruns = int(opts['N'][0])
734 if nruns < 1:
735 error('Number of runs must be >=1')
736 return
737 except (KeyError):
738 nruns = 1
739 self._run_with_timing(run, nruns)
740 else:
741 # regular execution
742 run()
743
744 if 'i' in opts:
745 self.shell.user_ns['__name__'] = __name__save
746 else:
747 # update IPython interactive namespace
749 748
750 # Some forms of read errors on the file may mean the
751 # __name__ key was never set; using pop we don't have to
752 # worry about a possible KeyError.
753 prog_ns.pop('__name__', None)
749 # Some forms of read errors on the file may mean the
750 # __name__ key was never set; using pop we don't have to
751 # worry about a possible KeyError.
752 prog_ns.pop('__name__', None)
754 753
755 with preserve_keys(self.shell.user_ns, '__file__'):
756 self.shell.user_ns.update(prog_ns)
754 with preserve_keys(self.shell.user_ns, '__file__'):
755 self.shell.user_ns.update(prog_ns)
757 756 finally:
758 757 # It's a bit of a mystery why, but __builtins__ can change from
759 758 # being a module to becoming a dict missing some key data after
760 759 # %run. As best I can see, this is NOT something IPython is doing
761 760 # at all, and similar problems have been reported before:
762 761 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
763 762 # Since this seems to be done by the interpreter itself, the best
764 763 # we can do is to at least restore __builtins__ for the user on
765 764 # exit.
766 765 self.shell.user_ns['__builtins__'] = builtin_mod
767 766
768 767 # Ensure key global structures are restored
769 768 sys.argv = save_argv
770 769 if restore_main:
771 770 sys.modules['__main__'] = restore_main
772 771 else:
773 772 # Remove from sys.modules the reference to main_mod we'd
774 773 # added. Otherwise it will trap references to objects
775 774 # contained therein.
776 775 del sys.modules[main_mod_name]
777 776
778 777 return stats
779 778
780 779 def _run_with_debugger(self, code, code_ns, filename=None,
781 780 bp_line=None, bp_file=None):
782 781 """
783 782 Run `code` in debugger with a break point.
784 783
785 784 Parameters
786 785 ----------
787 786 code : str
788 787 Code to execute.
789 788 code_ns : dict
790 789 A namespace in which `code` is executed.
791 790 filename : str
792 791 `code` is ran as if it is in `filename`.
793 792 bp_line : int, optional
794 793 Line number of the break point.
795 794 bp_file : str, optional
796 795 Path to the file in which break point is specified.
797 796 `filename` is used if not given.
798 797
799 798 Raises
800 799 ------
801 800 UsageError
802 801 If the break point given by `bp_line` is not valid.
803 802
804 803 """
805 804 deb = debugger.Pdb(self.shell.colors)
806 805 # reset Breakpoint state, which is moronically kept
807 806 # in a class
808 807 bdb.Breakpoint.next = 1
809 808 bdb.Breakpoint.bplist = {}
810 809 bdb.Breakpoint.bpbynumber = [None]
811 810 if bp_line is not None:
812 811 # Set an initial breakpoint to stop execution
813 812 maxtries = 10
814 813 bp_file = bp_file or filename
815 814 checkline = deb.checkline(bp_file, bp_line)
816 815 if not checkline:
817 816 for bp in range(bp_line + 1, bp_line + maxtries + 1):
818 817 if deb.checkline(bp_file, bp):
819 818 break
820 819 else:
821 820 msg = ("\nI failed to find a valid line to set "
822 821 "a breakpoint\n"
823 822 "after trying up to line: %s.\n"
824 823 "Please set a valid breakpoint manually "
825 824 "with the -b option." % bp)
826 825 raise UsageError(msg)
827 826 # if we find a good linenumber, set the breakpoint
828 827 deb.do_break('%s:%s' % (bp_file, bp_line))
829 828
830 829 if filename:
831 830 # Mimic Pdb._runscript(...)
832 831 deb._wait_for_mainpyfile = True
833 832 deb.mainpyfile = deb.canonic(filename)
834 833
835 834 # Start file run
836 835 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
837 836 try:
838 837 if filename:
839 838 # save filename so it can be used by methods on the deb object
840 839 deb._exec_filename = filename
841 840 while True:
842 841 try:
843 842 deb.run(code, code_ns)
844 843 except Restart:
845 844 print("Restarting")
846 845 if filename:
847 846 deb._wait_for_mainpyfile = True
848 847 deb.mainpyfile = deb.canonic(filename)
849 848 continue
850 849 else:
851 850 break
852 851
853 852
854 853 except:
855 854 etype, value, tb = sys.exc_info()
856 855 # Skip three frames in the traceback: the %run one,
857 856 # one inside bdb.py, and the command-line typed by the
858 857 # user (run by exec in pdb itself).
859 858 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
860 859
861 860 @staticmethod
862 861 def _run_with_timing(run, nruns):
863 862 """
864 863 Run function `run` and print timing information.
865 864
866 865 Parameters
867 866 ----------
868 867 run : callable
869 868 Any callable object which takes no argument.
870 869 nruns : int
871 870 Number of times to execute `run`.
872 871
873 872 """
874 873 twall0 = time.time()
875 874 if nruns == 1:
876 875 t0 = clock2()
877 876 run()
878 877 t1 = clock2()
879 878 t_usr = t1[0] - t0[0]
880 879 t_sys = t1[1] - t0[1]
881 880 print("\nIPython CPU timings (estimated):")
882 881 print(" User : %10.2f s." % t_usr)
883 882 print(" System : %10.2f s." % t_sys)
884 883 else:
885 884 runs = range(nruns)
886 885 t0 = clock2()
887 886 for nr in runs:
888 887 run()
889 888 t1 = clock2()
890 889 t_usr = t1[0] - t0[0]
891 890 t_sys = t1[1] - t0[1]
892 891 print("\nIPython CPU timings (estimated):")
893 892 print("Total runs performed:", nruns)
894 893 print(" Times : %10s %10s" % ('Total', 'Per run'))
895 894 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
896 895 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
897 896 twall1 = time.time()
898 897 print("Wall time: %10.2f s." % (twall1 - twall0))
899 898
900 899 @skip_doctest
901 900 @line_cell_magic
902 901 def timeit(self, line='', cell=None):
903 902 """Time execution of a Python statement or expression
904 903
905 904 Usage, in line mode:
906 905 %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
907 906 or in cell mode:
908 907 %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
909 908 code
910 909 code...
911 910
912 911 Time execution of a Python statement or expression using the timeit
913 912 module. This function can be used both as a line and cell magic:
914 913
915 914 - In line mode you can time a single-line statement (though multiple
916 915 ones can be chained with using semicolons).
917 916
918 917 - In cell mode, the statement in the first line is used as setup code
919 918 (executed but not timed) and the body of the cell is timed. The cell
920 919 body has access to any variables created in the setup code.
921 920
922 921 Options:
923 922 -n<N>: execute the given statement <N> times in a loop. If this value
924 923 is not given, a fitting value is chosen.
925 924
926 925 -r<R>: repeat the loop iteration <R> times and take the best result.
927 926 Default: 3
928 927
929 928 -t: use time.time to measure the time, which is the default on Unix.
930 929 This function measures wall time.
931 930
932 931 -c: use time.clock to measure the time, which is the default on
933 932 Windows and measures wall time. On Unix, resource.getrusage is used
934 933 instead and returns the CPU user time.
935 934
936 935 -p<P>: use a precision of <P> digits to display the timing result.
937 936 Default: 3
938 937
939 938 -q: Quiet, do not print result.
940 939
941 940 -o: return a TimeitResult that can be stored in a variable to inspect
942 941 the result in more details.
943 942
944 943
945 944 Examples
946 945 --------
947 946 ::
948 947
949 948 In [1]: %timeit pass
950 949 10000000 loops, best of 3: 53.3 ns per loop
951 950
952 951 In [2]: u = None
953 952
954 953 In [3]: %timeit u is None
955 954 10000000 loops, best of 3: 184 ns per loop
956 955
957 956 In [4]: %timeit -r 4 u == None
958 957 1000000 loops, best of 4: 242 ns per loop
959 958
960 959 In [5]: import time
961 960
962 961 In [6]: %timeit -n1 time.sleep(2)
963 962 1 loop, best of 3: 2 s per loop
964 963
965 964
966 965 The times reported by %timeit will be slightly higher than those
967 966 reported by the timeit.py script when variables are accessed. This is
968 967 due to the fact that %timeit executes the statement in the namespace
969 968 of the shell, compared with timeit.py, which uses a single setup
970 969 statement to import function or create variables. Generally, the bias
971 970 does not matter as long as results from timeit.py are not mixed with
972 971 those from %timeit."""
973 972
974 973 opts, stmt = self.parse_options(line,'n:r:tcp:qo',
975 974 posix=False, strict=False)
976 975 if stmt == "" and cell is None:
977 976 return
978 977
979 978 timefunc = timeit.default_timer
980 979 number = int(getattr(opts, "n", 0))
981 980 repeat = int(getattr(opts, "r", timeit.default_repeat))
982 981 precision = int(getattr(opts, "p", 3))
983 982 quiet = 'q' in opts
984 983 return_result = 'o' in opts
985 984 if hasattr(opts, "t"):
986 985 timefunc = time.time
987 986 if hasattr(opts, "c"):
988 987 timefunc = clock
989 988
990 989 timer = Timer(timer=timefunc)
991 990 # this code has tight coupling to the inner workings of timeit.Timer,
992 991 # but is there a better way to achieve that the code stmt has access
993 992 # to the shell namespace?
994 993 transform = self.shell.input_splitter.transform_cell
995 994
996 995 if cell is None:
997 996 # called as line magic
998 997 ast_setup = self.shell.compile.ast_parse("pass")
999 998 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1000 999 else:
1001 1000 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1002 1001 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1003 1002
1004 1003 ast_setup = self.shell.transform_ast(ast_setup)
1005 1004 ast_stmt = self.shell.transform_ast(ast_stmt)
1006 1005
1007 1006 # This codestring is taken from timeit.template - we fill it in as an
1008 1007 # AST, so that we can apply our AST transformations to the user code
1009 1008 # without affecting the timing code.
1010 1009 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1011 1010 ' setup\n'
1012 1011 ' _t0 = _timer()\n'
1013 1012 ' for _i in _it:\n'
1014 1013 ' stmt\n'
1015 1014 ' _t1 = _timer()\n'
1016 1015 ' return _t1 - _t0\n')
1017 1016
1018 1017 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1019 1018 timeit_ast = ast.fix_missing_locations(timeit_ast)
1020 1019
1021 1020 # Track compilation time so it can be reported if too long
1022 1021 # Minimum time above which compilation time will be reported
1023 1022 tc_min = 0.1
1024 1023
1025 1024 t0 = clock()
1026 1025 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1027 1026 tc = clock()-t0
1028 1027
1029 1028 ns = {}
1030 1029 exec(code, self.shell.user_ns, ns)
1031 1030 timer.inner = ns["inner"]
1032 1031
1033 1032 # This is used to check if there is a huge difference between the
1034 1033 # best and worst timings.
1035 1034 # Issue: https://github.com/ipython/ipython/issues/6471
1036 1035 worst_tuning = 0
1037 1036 if number == 0:
1038 1037 # determine number so that 0.2 <= total time < 2.0
1039 1038 number = 1
1040 1039 for _ in range(1, 10):
1041 1040 time_number = timer.timeit(number)
1042 1041 worst_tuning = max(worst_tuning, time_number / number)
1043 1042 if time_number >= 0.2:
1044 1043 break
1045 1044 number *= 10
1046 1045 all_runs = timer.repeat(repeat, number)
1047 1046 best = min(all_runs) / number
1048 1047
1049 1048 worst = max(all_runs) / number
1050 1049 if worst_tuning:
1051 1050 worst = max(worst, worst_tuning)
1052 1051
1053 1052 if not quiet :
1054 1053 # Check best timing is greater than zero to avoid a
1055 1054 # ZeroDivisionError.
1056 1055 # In cases where the slowest timing is lesser than a micosecond
1057 1056 # we assume that it does not really matter if the fastest
1058 1057 # timing is 4 times faster than the slowest timing or not.
1059 1058 if worst > 4 * best and best > 0 and worst > 1e-6:
1060 1059 print("The slowest run took %0.2f times longer than the "
1061 1060 "fastest. This could mean that an intermediate result "
1062 1061 "is being cached." % (worst / best))
1063 1062 if number == 1: # No s at "loops" if only one loop
1064 1063 print(u"%d loop, best of %d: %s per loop" % (number, repeat,
1065 1064 _format_time(best, precision)))
1066 1065 else:
1067 1066 print(u"%d loops, best of %d: %s per loop" % (number, repeat,
1068 1067 _format_time(best, precision)))
1069 1068 if tc > tc_min:
1070 1069 print("Compiler time: %.2f s" % tc)
1071 1070 if return_result:
1072 1071 return TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1073 1072
1074 1073 @skip_doctest
1075 1074 @needs_local_scope
1076 1075 @line_cell_magic
1077 1076 def time(self,line='', cell=None, local_ns=None):
1078 1077 """Time execution of a Python statement or expression.
1079 1078
1080 1079 The CPU and wall clock times are printed, and the value of the
1081 1080 expression (if any) is returned. Note that under Win32, system time
1082 1081 is always reported as 0, since it can not be measured.
1083 1082
1084 1083 This function can be used both as a line and cell magic:
1085 1084
1086 1085 - In line mode you can time a single-line statement (though multiple
1087 1086 ones can be chained with using semicolons).
1088 1087
1089 1088 - In cell mode, you can time the cell body (a directly
1090 1089 following statement raises an error).
1091 1090
1092 1091 This function provides very basic timing functionality. Use the timeit
1093 1092 magic for more control over the measurement.
1094 1093
1095 1094 Examples
1096 1095 --------
1097 1096 ::
1098 1097
1099 1098 In [1]: %time 2**128
1100 1099 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1101 1100 Wall time: 0.00
1102 1101 Out[1]: 340282366920938463463374607431768211456L
1103 1102
1104 1103 In [2]: n = 1000000
1105 1104
1106 1105 In [3]: %time sum(range(n))
1107 1106 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1108 1107 Wall time: 1.37
1109 1108 Out[3]: 499999500000L
1110 1109
1111 1110 In [4]: %time print 'hello world'
1112 1111 hello world
1113 1112 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1114 1113 Wall time: 0.00
1115 1114
1116 1115 Note that the time needed by Python to compile the given expression
1117 1116 will be reported if it is more than 0.1s. In this example, the
1118 1117 actual exponentiation is done by Python at compilation time, so while
1119 1118 the expression can take a noticeable amount of time to compute, that
1120 1119 time is purely due to the compilation:
1121 1120
1122 1121 In [5]: %time 3**9999;
1123 1122 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1124 1123 Wall time: 0.00 s
1125 1124
1126 1125 In [6]: %time 3**999999;
1127 1126 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1128 1127 Wall time: 0.00 s
1129 1128 Compiler : 0.78 s
1130 1129 """
1131 1130
1132 1131 # fail immediately if the given expression can't be compiled
1133 1132
1134 1133 if line and cell:
1135 1134 raise UsageError("Can't use statement directly after '%%time'!")
1136 1135
1137 1136 if cell:
1138 1137 expr = self.shell.input_transformer_manager.transform_cell(cell)
1139 1138 else:
1140 1139 expr = self.shell.input_transformer_manager.transform_cell(line)
1141 1140
1142 1141 # Minimum time above which parse time will be reported
1143 1142 tp_min = 0.1
1144 1143
1145 1144 t0 = clock()
1146 1145 expr_ast = self.shell.compile.ast_parse(expr)
1147 1146 tp = clock()-t0
1148 1147
1149 1148 # Apply AST transformations
1150 1149 expr_ast = self.shell.transform_ast(expr_ast)
1151 1150
1152 1151 # Minimum time above which compilation time will be reported
1153 1152 tc_min = 0.1
1154 1153
1155 1154 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1156 1155 mode = 'eval'
1157 1156 source = '<timed eval>'
1158 1157 expr_ast = ast.Expression(expr_ast.body[0].value)
1159 1158 else:
1160 1159 mode = 'exec'
1161 1160 source = '<timed exec>'
1162 1161 t0 = clock()
1163 1162 code = self.shell.compile(expr_ast, source, mode)
1164 1163 tc = clock()-t0
1165 1164
1166 1165 # skew measurement as little as possible
1167 1166 glob = self.shell.user_ns
1168 1167 wtime = time.time
1169 1168 # time execution
1170 1169 wall_st = wtime()
1171 1170 if mode=='eval':
1172 1171 st = clock2()
1173 1172 out = eval(code, glob, local_ns)
1174 1173 end = clock2()
1175 1174 else:
1176 1175 st = clock2()
1177 1176 exec(code, glob, local_ns)
1178 1177 end = clock2()
1179 1178 out = None
1180 1179 wall_end = wtime()
1181 1180 # Compute actual times and report
1182 1181 wall_time = wall_end-wall_st
1183 1182 cpu_user = end[0]-st[0]
1184 1183 cpu_sys = end[1]-st[1]
1185 1184 cpu_tot = cpu_user+cpu_sys
1186 1185 # On windows cpu_sys is always zero, so no new information to the next print
1187 1186 if sys.platform != 'win32':
1188 1187 print("CPU times: user %s, sys: %s, total: %s" % \
1189 1188 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1190 1189 print("Wall time: %s" % _format_time(wall_time))
1191 1190 if tc > tc_min:
1192 1191 print("Compiler : %s" % _format_time(tc))
1193 1192 if tp > tp_min:
1194 1193 print("Parser : %s" % _format_time(tp))
1195 1194 return out
1196 1195
1197 1196 @skip_doctest
1198 1197 @line_magic
1199 1198 def macro(self, parameter_s=''):
1200 1199 """Define a macro for future re-execution. It accepts ranges of history,
1201 1200 filenames or string objects.
1202 1201
1203 1202 Usage:\\
1204 1203 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1205 1204
1206 1205 Options:
1207 1206
1208 1207 -r: use 'raw' input. By default, the 'processed' history is used,
1209 1208 so that magics are loaded in their transformed version to valid
1210 1209 Python. If this option is given, the raw input as typed at the
1211 1210 command line is used instead.
1212 1211
1213 1212 -q: quiet macro definition. By default, a tag line is printed
1214 1213 to indicate the macro has been created, and then the contents of
1215 1214 the macro are printed. If this option is given, then no printout
1216 1215 is produced once the macro is created.
1217 1216
1218 1217 This will define a global variable called `name` which is a string
1219 1218 made of joining the slices and lines you specify (n1,n2,... numbers
1220 1219 above) from your input history into a single string. This variable
1221 1220 acts like an automatic function which re-executes those lines as if
1222 1221 you had typed them. You just type 'name' at the prompt and the code
1223 1222 executes.
1224 1223
1225 1224 The syntax for indicating input ranges is described in %history.
1226 1225
1227 1226 Note: as a 'hidden' feature, you can also use traditional python slice
1228 1227 notation, where N:M means numbers N through M-1.
1229 1228
1230 1229 For example, if your history contains (print using %hist -n )::
1231 1230
1232 1231 44: x=1
1233 1232 45: y=3
1234 1233 46: z=x+y
1235 1234 47: print x
1236 1235 48: a=5
1237 1236 49: print 'x',x,'y',y
1238 1237
1239 1238 you can create a macro with lines 44 through 47 (included) and line 49
1240 1239 called my_macro with::
1241 1240
1242 1241 In [55]: %macro my_macro 44-47 49
1243 1242
1244 1243 Now, typing `my_macro` (without quotes) will re-execute all this code
1245 1244 in one pass.
1246 1245
1247 1246 You don't need to give the line-numbers in order, and any given line
1248 1247 number can appear multiple times. You can assemble macros with any
1249 1248 lines from your input history in any order.
1250 1249
1251 1250 The macro is a simple object which holds its value in an attribute,
1252 1251 but IPython's display system checks for macros and executes them as
1253 1252 code instead of printing them when you type their name.
1254 1253
1255 1254 You can view a macro's contents by explicitly printing it with::
1256 1255
1257 1256 print macro_name
1258 1257
1259 1258 """
1260 1259 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1261 1260 if not args: # List existing macros
1262 1261 return sorted(k for k,v in iteritems(self.shell.user_ns) if\
1263 1262 isinstance(v, Macro))
1264 1263 if len(args) == 1:
1265 1264 raise UsageError(
1266 1265 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1267 1266 name, codefrom = args[0], " ".join(args[1:])
1268 1267
1269 1268 #print 'rng',ranges # dbg
1270 1269 try:
1271 1270 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1272 1271 except (ValueError, TypeError) as e:
1273 1272 print(e.args[0])
1274 1273 return
1275 1274 macro = Macro(lines)
1276 1275 self.shell.define_macro(name, macro)
1277 1276 if not ( 'q' in opts) :
1278 1277 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1279 1278 print('=== Macro contents: ===')
1280 1279 print(macro, end=' ')
1281 1280
1282 1281 @magic_arguments.magic_arguments()
1283 1282 @magic_arguments.argument('output', type=str, default='', nargs='?',
1284 1283 help="""The name of the variable in which to store output.
1285 1284 This is a utils.io.CapturedIO object with stdout/err attributes
1286 1285 for the text of the captured output.
1287 1286
1288 1287 CapturedOutput also has a show() method for displaying the output,
1289 1288 and __call__ as well, so you can use that to quickly display the
1290 1289 output.
1291 1290
1292 1291 If unspecified, captured output is discarded.
1293 1292 """
1294 1293 )
1295 1294 @magic_arguments.argument('--no-stderr', action="store_true",
1296 1295 help="""Don't capture stderr."""
1297 1296 )
1298 1297 @magic_arguments.argument('--no-stdout', action="store_true",
1299 1298 help="""Don't capture stdout."""
1300 1299 )
1301 1300 @magic_arguments.argument('--no-display', action="store_true",
1302 1301 help="""Don't capture IPython's rich display."""
1303 1302 )
1304 1303 @cell_magic
1305 1304 def capture(self, line, cell):
1306 1305 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1307 1306 args = magic_arguments.parse_argstring(self.capture, line)
1308 1307 out = not args.no_stdout
1309 1308 err = not args.no_stderr
1310 1309 disp = not args.no_display
1311 1310 with capture_output(out, err, disp) as io:
1312 1311 self.shell.run_cell(cell)
1313 1312 if args.output:
1314 1313 self.shell.user_ns[args.output] = io
1315 1314
1316 1315 def parse_breakpoint(text, current_file):
1317 1316 '''Returns (file, line) for file:line and (current_file, line) for line'''
1318 1317 colon = text.find(':')
1319 1318 if colon == -1:
1320 1319 return current_file, int(text)
1321 1320 else:
1322 1321 return text[:colon], int(text[colon+1:])
1323 1322
1324 1323 def _format_time(timespan, precision=3):
1325 1324 """Formats the timespan in a human readable form"""
1326 1325 import math
1327 1326
1328 1327 if timespan >= 60.0:
1329 1328 # we have more than a minute, format that in a human readable form
1330 1329 # Idea from http://snipplr.com/view/5713/
1331 1330 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1332 1331 time = []
1333 1332 leftover = timespan
1334 1333 for suffix, length in parts:
1335 1334 value = int(leftover / length)
1336 1335 if value > 0:
1337 1336 leftover = leftover % length
1338 1337 time.append(u'%s%s' % (str(value), suffix))
1339 1338 if leftover < 1:
1340 1339 break
1341 1340 return " ".join(time)
1342 1341
1343 1342
1344 1343 # Unfortunately the unicode 'micro' symbol can cause problems in
1345 1344 # certain terminals.
1346 1345 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1347 1346 # Try to prevent crashes by being more secure than it needs to
1348 1347 # E.g. eclipse is able to print a Β΅, but has no sys.stdout.encoding set.
1349 1348 units = [u"s", u"ms",u'us',"ns"] # the save value
1350 1349 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1351 1350 try:
1352 1351 u'\xb5'.encode(sys.stdout.encoding)
1353 1352 units = [u"s", u"ms",u'\xb5s',"ns"]
1354 1353 except:
1355 1354 pass
1356 1355 scaling = [1, 1e3, 1e6, 1e9]
1357 1356
1358 1357 if timespan > 0.0:
1359 1358 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1360 1359 else:
1361 1360 order = 3
1362 1361 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
@@ -1,415 +1,409 b''
1 1 # encoding: utf-8
2 2 """
3 3 A mixin for :class:`~IPython.core.application.Application` classes that
4 4 launch InteractiveShell instances, load extensions, etc.
5 5 """
6 6
7 7 # Copyright (c) IPython Development Team.
8 8 # Distributed under the terms of the Modified BSD License.
9 9
10 10 from __future__ import absolute_import
11 11 from __future__ import print_function
12 12
13 13 import glob
14 14 import os
15 15 import sys
16 16
17 17 from traitlets.config.application import boolean_flag
18 18 from traitlets.config.configurable import Configurable
19 19 from traitlets.config.loader import Config
20 20 from IPython.core import pylabtools
21 21 from IPython.utils import py3compat
22 22 from IPython.utils.contexts import preserve_keys
23 23 from IPython.utils.path import filefind
24 24 from traitlets import (
25 25 Unicode, Instance, List, Bool, CaselessStrEnum, observe,
26 26 )
27 27 from IPython.lib.inputhook import guis
28 28
29 29 #-----------------------------------------------------------------------------
30 30 # Aliases and Flags
31 31 #-----------------------------------------------------------------------------
32 32
33 33 gui_keys = tuple(sorted([ key for key in guis if key is not None ]))
34 34
35 35 backend_keys = sorted(pylabtools.backends.keys())
36 36 backend_keys.insert(0, 'auto')
37 37
38 38 shell_flags = {}
39 39
40 40 addflag = lambda *args: shell_flags.update(boolean_flag(*args))
41 41 addflag('autoindent', 'InteractiveShell.autoindent',
42 42 'Turn on autoindenting.', 'Turn off autoindenting.'
43 43 )
44 44 addflag('automagic', 'InteractiveShell.automagic',
45 45 """Turn on the auto calling of magic commands. Type %%magic at the
46 46 IPython prompt for more information.""",
47 47 'Turn off the auto calling of magic commands.'
48 48 )
49 49 addflag('pdb', 'InteractiveShell.pdb',
50 50 "Enable auto calling the pdb debugger after every exception.",
51 51 "Disable auto calling the pdb debugger after every exception."
52 52 )
53 53 addflag('pprint', 'PlainTextFormatter.pprint',
54 54 "Enable auto pretty printing of results.",
55 55 "Disable auto pretty printing of results."
56 56 )
57 57 addflag('color-info', 'InteractiveShell.color_info',
58 58 """IPython can display information about objects via a set of functions,
59 59 and optionally can use colors for this, syntax highlighting
60 60 source code and various other elements. This is on by default, but can cause
61 61 problems with some pagers. If you see such problems, you can disable the
62 62 colours.""",
63 63 "Disable using colors for info related things."
64 64 )
65 65 nosep_config = Config()
66 66 nosep_config.InteractiveShell.separate_in = ''
67 67 nosep_config.InteractiveShell.separate_out = ''
68 68 nosep_config.InteractiveShell.separate_out2 = ''
69 69
70 70 shell_flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.")
71 71 shell_flags['pylab'] = (
72 72 {'InteractiveShellApp' : {'pylab' : 'auto'}},
73 73 """Pre-load matplotlib and numpy for interactive use with
74 74 the default matplotlib backend."""
75 75 )
76 76 shell_flags['matplotlib'] = (
77 77 {'InteractiveShellApp' : {'matplotlib' : 'auto'}},
78 78 """Configure matplotlib for interactive use with
79 79 the default matplotlib backend."""
80 80 )
81 81
82 82 # it's possible we don't want short aliases for *all* of these:
83 83 shell_aliases = dict(
84 84 autocall='InteractiveShell.autocall',
85 85 colors='InteractiveShell.colors',
86 86 logfile='InteractiveShell.logfile',
87 87 logappend='InteractiveShell.logappend',
88 88 c='InteractiveShellApp.code_to_run',
89 89 m='InteractiveShellApp.module_to_run',
90 90 ext='InteractiveShellApp.extra_extension',
91 91 gui='InteractiveShellApp.gui',
92 92 pylab='InteractiveShellApp.pylab',
93 93 matplotlib='InteractiveShellApp.matplotlib',
94 94 )
95 95 shell_aliases['cache-size'] = 'InteractiveShell.cache_size'
96 96
97 97 #-----------------------------------------------------------------------------
98 98 # Main classes and functions
99 99 #-----------------------------------------------------------------------------
100 100
101 101 class InteractiveShellApp(Configurable):
102 102 """A Mixin for applications that start InteractiveShell instances.
103 103
104 104 Provides configurables for loading extensions and executing files
105 105 as part of configuring a Shell environment.
106 106
107 107 The following methods should be called by the :meth:`initialize` method
108 108 of the subclass:
109 109
110 110 - :meth:`init_path`
111 111 - :meth:`init_shell` (to be implemented by the subclass)
112 112 - :meth:`init_gui_pylab`
113 113 - :meth:`init_extensions`
114 114 - :meth:`init_code`
115 115 """
116 116 extensions = List(Unicode(),
117 117 help="A list of dotted module names of IPython extensions to load."
118 118 ).tag(config=True)
119 119 extra_extension = Unicode('',
120 120 help="dotted module name of an IPython extension to load."
121 121 ).tag(config=True)
122 122
123 123 reraise_ipython_extension_failures = Bool(False,
124 124 help="Reraise exceptions encountered loading IPython extensions?",
125 125 ).tag(config=True)
126 126
127 127 # Extensions that are always loaded (not configurable)
128 128 default_extensions = List(Unicode(), [u'storemagic']).tag(config=False)
129 129
130 130 hide_initial_ns = Bool(True,
131 131 help="""Should variables loaded at startup (by startup files, exec_lines, etc.)
132 132 be hidden from tools like %who?"""
133 133 ).tag(config=True)
134 134
135 135 exec_files = List(Unicode(),
136 136 help="""List of files to run at IPython startup."""
137 137 ).tag(config=True)
138 138 exec_PYTHONSTARTUP = Bool(True,
139 139 help="""Run the file referenced by the PYTHONSTARTUP environment
140 140 variable at IPython startup."""
141 141 ).tag(config=True)
142 142 file_to_run = Unicode('',
143 143 help="""A file to be run""").tag(config=True)
144 144
145 145 exec_lines = List(Unicode(),
146 146 help="""lines of code to run at IPython startup."""
147 147 ).tag(config=True)
148 148 code_to_run = Unicode('',
149 149 help="Execute the given command string."
150 150 ).tag(config=True)
151 151 module_to_run = Unicode('',
152 152 help="Run the module as a script."
153 153 ).tag(config=True)
154 154 gui = CaselessStrEnum(gui_keys, allow_none=True,
155 155 help="Enable GUI event loop integration with any of {0}.".format(gui_keys)
156 156 ).tag(config=True)
157 157 matplotlib = CaselessStrEnum(backend_keys, allow_none=True,
158 158 help="""Configure matplotlib for interactive use with
159 159 the default matplotlib backend."""
160 160 ).tag(config=True)
161 161 pylab = CaselessStrEnum(backend_keys, allow_none=True,
162 162 help="""Pre-load matplotlib and numpy for interactive use,
163 163 selecting a particular matplotlib backend and loop integration.
164 164 """
165 165 ).tag(config=True)
166 166 pylab_import_all = Bool(True,
167 167 help="""If true, IPython will populate the user namespace with numpy, pylab, etc.
168 168 and an ``import *`` is done from numpy and pylab, when using pylab mode.
169 169
170 170 When False, pylab mode should not import any names into the user namespace.
171 171 """
172 172 ).tag(config=True)
173 173 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
174 174 allow_none=True)
175 175 # whether interact-loop should start
176 176 interact = Bool(True)
177 177
178 178 user_ns = Instance(dict, args=None, allow_none=True)
179 179 @observe('user_ns')
180 180 def _user_ns_changed(self, change):
181 181 if self.shell is not None:
182 182 self.shell.user_ns = change['new']
183 183 self.shell.init_user_ns()
184 184
185 185 def init_path(self):
186 186 """Add current working directory, '', to sys.path"""
187 187 if sys.path[0] != '':
188 188 sys.path.insert(0, '')
189 189
190 190 def init_shell(self):
191 191 raise NotImplementedError("Override in subclasses")
192 192
193 193 def init_gui_pylab(self):
194 194 """Enable GUI event loop integration, taking pylab into account."""
195 195 enable = False
196 196 shell = self.shell
197 197 if self.pylab:
198 198 enable = lambda key: shell.enable_pylab(key, import_all=self.pylab_import_all)
199 199 key = self.pylab
200 200 elif self.matplotlib:
201 201 enable = shell.enable_matplotlib
202 202 key = self.matplotlib
203 203 elif self.gui:
204 204 enable = shell.enable_gui
205 205 key = self.gui
206 206
207 207 if not enable:
208 208 return
209 209
210 210 try:
211 211 r = enable(key)
212 212 except ImportError:
213 213 self.log.warning("Eventloop or matplotlib integration failed. Is matplotlib installed?")
214 214 self.shell.showtraceback()
215 215 return
216 216 except Exception:
217 217 self.log.warning("GUI event loop or pylab initialization failed")
218 218 self.shell.showtraceback()
219 219 return
220 220
221 221 if isinstance(r, tuple):
222 222 gui, backend = r[:2]
223 223 self.log.info("Enabling GUI event loop integration, "
224 224 "eventloop=%s, matplotlib=%s", gui, backend)
225 225 if key == "auto":
226 226 print("Using matplotlib backend: %s" % backend)
227 227 else:
228 228 gui = r
229 229 self.log.info("Enabling GUI event loop integration, "
230 230 "eventloop=%s", gui)
231 231
232 232 def init_extensions(self):
233 233 """Load all IPython extensions in IPythonApp.extensions.
234 234
235 235 This uses the :meth:`ExtensionManager.load_extensions` to load all
236 236 the extensions listed in ``self.extensions``.
237 237 """
238 238 try:
239 239 self.log.debug("Loading IPython extensions...")
240 240 extensions = self.default_extensions + self.extensions
241 241 if self.extra_extension:
242 242 extensions.append(self.extra_extension)
243 243 for ext in extensions:
244 244 try:
245 245 self.log.info("Loading IPython extension: %s" % ext)
246 246 self.shell.extension_manager.load_extension(ext)
247 247 except:
248 248 if self.reraise_ipython_extension_failures:
249 249 raise
250 250 msg = ("Error in loading extension: {ext}\n"
251 251 "Check your config files in {location}".format(
252 252 ext=ext,
253 253 location=self.profile_dir.location
254 254 ))
255 255 self.log.warning(msg, exc_info=True)
256 256 except:
257 257 if self.reraise_ipython_extension_failures:
258 258 raise
259 259 self.log.warning("Unknown error in loading extensions:", exc_info=True)
260 260
261 261 def init_code(self):
262 262 """run the pre-flight code, specified via exec_lines"""
263 263 self._run_startup_files()
264 264 self._run_exec_lines()
265 265 self._run_exec_files()
266 266
267 267 # Hide variables defined here from %who etc.
268 268 if self.hide_initial_ns:
269 269 self.shell.user_ns_hidden.update(self.shell.user_ns)
270 270
271 271 # command-line execution (ipython -i script.py, ipython -m module)
272 272 # should *not* be excluded from %whos
273 273 self._run_cmd_line_code()
274 274 self._run_module()
275 275
276 276 # flush output, so itwon't be attached to the first cell
277 277 sys.stdout.flush()
278 278 sys.stderr.flush()
279 279
280 280 def _run_exec_lines(self):
281 281 """Run lines of code in IPythonApp.exec_lines in the user's namespace."""
282 282 if not self.exec_lines:
283 283 return
284 284 try:
285 285 self.log.debug("Running code from IPythonApp.exec_lines...")
286 286 for line in self.exec_lines:
287 287 try:
288 288 self.log.info("Running code in user namespace: %s" %
289 289 line)
290 290 self.shell.run_cell(line, store_history=False)
291 291 except:
292 292 self.log.warning("Error in executing line in user "
293 293 "namespace: %s" % line)
294 294 self.shell.showtraceback()
295 295 except:
296 296 self.log.warning("Unknown error in handling IPythonApp.exec_lines:")
297 297 self.shell.showtraceback()
298 298
299 299 def _exec_file(self, fname, shell_futures=False):
300 300 try:
301 301 full_filename = filefind(fname, [u'.', self.ipython_dir])
302 302 except IOError:
303 303 self.log.warning("File not found: %r"%fname)
304 304 return
305 305 # Make sure that the running script gets a proper sys.argv as if it
306 306 # were run from a system shell.
307 307 save_argv = sys.argv
308 308 sys.argv = [full_filename] + self.extra_args[1:]
309 309 # protect sys.argv from potential unicode strings on Python 2:
310 310 if not py3compat.PY3:
311 311 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
312 312 try:
313 313 if os.path.isfile(full_filename):
314 314 self.log.info("Running file in user namespace: %s" %
315 315 full_filename)
316 316 # Ensure that __file__ is always defined to match Python
317 317 # behavior.
318 318 with preserve_keys(self.shell.user_ns, '__file__'):
319 319 self.shell.user_ns['__file__'] = fname
320 320 if full_filename.endswith('.ipy'):
321 321 self.shell.safe_execfile_ipy(full_filename,
322 322 shell_futures=shell_futures)
323 323 else:
324 324 # default to python, even without extension
325 325 self.shell.safe_execfile(full_filename,
326 326 self.shell.user_ns,
327 327 shell_futures=shell_futures,
328 328 raise_exceptions=True)
329 329 finally:
330 330 sys.argv = save_argv
331 331
332 332 def _run_startup_files(self):
333 333 """Run files from profile startup directory"""
334 334 startup_dir = self.profile_dir.startup_dir
335 335 startup_files = []
336 336
337 337 if self.exec_PYTHONSTARTUP and os.environ.get('PYTHONSTARTUP', False) and \
338 338 not (self.file_to_run or self.code_to_run or self.module_to_run):
339 339 python_startup = os.environ['PYTHONSTARTUP']
340 340 self.log.debug("Running PYTHONSTARTUP file %s...", python_startup)
341 341 try:
342 342 self._exec_file(python_startup)
343 343 except:
344 344 self.log.warning("Unknown error in handling PYTHONSTARTUP file %s:", python_startup)
345 345 self.shell.showtraceback()
346 finally:
347 # Many PYTHONSTARTUP files set up the readline completions,
348 # but this is often at odds with IPython's own completions.
349 # Do not allow PYTHONSTARTUP to set up readline.
350 if self.shell.has_readline:
351 self.shell.set_readline_completer()
352 346
353 347 startup_files += glob.glob(os.path.join(startup_dir, '*.py'))
354 348 startup_files += glob.glob(os.path.join(startup_dir, '*.ipy'))
355 349 if not startup_files:
356 350 return
357 351
358 352 self.log.debug("Running startup files from %s...", startup_dir)
359 353 try:
360 354 for fname in sorted(startup_files):
361 355 self._exec_file(fname)
362 356 except:
363 357 self.log.warning("Unknown error in handling startup files:")
364 358 self.shell.showtraceback()
365 359
366 360 def _run_exec_files(self):
367 361 """Run files from IPythonApp.exec_files"""
368 362 if not self.exec_files:
369 363 return
370 364
371 365 self.log.debug("Running files in IPythonApp.exec_files...")
372 366 try:
373 367 for fname in self.exec_files:
374 368 self._exec_file(fname)
375 369 except:
376 370 self.log.warning("Unknown error in handling IPythonApp.exec_files:")
377 371 self.shell.showtraceback()
378 372
379 373 def _run_cmd_line_code(self):
380 374 """Run code or file specified at the command-line"""
381 375 if self.code_to_run:
382 376 line = self.code_to_run
383 377 try:
384 378 self.log.info("Running code given at command line (c=): %s" %
385 379 line)
386 380 self.shell.run_cell(line, store_history=False)
387 381 except:
388 382 self.log.warning("Error in executing line in user namespace: %s" %
389 383 line)
390 384 self.shell.showtraceback()
391 385 if not self.interact:
392 386 self.exit(1)
393 387
394 388 # Like Python itself, ignore the second if the first of these is present
395 389 elif self.file_to_run:
396 390 fname = self.file_to_run
397 391 try:
398 392 self._exec_file(fname, shell_futures=True)
399 393 except:
400 394 self.shell.showtraceback(tb_offset=4)
401 395 if not self.interact:
402 396 self.exit(1)
403 397
404 398 def _run_module(self):
405 399 """Run module specified at the command-line."""
406 400 if self.module_to_run:
407 401 # Make sure that the module gets a proper sys.argv as if it were
408 402 # run using `python -m`.
409 403 save_argv = sys.argv
410 404 sys.argv = [sys.executable] + self.extra_args
411 405 try:
412 406 self.shell.safe_run_module(self.module_to_run,
413 407 self.shell.user_ns)
414 408 finally:
415 409 sys.argv = save_argv
@@ -1,1495 +1,1494 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Verbose and colourful traceback formatting.
4 4
5 5 **ColorTB**
6 6
7 7 I've always found it a bit hard to visually parse tracebacks in Python. The
8 8 ColorTB class is a solution to that problem. It colors the different parts of a
9 9 traceback in a manner similar to what you would expect from a syntax-highlighting
10 10 text editor.
11 11
12 12 Installation instructions for ColorTB::
13 13
14 14 import sys,ultratb
15 15 sys.excepthook = ultratb.ColorTB()
16 16
17 17 **VerboseTB**
18 18
19 19 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
20 20 of useful info when a traceback occurs. Ping originally had it spit out HTML
21 21 and intended it for CGI programmers, but why should they have all the fun? I
22 22 altered it to spit out colored text to the terminal. It's a bit overwhelming,
23 23 but kind of neat, and maybe useful for long-running programs that you believe
24 24 are bug-free. If a crash *does* occur in that type of program you want details.
25 25 Give it a shot--you'll love it or you'll hate it.
26 26
27 27 .. note::
28 28
29 29 The Verbose mode prints the variables currently visible where the exception
30 30 happened (shortening their strings if too long). This can potentially be
31 31 very slow, if you happen to have a huge data structure whose string
32 32 representation is complex to compute. Your computer may appear to freeze for
33 33 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
34 34 with Ctrl-C (maybe hitting it more than once).
35 35
36 36 If you encounter this kind of situation often, you may want to use the
37 37 Verbose_novars mode instead of the regular Verbose, which avoids formatting
38 38 variables (but otherwise includes the information and context given by
39 39 Verbose).
40 40
41 41 .. note::
42 42
43 43 The verbose mode print all variables in the stack, which means it can
44 44 potentially leak sensitive information like access keys, or unencryted
45 45 password.
46 46
47 47 Installation instructions for VerboseTB::
48 48
49 49 import sys,ultratb
50 50 sys.excepthook = ultratb.VerboseTB()
51 51
52 52 Note: Much of the code in this module was lifted verbatim from the standard
53 53 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
54 54
55 55 Color schemes
56 56 -------------
57 57
58 58 The colors are defined in the class TBTools through the use of the
59 59 ColorSchemeTable class. Currently the following exist:
60 60
61 61 - NoColor: allows all of this module to be used in any terminal (the color
62 62 escapes are just dummy blank strings).
63 63
64 64 - Linux: is meant to look good in a terminal like the Linux console (black
65 65 or very dark background).
66 66
67 67 - LightBG: similar to Linux but swaps dark/light colors to be more readable
68 68 in light background terminals.
69 69
70 70 - Neutral: a neutral color scheme that should be readable on both light and
71 71 dark background
72 72
73 73 You can implement other color schemes easily, the syntax is fairly
74 74 self-explanatory. Please send back new schemes you develop to the author for
75 75 possible inclusion in future releases.
76 76
77 77 Inheritance diagram:
78 78
79 79 .. inheritance-diagram:: IPython.core.ultratb
80 80 :parts: 3
81 81 """
82 82
83 83 #*****************************************************************************
84 84 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
85 85 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
86 86 #
87 87 # Distributed under the terms of the BSD License. The full license is in
88 88 # the file COPYING, distributed as part of this software.
89 89 #*****************************************************************************
90 90
91 91 from __future__ import absolute_import
92 92 from __future__ import unicode_literals
93 93 from __future__ import print_function
94 94
95 95 import dis
96 96 import inspect
97 97 import keyword
98 98 import linecache
99 99 import os
100 100 import pydoc
101 101 import re
102 102 import sys
103 103 import time
104 104 import tokenize
105 105 import traceback
106 106 import types
107 107
108 108 try: # Python 2
109 109 generate_tokens = tokenize.generate_tokens
110 110 except AttributeError: # Python 3
111 111 generate_tokens = tokenize.tokenize
112 112
113 113 # For purposes of monkeypatching inspect to fix a bug in it.
114 114 from inspect import getsourcefile, getfile, getmodule, \
115 115 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
116 116
117 117 # IPython's own modules
118 # Modified pdb which doesn't damage IPython's readline handling
119 118 from IPython import get_ipython
120 119 from IPython.core import debugger
121 120 from IPython.core.display_trap import DisplayTrap
122 121 from IPython.core.excolors import exception_colors
123 122 from IPython.utils import PyColorize
124 123 from IPython.utils import openpy
125 124 from IPython.utils import path as util_path
126 125 from IPython.utils import py3compat
127 126 from IPython.utils import ulinecache
128 127 from IPython.utils.data import uniq_stable
129 128 from IPython.utils.terminal import get_terminal_size
130 129 from logging import info, error
131 130
132 131 import IPython.utils.colorable as colorable
133 132
134 133 # Globals
135 134 # amount of space to put line numbers before verbose tracebacks
136 135 INDENT_SIZE = 8
137 136
138 137 # Default color scheme. This is used, for example, by the traceback
139 138 # formatter. When running in an actual IPython instance, the user's rc.colors
140 139 # value is used, but having a module global makes this functionality available
141 140 # to users of ultratb who are NOT running inside ipython.
142 141 DEFAULT_SCHEME = 'NoColor'
143 142
144 143 # ---------------------------------------------------------------------------
145 144 # Code begins
146 145
147 146 # Utility functions
148 147 def inspect_error():
149 148 """Print a message about internal inspect errors.
150 149
151 150 These are unfortunately quite common."""
152 151
153 152 error('Internal Python error in the inspect module.\n'
154 153 'Below is the traceback from this internal error.\n')
155 154
156 155
157 156 # This function is a monkeypatch we apply to the Python inspect module. We have
158 157 # now found when it's needed (see discussion on issue gh-1456), and we have a
159 158 # test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if
160 159 # the monkeypatch is not applied. TK, Aug 2012.
161 160 def findsource(object):
162 161 """Return the entire source file and starting line number for an object.
163 162
164 163 The argument may be a module, class, method, function, traceback, frame,
165 164 or code object. The source code is returned as a list of all the lines
166 165 in the file and the line number indexes a line in that list. An IOError
167 166 is raised if the source code cannot be retrieved.
168 167
169 168 FIXED version with which we monkeypatch the stdlib to work around a bug."""
170 169
171 170 file = getsourcefile(object) or getfile(object)
172 171 # If the object is a frame, then trying to get the globals dict from its
173 172 # module won't work. Instead, the frame object itself has the globals
174 173 # dictionary.
175 174 globals_dict = None
176 175 if inspect.isframe(object):
177 176 # XXX: can this ever be false?
178 177 globals_dict = object.f_globals
179 178 else:
180 179 module = getmodule(object, file)
181 180 if module:
182 181 globals_dict = module.__dict__
183 182 lines = linecache.getlines(file, globals_dict)
184 183 if not lines:
185 184 raise IOError('could not get source code')
186 185
187 186 if ismodule(object):
188 187 return lines, 0
189 188
190 189 if isclass(object):
191 190 name = object.__name__
192 191 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
193 192 # make some effort to find the best matching class definition:
194 193 # use the one with the least indentation, which is the one
195 194 # that's most probably not inside a function definition.
196 195 candidates = []
197 196 for i in range(len(lines)):
198 197 match = pat.match(lines[i])
199 198 if match:
200 199 # if it's at toplevel, it's already the best one
201 200 if lines[i][0] == 'c':
202 201 return lines, i
203 202 # else add whitespace to candidate list
204 203 candidates.append((match.group(1), i))
205 204 if candidates:
206 205 # this will sort by whitespace, and by line number,
207 206 # less whitespace first
208 207 candidates.sort()
209 208 return lines, candidates[0][1]
210 209 else:
211 210 raise IOError('could not find class definition')
212 211
213 212 if ismethod(object):
214 213 object = object.__func__
215 214 if isfunction(object):
216 215 object = object.__code__
217 216 if istraceback(object):
218 217 object = object.tb_frame
219 218 if isframe(object):
220 219 object = object.f_code
221 220 if iscode(object):
222 221 if not hasattr(object, 'co_firstlineno'):
223 222 raise IOError('could not find function definition')
224 223 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
225 224 pmatch = pat.match
226 225 # fperez - fix: sometimes, co_firstlineno can give a number larger than
227 226 # the length of lines, which causes an error. Safeguard against that.
228 227 lnum = min(object.co_firstlineno, len(lines)) - 1
229 228 while lnum > 0:
230 229 if pmatch(lines[lnum]):
231 230 break
232 231 lnum -= 1
233 232
234 233 return lines, lnum
235 234 raise IOError('could not find code object')
236 235
237 236
238 237 # This is a patched version of inspect.getargs that applies the (unmerged)
239 238 # patch for http://bugs.python.org/issue14611 by Stefano Taschini. This fixes
240 239 # https://github.com/ipython/ipython/issues/8205 and
241 240 # https://github.com/ipython/ipython/issues/8293
242 241 def getargs(co):
243 242 """Get information about the arguments accepted by a code object.
244 243
245 244 Three things are returned: (args, varargs, varkw), where 'args' is
246 245 a list of argument names (possibly containing nested lists), and
247 246 'varargs' and 'varkw' are the names of the * and ** arguments or None."""
248 247 if not iscode(co):
249 248 raise TypeError('{!r} is not a code object'.format(co))
250 249
251 250 nargs = co.co_argcount
252 251 names = co.co_varnames
253 252 args = list(names[:nargs])
254 253 step = 0
255 254
256 255 # The following acrobatics are for anonymous (tuple) arguments.
257 256 for i in range(nargs):
258 257 if args[i][:1] in ('', '.'):
259 258 stack, remain, count = [], [], []
260 259 while step < len(co.co_code):
261 260 op = ord(co.co_code[step])
262 261 step = step + 1
263 262 if op >= dis.HAVE_ARGUMENT:
264 263 opname = dis.opname[op]
265 264 value = ord(co.co_code[step]) + ord(co.co_code[step+1])*256
266 265 step = step + 2
267 266 if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'):
268 267 remain.append(value)
269 268 count.append(value)
270 269 elif opname in ('STORE_FAST', 'STORE_DEREF'):
271 270 if op in dis.haslocal:
272 271 stack.append(co.co_varnames[value])
273 272 elif op in dis.hasfree:
274 273 stack.append((co.co_cellvars + co.co_freevars)[value])
275 274 # Special case for sublists of length 1: def foo((bar))
276 275 # doesn't generate the UNPACK_TUPLE bytecode, so if
277 276 # `remain` is empty here, we have such a sublist.
278 277 if not remain:
279 278 stack[0] = [stack[0]]
280 279 break
281 280 else:
282 281 remain[-1] = remain[-1] - 1
283 282 while remain[-1] == 0:
284 283 remain.pop()
285 284 size = count.pop()
286 285 stack[-size:] = [stack[-size:]]
287 286 if not remain:
288 287 break
289 288 remain[-1] = remain[-1] - 1
290 289 if not remain:
291 290 break
292 291 args[i] = stack[0]
293 292
294 293 varargs = None
295 294 if co.co_flags & inspect.CO_VARARGS:
296 295 varargs = co.co_varnames[nargs]
297 296 nargs = nargs + 1
298 297 varkw = None
299 298 if co.co_flags & inspect.CO_VARKEYWORDS:
300 299 varkw = co.co_varnames[nargs]
301 300 return inspect.Arguments(args, varargs, varkw)
302 301
303 302
304 303 # Monkeypatch inspect to apply our bugfix.
305 304 def with_patch_inspect(f):
306 305 """decorator for monkeypatching inspect.findsource"""
307 306
308 307 def wrapped(*args, **kwargs):
309 308 save_findsource = inspect.findsource
310 309 save_getargs = inspect.getargs
311 310 inspect.findsource = findsource
312 311 inspect.getargs = getargs
313 312 try:
314 313 return f(*args, **kwargs)
315 314 finally:
316 315 inspect.findsource = save_findsource
317 316 inspect.getargs = save_getargs
318 317
319 318 return wrapped
320 319
321 320
322 321 if py3compat.PY3:
323 322 fixed_getargvalues = inspect.getargvalues
324 323 else:
325 324 # Fixes for https://github.com/ipython/ipython/issues/8293
326 325 # and https://github.com/ipython/ipython/issues/8205.
327 326 # The relevant bug is caused by failure to correctly handle anonymous tuple
328 327 # unpacking, which only exists in Python 2.
329 328 fixed_getargvalues = with_patch_inspect(inspect.getargvalues)
330 329
331 330
332 331 def fix_frame_records_filenames(records):
333 332 """Try to fix the filenames in each record from inspect.getinnerframes().
334 333
335 334 Particularly, modules loaded from within zip files have useless filenames
336 335 attached to their code object, and inspect.getinnerframes() just uses it.
337 336 """
338 337 fixed_records = []
339 338 for frame, filename, line_no, func_name, lines, index in records:
340 339 # Look inside the frame's globals dictionary for __file__,
341 340 # which should be better. However, keep Cython filenames since
342 341 # we prefer the source filenames over the compiled .so file.
343 342 filename = py3compat.cast_unicode_py2(filename, "utf-8")
344 343 if not filename.endswith(('.pyx', '.pxd', '.pxi')):
345 344 better_fn = frame.f_globals.get('__file__', None)
346 345 if isinstance(better_fn, str):
347 346 # Check the type just in case someone did something weird with
348 347 # __file__. It might also be None if the error occurred during
349 348 # import.
350 349 filename = better_fn
351 350 fixed_records.append((frame, filename, line_no, func_name, lines, index))
352 351 return fixed_records
353 352
354 353
355 354 @with_patch_inspect
356 355 def _fixed_getinnerframes(etb, context=1, tb_offset=0):
357 356 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
358 357
359 358 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
360 359 # If the error is at the console, don't build any context, since it would
361 360 # otherwise produce 5 blank lines printed out (there is no file at the
362 361 # console)
363 362 rec_check = records[tb_offset:]
364 363 try:
365 364 rname = rec_check[0][1]
366 365 if rname == '<ipython console>' or rname.endswith('<string>'):
367 366 return rec_check
368 367 except IndexError:
369 368 pass
370 369
371 370 aux = traceback.extract_tb(etb)
372 371 assert len(records) == len(aux)
373 372 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
374 373 maybeStart = lnum - 1 - context // 2
375 374 start = max(maybeStart, 0)
376 375 end = start + context
377 376 lines = ulinecache.getlines(file)[start:end]
378 377 buf = list(records[i])
379 378 buf[LNUM_POS] = lnum
380 379 buf[INDEX_POS] = lnum - 1 - start
381 380 buf[LINES_POS] = lines
382 381 records[i] = tuple(buf)
383 382 return records[tb_offset:]
384 383
385 384 # Helper function -- largely belongs to VerboseTB, but we need the same
386 385 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
387 386 # can be recognized properly by ipython.el's py-traceback-line-re
388 387 # (SyntaxErrors have to be treated specially because they have no traceback)
389 388
390 389 _parser = PyColorize.Parser()
391 390
392 391
393 392 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None, scheme=None):
394 393 numbers_width = INDENT_SIZE - 1
395 394 res = []
396 395 i = lnum - index
397 396
398 397 # This lets us get fully syntax-highlighted tracebacks.
399 398 if scheme is None:
400 399 ipinst = get_ipython()
401 400 if ipinst is not None:
402 401 scheme = ipinst.colors
403 402 else:
404 403 scheme = DEFAULT_SCHEME
405 404
406 405 _line_format = _parser.format2
407 406
408 407 for line in lines:
409 408 line = py3compat.cast_unicode(line)
410 409
411 410 new_line, err = _line_format(line, 'str', scheme)
412 411 if not err: line = new_line
413 412
414 413 if i == lnum:
415 414 # This is the line with the error
416 415 pad = numbers_width - len(str(i))
417 416 num = '%s%s' % (debugger.make_arrow(pad), str(lnum))
418 417 line = '%s%s%s %s%s' % (Colors.linenoEm, num,
419 418 Colors.line, line, Colors.Normal)
420 419 else:
421 420 num = '%*s' % (numbers_width, i)
422 421 line = '%s%s%s %s' % (Colors.lineno, num,
423 422 Colors.Normal, line)
424 423
425 424 res.append(line)
426 425 if lvals and i == lnum:
427 426 res.append(lvals + '\n')
428 427 i = i + 1
429 428 return res
430 429
431 430 def is_recursion_error(etype, value, records):
432 431 try:
433 432 # RecursionError is new in Python 3.5
434 433 recursion_error_type = RecursionError
435 434 except NameError:
436 435 recursion_error_type = RuntimeError
437 436
438 437 # The default recursion limit is 1000, but some of that will be taken up
439 438 # by stack frames in IPython itself. >500 frames probably indicates
440 439 # a recursion error.
441 440 return (etype is recursion_error_type) \
442 441 and "recursion" in str(value).lower() \
443 442 and len(records) > 500
444 443
445 444 def find_recursion(etype, value, records):
446 445 """Identify the repeating stack frames from a RecursionError traceback
447 446
448 447 'records' is a list as returned by VerboseTB.get_records()
449 448
450 449 Returns (last_unique, repeat_length)
451 450 """
452 451 # This involves a bit of guesswork - we want to show enough of the traceback
453 452 # to indicate where the recursion is occurring. We guess that the innermost
454 453 # quarter of the traceback (250 frames by default) is repeats, and find the
455 454 # first frame (from in to out) that looks different.
456 455 if not is_recursion_error(etype, value, records):
457 456 return len(records), 0
458 457
459 458 # Select filename, lineno, func_name to track frames with
460 459 records = [r[1:4] for r in records]
461 460 inner_frames = records[-(len(records)//4):]
462 461 frames_repeated = set(inner_frames)
463 462
464 463 last_seen_at = {}
465 464 longest_repeat = 0
466 465 i = len(records)
467 466 for frame in reversed(records):
468 467 i -= 1
469 468 if frame not in frames_repeated:
470 469 last_unique = i
471 470 break
472 471
473 472 if frame in last_seen_at:
474 473 distance = last_seen_at[frame] - i
475 474 longest_repeat = max(longest_repeat, distance)
476 475
477 476 last_seen_at[frame] = i
478 477 else:
479 478 last_unique = 0 # The whole traceback was recursion
480 479
481 480 return last_unique, longest_repeat
482 481
483 482 #---------------------------------------------------------------------------
484 483 # Module classes
485 484 class TBTools(colorable.Colorable):
486 485 """Basic tools used by all traceback printer classes."""
487 486
488 487 # Number of frames to skip when reporting tracebacks
489 488 tb_offset = 0
490 489
491 490 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
492 491 # Whether to call the interactive pdb debugger after printing
493 492 # tracebacks or not
494 493 super(TBTools, self).__init__(parent=parent, config=config)
495 494 self.call_pdb = call_pdb
496 495
497 496 # Output stream to write to. Note that we store the original value in
498 497 # a private attribute and then make the public ostream a property, so
499 498 # that we can delay accessing io.stdout until runtime. The way
500 499 # things are written now, the io.stdout object is dynamically managed
501 500 # so a reference to it should NEVER be stored statically. This
502 501 # property approach confines this detail to a single location, and all
503 502 # subclasses can simply access self.ostream for writing.
504 503 self._ostream = ostream
505 504
506 505 # Create color table
507 506 self.color_scheme_table = exception_colors()
508 507
509 508 self.set_colors(color_scheme)
510 509 self.old_scheme = color_scheme # save initial value for toggles
511 510
512 511 if call_pdb:
513 512 self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name)
514 513 else:
515 514 self.pdb = None
516 515
517 516 def _get_ostream(self):
518 517 """Output stream that exceptions are written to.
519 518
520 519 Valid values are:
521 520
522 521 - None: the default, which means that IPython will dynamically resolve
523 522 to io.stdout. This ensures compatibility with most tools, including
524 523 Windows (where plain stdout doesn't recognize ANSI escapes).
525 524
526 525 - Any object with 'write' and 'flush' attributes.
527 526 """
528 527 return sys.stdout if self._ostream is None else self._ostream
529 528
530 529 def _set_ostream(self, val):
531 530 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
532 531 self._ostream = val
533 532
534 533 ostream = property(_get_ostream, _set_ostream)
535 534
536 535 def set_colors(self, *args, **kw):
537 536 """Shorthand access to the color table scheme selector method."""
538 537
539 538 # Set own color table
540 539 self.color_scheme_table.set_active_scheme(*args, **kw)
541 540 # for convenience, set Colors to the active scheme
542 541 self.Colors = self.color_scheme_table.active_colors
543 542 # Also set colors of debugger
544 543 if hasattr(self, 'pdb') and self.pdb is not None:
545 544 self.pdb.set_colors(*args, **kw)
546 545
547 546 def color_toggle(self):
548 547 """Toggle between the currently active color scheme and NoColor."""
549 548
550 549 if self.color_scheme_table.active_scheme_name == 'NoColor':
551 550 self.color_scheme_table.set_active_scheme(self.old_scheme)
552 551 self.Colors = self.color_scheme_table.active_colors
553 552 else:
554 553 self.old_scheme = self.color_scheme_table.active_scheme_name
555 554 self.color_scheme_table.set_active_scheme('NoColor')
556 555 self.Colors = self.color_scheme_table.active_colors
557 556
558 557 def stb2text(self, stb):
559 558 """Convert a structured traceback (a list) to a string."""
560 559 return '\n'.join(stb)
561 560
562 561 def text(self, etype, value, tb, tb_offset=None, context=5):
563 562 """Return formatted traceback.
564 563
565 564 Subclasses may override this if they add extra arguments.
566 565 """
567 566 tb_list = self.structured_traceback(etype, value, tb,
568 567 tb_offset, context)
569 568 return self.stb2text(tb_list)
570 569
571 570 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
572 571 context=5, mode=None):
573 572 """Return a list of traceback frames.
574 573
575 574 Must be implemented by each class.
576 575 """
577 576 raise NotImplementedError()
578 577
579 578
580 579 #---------------------------------------------------------------------------
581 580 class ListTB(TBTools):
582 581 """Print traceback information from a traceback list, with optional color.
583 582
584 583 Calling requires 3 arguments: (etype, evalue, elist)
585 584 as would be obtained by::
586 585
587 586 etype, evalue, tb = sys.exc_info()
588 587 if tb:
589 588 elist = traceback.extract_tb(tb)
590 589 else:
591 590 elist = None
592 591
593 592 It can thus be used by programs which need to process the traceback before
594 593 printing (such as console replacements based on the code module from the
595 594 standard library).
596 595
597 596 Because they are meant to be called without a full traceback (only a
598 597 list), instances of this class can't call the interactive pdb debugger."""
599 598
600 599 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None):
601 600 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
602 601 ostream=ostream, parent=parent)
603 602
604 603 def __call__(self, etype, value, elist):
605 604 self.ostream.flush()
606 605 self.ostream.write(self.text(etype, value, elist))
607 606 self.ostream.write('\n')
608 607
609 608 def structured_traceback(self, etype, value, elist, tb_offset=None,
610 609 context=5):
611 610 """Return a color formatted string with the traceback info.
612 611
613 612 Parameters
614 613 ----------
615 614 etype : exception type
616 615 Type of the exception raised.
617 616
618 617 value : object
619 618 Data stored in the exception
620 619
621 620 elist : list
622 621 List of frames, see class docstring for details.
623 622
624 623 tb_offset : int, optional
625 624 Number of frames in the traceback to skip. If not given, the
626 625 instance value is used (set in constructor).
627 626
628 627 context : int, optional
629 628 Number of lines of context information to print.
630 629
631 630 Returns
632 631 -------
633 632 String with formatted exception.
634 633 """
635 634 tb_offset = self.tb_offset if tb_offset is None else tb_offset
636 635 Colors = self.Colors
637 636 out_list = []
638 637 if elist:
639 638
640 639 if tb_offset and len(elist) > tb_offset:
641 640 elist = elist[tb_offset:]
642 641
643 642 out_list.append('Traceback %s(most recent call last)%s:' %
644 643 (Colors.normalEm, Colors.Normal) + '\n')
645 644 out_list.extend(self._format_list(elist))
646 645 # The exception info should be a single entry in the list.
647 646 lines = ''.join(self._format_exception_only(etype, value))
648 647 out_list.append(lines)
649 648
650 649 # Note: this code originally read:
651 650
652 651 ## for line in lines[:-1]:
653 652 ## out_list.append(" "+line)
654 653 ## out_list.append(lines[-1])
655 654
656 655 # This means it was indenting everything but the last line by a little
657 656 # bit. I've disabled this for now, but if we see ugliness somewhere we
658 657 # can restore it.
659 658
660 659 return out_list
661 660
662 661 def _format_list(self, extracted_list):
663 662 """Format a list of traceback entry tuples for printing.
664 663
665 664 Given a list of tuples as returned by extract_tb() or
666 665 extract_stack(), return a list of strings ready for printing.
667 666 Each string in the resulting list corresponds to the item with the
668 667 same index in the argument list. Each string ends in a newline;
669 668 the strings may contain internal newlines as well, for those items
670 669 whose source text line is not None.
671 670
672 671 Lifted almost verbatim from traceback.py
673 672 """
674 673
675 674 Colors = self.Colors
676 675 list = []
677 676 for filename, lineno, name, line in extracted_list[:-1]:
678 677 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
679 678 (Colors.filename, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.Normal,
680 679 Colors.lineno, lineno, Colors.Normal,
681 680 Colors.name, py3compat.cast_unicode_py2(name, "utf-8"), Colors.Normal)
682 681 if line:
683 682 item += ' %s\n' % line.strip()
684 683 list.append(item)
685 684 # Emphasize the last entry
686 685 filename, lineno, name, line = extracted_list[-1]
687 686 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
688 687 (Colors.normalEm,
689 688 Colors.filenameEm, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.normalEm,
690 689 Colors.linenoEm, lineno, Colors.normalEm,
691 690 Colors.nameEm, py3compat.cast_unicode_py2(name, "utf-8"), Colors.normalEm,
692 691 Colors.Normal)
693 692 if line:
694 693 item += '%s %s%s\n' % (Colors.line, line.strip(),
695 694 Colors.Normal)
696 695 list.append(item)
697 696 return list
698 697
699 698 def _format_exception_only(self, etype, value):
700 699 """Format the exception part of a traceback.
701 700
702 701 The arguments are the exception type and value such as given by
703 702 sys.exc_info()[:2]. The return value is a list of strings, each ending
704 703 in a newline. Normally, the list contains a single string; however,
705 704 for SyntaxError exceptions, it contains several lines that (when
706 705 printed) display detailed information about where the syntax error
707 706 occurred. The message indicating which exception occurred is the
708 707 always last string in the list.
709 708
710 709 Also lifted nearly verbatim from traceback.py
711 710 """
712 711 have_filedata = False
713 712 Colors = self.Colors
714 713 list = []
715 714 stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
716 715 if value is None:
717 716 # Not sure if this can still happen in Python 2.6 and above
718 717 list.append(stype + '\n')
719 718 else:
720 719 if issubclass(etype, SyntaxError):
721 720 have_filedata = True
722 721 if not value.filename: value.filename = "<string>"
723 722 if value.lineno:
724 723 lineno = value.lineno
725 724 textline = ulinecache.getline(value.filename, value.lineno)
726 725 else:
727 726 lineno = 'unknown'
728 727 textline = ''
729 728 list.append('%s File %s"%s"%s, line %s%s%s\n' % \
730 729 (Colors.normalEm,
731 730 Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm,
732 731 Colors.linenoEm, lineno, Colors.Normal ))
733 732 if textline == '':
734 733 textline = py3compat.cast_unicode(value.text, "utf-8")
735 734
736 735 if textline is not None:
737 736 i = 0
738 737 while i < len(textline) and textline[i].isspace():
739 738 i += 1
740 739 list.append('%s %s%s\n' % (Colors.line,
741 740 textline.strip(),
742 741 Colors.Normal))
743 742 if value.offset is not None:
744 743 s = ' '
745 744 for c in textline[i:value.offset - 1]:
746 745 if c.isspace():
747 746 s += c
748 747 else:
749 748 s += ' '
750 749 list.append('%s%s^%s\n' % (Colors.caret, s,
751 750 Colors.Normal))
752 751
753 752 try:
754 753 s = value.msg
755 754 except Exception:
756 755 s = self._some_str(value)
757 756 if s:
758 757 list.append('%s%s:%s %s\n' % (stype, Colors.excName,
759 758 Colors.Normal, s))
760 759 else:
761 760 list.append('%s\n' % stype)
762 761
763 762 # sync with user hooks
764 763 if have_filedata:
765 764 ipinst = get_ipython()
766 765 if ipinst is not None:
767 766 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
768 767
769 768 return list
770 769
771 770 def get_exception_only(self, etype, value):
772 771 """Only print the exception type and message, without a traceback.
773 772
774 773 Parameters
775 774 ----------
776 775 etype : exception type
777 776 value : exception value
778 777 """
779 778 return ListTB.structured_traceback(self, etype, value, [])
780 779
781 780 def show_exception_only(self, etype, evalue):
782 781 """Only print the exception type and message, without a traceback.
783 782
784 783 Parameters
785 784 ----------
786 785 etype : exception type
787 786 value : exception value
788 787 """
789 788 # This method needs to use __call__ from *this* class, not the one from
790 789 # a subclass whose signature or behavior may be different
791 790 ostream = self.ostream
792 791 ostream.flush()
793 792 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
794 793 ostream.flush()
795 794
796 795 def _some_str(self, value):
797 796 # Lifted from traceback.py
798 797 try:
799 798 return py3compat.cast_unicode(str(value))
800 799 except:
801 800 return u'<unprintable %s object>' % type(value).__name__
802 801
803 802
804 803 #----------------------------------------------------------------------------
805 804 class VerboseTB(TBTools):
806 805 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
807 806 of HTML. Requires inspect and pydoc. Crazy, man.
808 807
809 808 Modified version which optionally strips the topmost entries from the
810 809 traceback, to be used with alternate interpreters (because their own code
811 810 would appear in the traceback)."""
812 811
813 812 def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None,
814 813 tb_offset=0, long_header=False, include_vars=True,
815 814 check_cache=None, debugger_cls = None):
816 815 """Specify traceback offset, headers and color scheme.
817 816
818 817 Define how many frames to drop from the tracebacks. Calling it with
819 818 tb_offset=1 allows use of this handler in interpreters which will have
820 819 their own code at the top of the traceback (VerboseTB will first
821 820 remove that frame before printing the traceback info)."""
822 821 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
823 822 ostream=ostream)
824 823 self.tb_offset = tb_offset
825 824 self.long_header = long_header
826 825 self.include_vars = include_vars
827 826 # By default we use linecache.checkcache, but the user can provide a
828 827 # different check_cache implementation. This is used by the IPython
829 828 # kernel to provide tracebacks for interactive code that is cached,
830 829 # by a compiler instance that flushes the linecache but preserves its
831 830 # own code cache.
832 831 if check_cache is None:
833 832 check_cache = linecache.checkcache
834 833 self.check_cache = check_cache
835 834
836 835 self.debugger_cls = debugger_cls or debugger.Pdb
837 836
838 837 def format_records(self, records, last_unique, recursion_repeat):
839 838 """Format the stack frames of the traceback"""
840 839 frames = []
841 840 for r in records[:last_unique+recursion_repeat+1]:
842 841 #print '*** record:',file,lnum,func,lines,index # dbg
843 842 frames.append(self.format_record(*r))
844 843
845 844 if recursion_repeat:
846 845 frames.append('... last %d frames repeated, from the frame below ...\n' % recursion_repeat)
847 846 frames.append(self.format_record(*records[last_unique+recursion_repeat+1]))
848 847
849 848 return frames
850 849
851 850 def format_record(self, frame, file, lnum, func, lines, index):
852 851 """Format a single stack frame"""
853 852 Colors = self.Colors # just a shorthand + quicker name lookup
854 853 ColorsNormal = Colors.Normal # used a lot
855 854 col_scheme = self.color_scheme_table.active_scheme_name
856 855 indent = ' ' * INDENT_SIZE
857 856 em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal)
858 857 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
859 858 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
860 859 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
861 860 ColorsNormal)
862 861 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
863 862 (Colors.vName, Colors.valEm, ColorsNormal)
864 863 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
865 864 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
866 865 Colors.vName, ColorsNormal)
867 866 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
868 867
869 868 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
870 869 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm, Colors.line,
871 870 ColorsNormal)
872 871
873 872 abspath = os.path.abspath
874 873
875 874
876 875 if not file:
877 876 file = '?'
878 877 elif file.startswith(str("<")) and file.endswith(str(">")):
879 878 # Not a real filename, no problem...
880 879 pass
881 880 elif not os.path.isabs(file):
882 881 # Try to make the filename absolute by trying all
883 882 # sys.path entries (which is also what linecache does)
884 883 for dirname in sys.path:
885 884 try:
886 885 fullname = os.path.join(dirname, file)
887 886 if os.path.isfile(fullname):
888 887 file = os.path.abspath(fullname)
889 888 break
890 889 except Exception:
891 890 # Just in case that sys.path contains very
892 891 # strange entries...
893 892 pass
894 893
895 894 file = py3compat.cast_unicode(file, util_path.fs_encoding)
896 895 link = tpl_link % file
897 896 args, varargs, varkw, locals = fixed_getargvalues(frame)
898 897
899 898 if func == '?':
900 899 call = ''
901 900 else:
902 901 # Decide whether to include variable details or not
903 902 var_repr = self.include_vars and eqrepr or nullrepr
904 903 try:
905 904 call = tpl_call % (func, inspect.formatargvalues(args,
906 905 varargs, varkw,
907 906 locals, formatvalue=var_repr))
908 907 except KeyError:
909 908 # This happens in situations like errors inside generator
910 909 # expressions, where local variables are listed in the
911 910 # line, but can't be extracted from the frame. I'm not
912 911 # 100% sure this isn't actually a bug in inspect itself,
913 912 # but since there's no info for us to compute with, the
914 913 # best we can do is report the failure and move on. Here
915 914 # we must *not* call any traceback construction again,
916 915 # because that would mess up use of %debug later on. So we
917 916 # simply report the failure and move on. The only
918 917 # limitation will be that this frame won't have locals
919 918 # listed in the call signature. Quite subtle problem...
920 919 # I can't think of a good way to validate this in a unit
921 920 # test, but running a script consisting of:
922 921 # dict( (k,v.strip()) for (k,v) in range(10) )
923 922 # will illustrate the error, if this exception catch is
924 923 # disabled.
925 924 call = tpl_call_fail % func
926 925
927 926 # Don't attempt to tokenize binary files.
928 927 if file.endswith(('.so', '.pyd', '.dll')):
929 928 return '%s %s\n' % (link, call)
930 929
931 930 elif file.endswith(('.pyc', '.pyo')):
932 931 # Look up the corresponding source file.
933 932 try:
934 933 file = openpy.source_from_cache(file)
935 934 except ValueError:
936 935 # Failed to get the source file for some reason
937 936 # E.g. https://github.com/ipython/ipython/issues/9486
938 937 return '%s %s\n' % (link, call)
939 938
940 939 def linereader(file=file, lnum=[lnum], getline=ulinecache.getline):
941 940 line = getline(file, lnum[0])
942 941 lnum[0] += 1
943 942 return line
944 943
945 944 # Build the list of names on this line of code where the exception
946 945 # occurred.
947 946 try:
948 947 names = []
949 948 name_cont = False
950 949
951 950 for token_type, token, start, end, line in generate_tokens(linereader):
952 951 # build composite names
953 952 if token_type == tokenize.NAME and token not in keyword.kwlist:
954 953 if name_cont:
955 954 # Continuation of a dotted name
956 955 try:
957 956 names[-1].append(token)
958 957 except IndexError:
959 958 names.append([token])
960 959 name_cont = False
961 960 else:
962 961 # Regular new names. We append everything, the caller
963 962 # will be responsible for pruning the list later. It's
964 963 # very tricky to try to prune as we go, b/c composite
965 964 # names can fool us. The pruning at the end is easy
966 965 # to do (or the caller can print a list with repeated
967 966 # names if so desired.
968 967 names.append([token])
969 968 elif token == '.':
970 969 name_cont = True
971 970 elif token_type == tokenize.NEWLINE:
972 971 break
973 972
974 973 except (IndexError, UnicodeDecodeError, SyntaxError):
975 974 # signals exit of tokenizer
976 975 # SyntaxError can occur if the file is not actually Python
977 976 # - see gh-6300
978 977 pass
979 978 except tokenize.TokenError as msg:
980 979 _m = ("An unexpected error occurred while tokenizing input\n"
981 980 "The following traceback may be corrupted or invalid\n"
982 981 "The error message is: %s\n" % msg)
983 982 error(_m)
984 983
985 984 # Join composite names (e.g. "dict.fromkeys")
986 985 names = ['.'.join(n) for n in names]
987 986 # prune names list of duplicates, but keep the right order
988 987 unique_names = uniq_stable(names)
989 988
990 989 # Start loop over vars
991 990 lvals = []
992 991 if self.include_vars:
993 992 for name_full in unique_names:
994 993 name_base = name_full.split('.', 1)[0]
995 994 if name_base in frame.f_code.co_varnames:
996 995 if name_base in locals:
997 996 try:
998 997 value = repr(eval(name_full, locals))
999 998 except:
1000 999 value = undefined
1001 1000 else:
1002 1001 value = undefined
1003 1002 name = tpl_local_var % name_full
1004 1003 else:
1005 1004 if name_base in frame.f_globals:
1006 1005 try:
1007 1006 value = repr(eval(name_full, frame.f_globals))
1008 1007 except:
1009 1008 value = undefined
1010 1009 else:
1011 1010 value = undefined
1012 1011 name = tpl_global_var % name_full
1013 1012 lvals.append(tpl_name_val % (name, value))
1014 1013 if lvals:
1015 1014 lvals = '%s%s' % (indent, em_normal.join(lvals))
1016 1015 else:
1017 1016 lvals = ''
1018 1017
1019 1018 level = '%s %s\n' % (link, call)
1020 1019
1021 1020 if index is None:
1022 1021 return level
1023 1022 else:
1024 1023 return '%s%s' % (level, ''.join(
1025 1024 _format_traceback_lines(lnum, index, lines, Colors, lvals,
1026 1025 col_scheme)))
1027 1026
1028 1027 def prepare_chained_exception_message(self, cause):
1029 1028 direct_cause = "\nThe above exception was the direct cause of the following exception:\n"
1030 1029 exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n"
1031 1030
1032 1031 if cause:
1033 1032 message = [[direct_cause]]
1034 1033 else:
1035 1034 message = [[exception_during_handling]]
1036 1035 return message
1037 1036
1038 1037 def prepare_header(self, etype, long_version=False):
1039 1038 colors = self.Colors # just a shorthand + quicker name lookup
1040 1039 colorsnormal = colors.Normal # used a lot
1041 1040 exc = '%s%s%s' % (colors.excName, etype, colorsnormal)
1042 1041 width = min(75, get_terminal_size()[0])
1043 1042 if long_version:
1044 1043 # Header with the exception type, python version, and date
1045 1044 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
1046 1045 date = time.ctime(time.time())
1047 1046
1048 1047 head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal,
1049 1048 exc, ' ' * (width - len(str(etype)) - len(pyver)),
1050 1049 pyver, date.rjust(width) )
1051 1050 head += "\nA problem occurred executing Python code. Here is the sequence of function" \
1052 1051 "\ncalls leading up to the error, with the most recent (innermost) call last."
1053 1052 else:
1054 1053 # Simplified header
1055 1054 head = '%s%s' % (exc, 'Traceback (most recent call last)'. \
1056 1055 rjust(width - len(str(etype))) )
1057 1056
1058 1057 return head
1059 1058
1060 1059 def format_exception(self, etype, evalue):
1061 1060 colors = self.Colors # just a shorthand + quicker name lookup
1062 1061 colorsnormal = colors.Normal # used a lot
1063 1062 indent = ' ' * INDENT_SIZE
1064 1063 # Get (safely) a string form of the exception info
1065 1064 try:
1066 1065 etype_str, evalue_str = map(str, (etype, evalue))
1067 1066 except:
1068 1067 # User exception is improperly defined.
1069 1068 etype, evalue = str, sys.exc_info()[:2]
1070 1069 etype_str, evalue_str = map(str, (etype, evalue))
1071 1070 # ... and format it
1072 1071 exception = ['%s%s%s: %s' % (colors.excName, etype_str,
1073 1072 colorsnormal, py3compat.cast_unicode(evalue_str))]
1074 1073
1075 1074 if (not py3compat.PY3) and type(evalue) is types.InstanceType:
1076 1075 try:
1077 1076 names = [w for w in dir(evalue) if isinstance(w, py3compat.string_types)]
1078 1077 except:
1079 1078 # Every now and then, an object with funny internals blows up
1080 1079 # when dir() is called on it. We do the best we can to report
1081 1080 # the problem and continue
1082 1081 _m = '%sException reporting error (object with broken dir())%s:'
1083 1082 exception.append(_m % (colors.excName, colorsnormal))
1084 1083 etype_str, evalue_str = map(str, sys.exc_info()[:2])
1085 1084 exception.append('%s%s%s: %s' % (colors.excName, etype_str,
1086 1085 colorsnormal, py3compat.cast_unicode(evalue_str)))
1087 1086 names = []
1088 1087 for name in names:
1089 1088 value = text_repr(getattr(evalue, name))
1090 1089 exception.append('\n%s%s = %s' % (indent, name, value))
1091 1090
1092 1091 return exception
1093 1092
1094 1093 def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset):
1095 1094 """Formats the header, traceback and exception message for a single exception.
1096 1095
1097 1096 This may be called multiple times by Python 3 exception chaining
1098 1097 (PEP 3134).
1099 1098 """
1100 1099 # some locals
1101 1100 orig_etype = etype
1102 1101 try:
1103 1102 etype = etype.__name__
1104 1103 except AttributeError:
1105 1104 pass
1106 1105
1107 1106 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1108 1107 head = self.prepare_header(etype, self.long_header)
1109 1108 records = self.get_records(etb, number_of_lines_of_context, tb_offset)
1110 1109
1111 1110 if records is None:
1112 1111 return ""
1113 1112
1114 1113 last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records)
1115 1114
1116 1115 frames = self.format_records(records, last_unique, recursion_repeat)
1117 1116
1118 1117 formatted_exception = self.format_exception(etype, evalue)
1119 1118 if records:
1120 1119 filepath, lnum = records[-1][1:3]
1121 1120 filepath = os.path.abspath(filepath)
1122 1121 ipinst = get_ipython()
1123 1122 if ipinst is not None:
1124 1123 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
1125 1124
1126 1125 return [[head] + frames + [''.join(formatted_exception[0])]]
1127 1126
1128 1127 def get_records(self, etb, number_of_lines_of_context, tb_offset):
1129 1128 try:
1130 1129 # Try the default getinnerframes and Alex's: Alex's fixes some
1131 1130 # problems, but it generates empty tracebacks for console errors
1132 1131 # (5 blanks lines) where none should be returned.
1133 1132 return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
1134 1133 except:
1135 1134 # FIXME: I've been getting many crash reports from python 2.3
1136 1135 # users, traceable to inspect.py. If I can find a small test-case
1137 1136 # to reproduce this, I should either write a better workaround or
1138 1137 # file a bug report against inspect (if that's the real problem).
1139 1138 # So far, I haven't been able to find an isolated example to
1140 1139 # reproduce the problem.
1141 1140 inspect_error()
1142 1141 traceback.print_exc(file=self.ostream)
1143 1142 info('\nUnfortunately, your original traceback can not be constructed.\n')
1144 1143 return None
1145 1144
1146 1145 def get_parts_of_chained_exception(self, evalue):
1147 1146 def get_chained_exception(exception_value):
1148 1147 cause = getattr(exception_value, '__cause__', None)
1149 1148 if cause:
1150 1149 return cause
1151 1150 if getattr(exception_value, '__suppress_context__', False):
1152 1151 return None
1153 1152 return getattr(exception_value, '__context__', None)
1154 1153
1155 1154 chained_evalue = get_chained_exception(evalue)
1156 1155
1157 1156 if chained_evalue:
1158 1157 return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__
1159 1158
1160 1159 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
1161 1160 number_of_lines_of_context=5):
1162 1161 """Return a nice text document describing the traceback."""
1163 1162
1164 1163 formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
1165 1164 tb_offset)
1166 1165
1167 1166 colors = self.Colors # just a shorthand + quicker name lookup
1168 1167 colorsnormal = colors.Normal # used a lot
1169 1168 head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
1170 1169 structured_traceback_parts = [head]
1171 1170 if py3compat.PY3:
1172 1171 chained_exceptions_tb_offset = 0
1173 1172 lines_of_context = 3
1174 1173 formatted_exceptions = formatted_exception
1175 1174 exception = self.get_parts_of_chained_exception(evalue)
1176 1175 if exception:
1177 1176 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1178 1177 etype, evalue, etb = exception
1179 1178 else:
1180 1179 evalue = None
1181 1180 chained_exc_ids = set()
1182 1181 while evalue:
1183 1182 formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
1184 1183 chained_exceptions_tb_offset)
1185 1184 exception = self.get_parts_of_chained_exception(evalue)
1186 1185
1187 1186 if exception and not id(exception[1]) in chained_exc_ids:
1188 1187 chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop
1189 1188 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1190 1189 etype, evalue, etb = exception
1191 1190 else:
1192 1191 evalue = None
1193 1192
1194 1193 # we want to see exceptions in a reversed order:
1195 1194 # the first exception should be on top
1196 1195 for formatted_exception in reversed(formatted_exceptions):
1197 1196 structured_traceback_parts += formatted_exception
1198 1197 else:
1199 1198 structured_traceback_parts += formatted_exception[0]
1200 1199
1201 1200 return structured_traceback_parts
1202 1201
1203 1202 def debugger(self, force=False):
1204 1203 """Call up the pdb debugger if desired, always clean up the tb
1205 1204 reference.
1206 1205
1207 1206 Keywords:
1208 1207
1209 1208 - force(False): by default, this routine checks the instance call_pdb
1210 1209 flag and does not actually invoke the debugger if the flag is false.
1211 1210 The 'force' option forces the debugger to activate even if the flag
1212 1211 is false.
1213 1212
1214 1213 If the call_pdb flag is set, the pdb interactive debugger is
1215 1214 invoked. In all cases, the self.tb reference to the current traceback
1216 1215 is deleted to prevent lingering references which hamper memory
1217 1216 management.
1218 1217
1219 1218 Note that each call to pdb() does an 'import readline', so if your app
1220 1219 requires a special setup for the readline completers, you'll have to
1221 1220 fix that by hand after invoking the exception handler."""
1222 1221
1223 1222 if force or self.call_pdb:
1224 1223 if self.pdb is None:
1225 1224 self.pdb = self.debugger_cls(
1226 1225 self.color_scheme_table.active_scheme_name)
1227 1226 # the system displayhook may have changed, restore the original
1228 1227 # for pdb
1229 1228 display_trap = DisplayTrap(hook=sys.__displayhook__)
1230 1229 with display_trap:
1231 1230 self.pdb.reset()
1232 1231 # Find the right frame so we don't pop up inside ipython itself
1233 1232 if hasattr(self, 'tb') and self.tb is not None:
1234 1233 etb = self.tb
1235 1234 else:
1236 1235 etb = self.tb = sys.last_traceback
1237 1236 while self.tb is not None and self.tb.tb_next is not None:
1238 1237 self.tb = self.tb.tb_next
1239 1238 if etb and etb.tb_next:
1240 1239 etb = etb.tb_next
1241 1240 self.pdb.botframe = etb.tb_frame
1242 1241 self.pdb.interaction(self.tb.tb_frame, self.tb)
1243 1242
1244 1243 if hasattr(self, 'tb'):
1245 1244 del self.tb
1246 1245
1247 1246 def handler(self, info=None):
1248 1247 (etype, evalue, etb) = info or sys.exc_info()
1249 1248 self.tb = etb
1250 1249 ostream = self.ostream
1251 1250 ostream.flush()
1252 1251 ostream.write(self.text(etype, evalue, etb))
1253 1252 ostream.write('\n')
1254 1253 ostream.flush()
1255 1254
1256 1255 # Changed so an instance can just be called as VerboseTB_inst() and print
1257 1256 # out the right info on its own.
1258 1257 def __call__(self, etype=None, evalue=None, etb=None):
1259 1258 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1260 1259 if etb is None:
1261 1260 self.handler()
1262 1261 else:
1263 1262 self.handler((etype, evalue, etb))
1264 1263 try:
1265 1264 self.debugger()
1266 1265 except KeyboardInterrupt:
1267 1266 print("\nKeyboardInterrupt")
1268 1267
1269 1268
1270 1269 #----------------------------------------------------------------------------
1271 1270 class FormattedTB(VerboseTB, ListTB):
1272 1271 """Subclass ListTB but allow calling with a traceback.
1273 1272
1274 1273 It can thus be used as a sys.excepthook for Python > 2.1.
1275 1274
1276 1275 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1277 1276
1278 1277 Allows a tb_offset to be specified. This is useful for situations where
1279 1278 one needs to remove a number of topmost frames from the traceback (such as
1280 1279 occurs with python programs that themselves execute other python code,
1281 1280 like Python shells). """
1282 1281
1283 1282 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1284 1283 ostream=None,
1285 1284 tb_offset=0, long_header=False, include_vars=False,
1286 1285 check_cache=None, debugger_cls=None):
1287 1286
1288 1287 # NEVER change the order of this list. Put new modes at the end:
1289 1288 self.valid_modes = ['Plain', 'Context', 'Verbose']
1290 1289 self.verbose_modes = self.valid_modes[1:3]
1291 1290
1292 1291 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1293 1292 ostream=ostream, tb_offset=tb_offset,
1294 1293 long_header=long_header, include_vars=include_vars,
1295 1294 check_cache=check_cache, debugger_cls=debugger_cls)
1296 1295
1297 1296 # Different types of tracebacks are joined with different separators to
1298 1297 # form a single string. They are taken from this dict
1299 1298 self._join_chars = dict(Plain='', Context='\n', Verbose='\n')
1300 1299 # set_mode also sets the tb_join_char attribute
1301 1300 self.set_mode(mode)
1302 1301
1303 1302 def _extract_tb(self, tb):
1304 1303 if tb:
1305 1304 return traceback.extract_tb(tb)
1306 1305 else:
1307 1306 return None
1308 1307
1309 1308 def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5):
1310 1309 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1311 1310 mode = self.mode
1312 1311 if mode in self.verbose_modes:
1313 1312 # Verbose modes need a full traceback
1314 1313 return VerboseTB.structured_traceback(
1315 1314 self, etype, value, tb, tb_offset, number_of_lines_of_context
1316 1315 )
1317 1316 else:
1318 1317 # We must check the source cache because otherwise we can print
1319 1318 # out-of-date source code.
1320 1319 self.check_cache()
1321 1320 # Now we can extract and format the exception
1322 1321 elist = self._extract_tb(tb)
1323 1322 return ListTB.structured_traceback(
1324 1323 self, etype, value, elist, tb_offset, number_of_lines_of_context
1325 1324 )
1326 1325
1327 1326 def stb2text(self, stb):
1328 1327 """Convert a structured traceback (a list) to a string."""
1329 1328 return self.tb_join_char.join(stb)
1330 1329
1331 1330
1332 1331 def set_mode(self, mode=None):
1333 1332 """Switch to the desired mode.
1334 1333
1335 1334 If mode is not specified, cycles through the available modes."""
1336 1335
1337 1336 if not mode:
1338 1337 new_idx = (self.valid_modes.index(self.mode) + 1 ) % \
1339 1338 len(self.valid_modes)
1340 1339 self.mode = self.valid_modes[new_idx]
1341 1340 elif mode not in self.valid_modes:
1342 1341 raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n'
1343 1342 'Valid modes: ' + str(self.valid_modes))
1344 1343 else:
1345 1344 self.mode = mode
1346 1345 # include variable details only in 'Verbose' mode
1347 1346 self.include_vars = (self.mode == self.valid_modes[2])
1348 1347 # Set the join character for generating text tracebacks
1349 1348 self.tb_join_char = self._join_chars[self.mode]
1350 1349
1351 1350 # some convenient shortcuts
1352 1351 def plain(self):
1353 1352 self.set_mode(self.valid_modes[0])
1354 1353
1355 1354 def context(self):
1356 1355 self.set_mode(self.valid_modes[1])
1357 1356
1358 1357 def verbose(self):
1359 1358 self.set_mode(self.valid_modes[2])
1360 1359
1361 1360
1362 1361 #----------------------------------------------------------------------------
1363 1362 class AutoFormattedTB(FormattedTB):
1364 1363 """A traceback printer which can be called on the fly.
1365 1364
1366 1365 It will find out about exceptions by itself.
1367 1366
1368 1367 A brief example::
1369 1368
1370 1369 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1371 1370 try:
1372 1371 ...
1373 1372 except:
1374 1373 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1375 1374 """
1376 1375
1377 1376 def __call__(self, etype=None, evalue=None, etb=None,
1378 1377 out=None, tb_offset=None):
1379 1378 """Print out a formatted exception traceback.
1380 1379
1381 1380 Optional arguments:
1382 1381 - out: an open file-like object to direct output to.
1383 1382
1384 1383 - tb_offset: the number of frames to skip over in the stack, on a
1385 1384 per-call basis (this overrides temporarily the instance's tb_offset
1386 1385 given at initialization time. """
1387 1386
1388 1387 if out is None:
1389 1388 out = self.ostream
1390 1389 out.flush()
1391 1390 out.write(self.text(etype, evalue, etb, tb_offset))
1392 1391 out.write('\n')
1393 1392 out.flush()
1394 1393 # FIXME: we should remove the auto pdb behavior from here and leave
1395 1394 # that to the clients.
1396 1395 try:
1397 1396 self.debugger()
1398 1397 except KeyboardInterrupt:
1399 1398 print("\nKeyboardInterrupt")
1400 1399
1401 1400 def structured_traceback(self, etype=None, value=None, tb=None,
1402 1401 tb_offset=None, number_of_lines_of_context=5):
1403 1402 if etype is None:
1404 1403 etype, value, tb = sys.exc_info()
1405 1404 self.tb = tb
1406 1405 return FormattedTB.structured_traceback(
1407 1406 self, etype, value, tb, tb_offset, number_of_lines_of_context)
1408 1407
1409 1408
1410 1409 #---------------------------------------------------------------------------
1411 1410
1412 1411 # A simple class to preserve Nathan's original functionality.
1413 1412 class ColorTB(FormattedTB):
1414 1413 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1415 1414
1416 1415 def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs):
1417 1416 FormattedTB.__init__(self, color_scheme=color_scheme,
1418 1417 call_pdb=call_pdb, **kwargs)
1419 1418
1420 1419
1421 1420 class SyntaxTB(ListTB):
1422 1421 """Extension which holds some state: the last exception value"""
1423 1422
1424 1423 def __init__(self, color_scheme='NoColor'):
1425 1424 ListTB.__init__(self, color_scheme)
1426 1425 self.last_syntax_error = None
1427 1426
1428 1427 def __call__(self, etype, value, elist):
1429 1428 self.last_syntax_error = value
1430 1429
1431 1430 ListTB.__call__(self, etype, value, elist)
1432 1431
1433 1432 def structured_traceback(self, etype, value, elist, tb_offset=None,
1434 1433 context=5):
1435 1434 # If the source file has been edited, the line in the syntax error can
1436 1435 # be wrong (retrieved from an outdated cache). This replaces it with
1437 1436 # the current value.
1438 1437 if isinstance(value, SyntaxError) \
1439 1438 and isinstance(value.filename, py3compat.string_types) \
1440 1439 and isinstance(value.lineno, int):
1441 1440 linecache.checkcache(value.filename)
1442 1441 newtext = ulinecache.getline(value.filename, value.lineno)
1443 1442 if newtext:
1444 1443 value.text = newtext
1445 1444 self.last_syntax_error = value
1446 1445 return super(SyntaxTB, self).structured_traceback(etype, value, elist,
1447 1446 tb_offset=tb_offset, context=context)
1448 1447
1449 1448 def clear_err_state(self):
1450 1449 """Return the current error state and clear it"""
1451 1450 e = self.last_syntax_error
1452 1451 self.last_syntax_error = None
1453 1452 return e
1454 1453
1455 1454 def stb2text(self, stb):
1456 1455 """Convert a structured traceback (a list) to a string."""
1457 1456 return ''.join(stb)
1458 1457
1459 1458
1460 1459 # some internal-use functions
1461 1460 def text_repr(value):
1462 1461 """Hopefully pretty robust repr equivalent."""
1463 1462 # this is pretty horrible but should always return *something*
1464 1463 try:
1465 1464 return pydoc.text.repr(value)
1466 1465 except KeyboardInterrupt:
1467 1466 raise
1468 1467 except:
1469 1468 try:
1470 1469 return repr(value)
1471 1470 except KeyboardInterrupt:
1472 1471 raise
1473 1472 except:
1474 1473 try:
1475 1474 # all still in an except block so we catch
1476 1475 # getattr raising
1477 1476 name = getattr(value, '__name__', None)
1478 1477 if name:
1479 1478 # ick, recursion
1480 1479 return text_repr(name)
1481 1480 klass = getattr(value, '__class__', None)
1482 1481 if klass:
1483 1482 return '%s instance' % text_repr(klass)
1484 1483 except KeyboardInterrupt:
1485 1484 raise
1486 1485 except:
1487 1486 return 'UNRECOVERABLE REPR FAILURE'
1488 1487
1489 1488
1490 1489 def eqrepr(value, repr=text_repr):
1491 1490 return '=%s' % repr(value)
1492 1491
1493 1492
1494 1493 def nullrepr(value, repr=text_repr):
1495 1494 return ''
@@ -1,325 +1,322 b''
1 1 # encoding: utf-8
2 2 """
3 3 An embedded IPython shell.
4 4 """
5 5 # Copyright (c) IPython Development Team.
6 6 # Distributed under the terms of the Modified BSD License.
7 7
8 8 from __future__ import with_statement
9 9 from __future__ import print_function
10 10
11 11 import sys
12 12 import warnings
13 13
14 14 from IPython.core import ultratb, compilerop
15 15 from IPython.core.magic import Magics, magics_class, line_magic
16 16 from IPython.core.interactiveshell import DummyMod, InteractiveShell
17 17 from IPython.terminal.interactiveshell import TerminalInteractiveShell
18 18 from IPython.terminal.ipapp import load_default_config
19 19
20 20 from traitlets import Bool, CBool, Unicode
21 21 from IPython.utils.io import ask_yes_no
22 22
23 23 class KillEmbeded(Exception):pass
24 24
25 25 # This is an additional magic that is exposed in embedded shells.
26 26 @magics_class
27 27 class EmbeddedMagics(Magics):
28 28
29 29 @line_magic
30 30 def kill_embedded(self, parameter_s=''):
31 31 """%kill_embedded : deactivate for good the current embedded IPython.
32 32
33 33 This function (after asking for confirmation) sets an internal flag so
34 34 that an embedded IPython will never activate again. This is useful to
35 35 permanently disable a shell that is being called inside a loop: once
36 36 you've figured out what you needed from it, you may then kill it and
37 37 the program will then continue to run without the interactive shell
38 38 interfering again.
39 39 """
40 40
41 41 kill = ask_yes_no("Are you sure you want to kill this embedded instance? [y/N] ",'n')
42 42 if kill:
43 43 self.shell.embedded_active = False
44 44 print ("This embedded IPython will not reactivate anymore "
45 45 "once you exit.")
46 46
47 47
48 48 @line_magic
49 49 def exit_raise(self, parameter_s=''):
50 50 """%exit_raise Make the current embedded kernel exit and raise and exception.
51 51
52 52 This function sets an internal flag so that an embedded IPython will
53 53 raise a `IPython.terminal.embed.KillEmbeded` Exception on exit, and then exit the current I. This is
54 54 useful to permanently exit a loop that create IPython embed instance.
55 55 """
56 56
57 57 self.shell.should_raise = True
58 58 self.shell.ask_exit()
59 59
60 60
61 61
62 62 class InteractiveShellEmbed(TerminalInteractiveShell):
63 63
64 64 dummy_mode = Bool(False)
65 65 exit_msg = Unicode('')
66 66 embedded = CBool(True)
67 67 should_raise = CBool(False)
68 68 # Like the base class display_banner is not configurable, but here it
69 69 # is True by default.
70 70 display_banner = CBool(True)
71 71 exit_msg = Unicode()
72 72
73 73 _inactive_locations = set()
74 74
75 75 @property
76 76 def embedded_active(self):
77 77 return self._call_location_id not in InteractiveShellEmbed._inactive_locations
78 78
79 79 @embedded_active.setter
80 80 def embedded_active(self, value):
81 81 if value :
82 82 if self._call_location_id in InteractiveShellEmbed._inactive_locations:
83 83 InteractiveShellEmbed._inactive_locations.remove(self._call_location_id)
84 84 else:
85 85 InteractiveShellEmbed._inactive_locations.add(self._call_location_id)
86 86
87 87 def __init__(self, **kw):
88 88
89 89
90 90 if kw.get('user_global_ns', None) is not None:
91 91 raise DeprecationWarning("Key word argument `user_global_ns` has been replaced by `user_module` since IPython 4.0.")
92 92
93 93 self._call_location_id = kw.pop('_call_location_id', None)
94 94
95 95 super(InteractiveShellEmbed,self).__init__(**kw)
96 96
97 97 if not self._call_location_id:
98 98 frame = sys._getframe(1)
99 99 self._call_location_id = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno)
100 100 # don't use the ipython crash handler so that user exceptions aren't
101 101 # trapped
102 102 sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
103 103 mode=self.xmode,
104 104 call_pdb=self.pdb)
105 105
106 106 def init_sys_modules(self):
107 107 pass
108 108
109 109 def init_magics(self):
110 110 super(InteractiveShellEmbed, self).init_magics()
111 111 self.register_magics(EmbeddedMagics)
112 112
113 113 def __call__(self, header='', local_ns=None, module=None, dummy=None,
114 114 stack_depth=1, global_ns=None, compile_flags=None):
115 115 """Activate the interactive interpreter.
116 116
117 117 __call__(self,header='',local_ns=None,module=None,dummy=None) -> Start
118 118 the interpreter shell with the given local and global namespaces, and
119 119 optionally print a header string at startup.
120 120
121 121 The shell can be globally activated/deactivated using the
122 122 dummy_mode attribute. This allows you to turn off a shell used
123 123 for debugging globally.
124 124
125 125 However, *each* time you call the shell you can override the current
126 126 state of dummy_mode with the optional keyword parameter 'dummy'. For
127 127 example, if you set dummy mode on with IPShell.dummy_mode = True, you
128 128 can still have a specific call work by making it as IPShell(dummy=False).
129 129 """
130 130
131 131 # If the user has turned it off, go away
132 132 if not self.embedded_active:
133 133 return
134 134
135 135 # Normal exits from interactive mode set this flag, so the shell can't
136 136 # re-enter (it checks this variable at the start of interactive mode).
137 137 self.exit_now = False
138 138
139 139 # Allow the dummy parameter to override the global __dummy_mode
140 140 if dummy or (dummy != 0 and self.dummy_mode):
141 141 return
142 142
143 if self.has_readline:
144 self.set_readline_completer()
145
146 143 # self.banner is auto computed
147 144 if header:
148 145 self.old_banner2 = self.banner2
149 146 self.banner2 = self.banner2 + '\n' + header + '\n'
150 147 else:
151 148 self.old_banner2 = ''
152 149
153 150 if self.display_banner:
154 151 self.show_banner()
155 152
156 153 # Call the embedding code with a stack depth of 1 so it can skip over
157 154 # our call and get the original caller's namespaces.
158 155 self.mainloop(local_ns, module, stack_depth=stack_depth,
159 156 global_ns=global_ns, compile_flags=compile_flags)
160 157
161 158 self.banner2 = self.old_banner2
162 159
163 160 if self.exit_msg is not None:
164 161 print(self.exit_msg)
165 162
166 163 if self.should_raise:
167 164 raise KillEmbeded('Embedded IPython raising error, as user requested.')
168 165
169 166
170 167 def mainloop(self, local_ns=None, module=None, stack_depth=0,
171 168 display_banner=None, global_ns=None, compile_flags=None):
172 169 """Embeds IPython into a running python program.
173 170
174 171 Parameters
175 172 ----------
176 173
177 174 local_ns, module
178 175 Working local namespace (a dict) and module (a module or similar
179 176 object). If given as None, they are automatically taken from the scope
180 177 where the shell was called, so that program variables become visible.
181 178
182 179 stack_depth : int
183 180 How many levels in the stack to go to looking for namespaces (when
184 181 local_ns or module is None). This allows an intermediate caller to
185 182 make sure that this function gets the namespace from the intended
186 183 level in the stack. By default (0) it will get its locals and globals
187 184 from the immediate caller.
188 185
189 186 compile_flags
190 187 A bit field identifying the __future__ features
191 188 that are enabled, as passed to the builtin :func:`compile` function.
192 189 If given as None, they are automatically taken from the scope where
193 190 the shell was called.
194 191
195 192 """
196 193
197 194 if (global_ns is not None) and (module is None):
198 195 raise DeprecationWarning("'global_ns' keyword argument is deprecated, and has been removed in IPython 5.0 use `module` keyword argument instead.")
199 196
200 197 if (display_banner is not None):
201 198 warnings.warn("The display_banner parameter is deprecated since IPython 4.0", DeprecationWarning)
202 199
203 200 # Get locals and globals from caller
204 201 if ((local_ns is None or module is None or compile_flags is None)
205 202 and self.default_user_namespaces):
206 203 call_frame = sys._getframe(stack_depth).f_back
207 204
208 205 if local_ns is None:
209 206 local_ns = call_frame.f_locals
210 207 if module is None:
211 208 global_ns = call_frame.f_globals
212 209 try:
213 210 module = sys.modules[global_ns['__name__']]
214 211 except KeyError:
215 212 warnings.warn("Failed to get module %s" % \
216 213 global_ns.get('__name__', 'unknown module')
217 214 )
218 215 module = DummyMod()
219 216 module.__dict__ = global_ns
220 217 if compile_flags is None:
221 218 compile_flags = (call_frame.f_code.co_flags &
222 219 compilerop.PyCF_MASK)
223 220
224 221 # Save original namespace and module so we can restore them after
225 222 # embedding; otherwise the shell doesn't shut down correctly.
226 223 orig_user_module = self.user_module
227 224 orig_user_ns = self.user_ns
228 225 orig_compile_flags = self.compile.flags
229 226
230 227 # Update namespaces and fire up interpreter
231 228
232 229 # The global one is easy, we can just throw it in
233 230 if module is not None:
234 231 self.user_module = module
235 232
236 233 # But the user/local one is tricky: ipython needs it to store internal
237 234 # data, but we also need the locals. We'll throw our hidden variables
238 235 # like _ih and get_ipython() into the local namespace, but delete them
239 236 # later.
240 237 if local_ns is not None:
241 238 reentrant_local_ns = {k: v for (k, v) in local_ns.items() if k not in self.user_ns_hidden.keys()}
242 239 self.user_ns = reentrant_local_ns
243 240 self.init_user_ns()
244 241
245 242 # Compiler flags
246 243 if compile_flags is not None:
247 244 self.compile.flags = compile_flags
248 245
249 246 # make sure the tab-completer has the correct frame information, so it
250 247 # actually completes using the frame's locals/globals
251 248 self.set_completer_frame()
252 249
253 250 with self.builtin_trap, self.display_trap:
254 251 self.interact()
255 252
256 253 # now, purge out the local namespace of IPython's hidden variables.
257 254 if local_ns is not None:
258 255 local_ns.update({k: v for (k, v) in self.user_ns.items() if k not in self.user_ns_hidden.keys()})
259 256
260 257
261 258 # Restore original namespace so shell can shut down when we exit.
262 259 self.user_module = orig_user_module
263 260 self.user_ns = orig_user_ns
264 261 self.compile.flags = orig_compile_flags
265 262
266 263
267 264 def embed(**kwargs):
268 265 """Call this to embed IPython at the current point in your program.
269 266
270 267 The first invocation of this will create an :class:`InteractiveShellEmbed`
271 268 instance and then call it. Consecutive calls just call the already
272 269 created instance.
273 270
274 271 If you don't want the kernel to initialize the namespace
275 272 from the scope of the surrounding function,
276 273 and/or you want to load full IPython configuration,
277 274 you probably want `IPython.start_ipython()` instead.
278 275
279 276 Here is a simple example::
280 277
281 278 from IPython import embed
282 279 a = 10
283 280 b = 20
284 281 embed(header='First time')
285 282 c = 30
286 283 d = 40
287 284 embed()
288 285
289 286 Full customization can be done by passing a :class:`Config` in as the
290 287 config argument.
291 288 """
292 289 config = kwargs.get('config')
293 290 header = kwargs.pop('header', u'')
294 291 compile_flags = kwargs.pop('compile_flags', None)
295 292 if config is None:
296 293 config = load_default_config()
297 294 config.InteractiveShellEmbed = config.TerminalInteractiveShell
298 295 config.InteractiveShellEmbed.colors='nocolor'
299 296 kwargs['config'] = config
300 297 #save ps1/ps2 if defined
301 298 ps1 = None
302 299 ps2 = None
303 300 try:
304 301 ps1 = sys.ps1
305 302 ps2 = sys.ps2
306 303 except AttributeError:
307 304 pass
308 305 #save previous instance
309 306 saved_shell_instance = InteractiveShell._instance
310 307 if saved_shell_instance is not None:
311 308 cls = type(saved_shell_instance)
312 309 cls.clear_instance()
313 310 frame = sys._getframe(1)
314 311 shell = InteractiveShellEmbed.instance(_call_location_id='%s:%s' % (frame.f_code.co_filename, frame.f_lineno), **kwargs)
315 312 shell(header=header, stack_depth=2, compile_flags=compile_flags)
316 313 InteractiveShellEmbed.clear_instance()
317 314 #restore previous instance
318 315 if saved_shell_instance is not None:
319 316 cls = type(saved_shell_instance)
320 317 cls.clear_instance()
321 318 for subclass in cls._walk_mro():
322 319 subclass._instance = saved_shell_instance
323 320 if ps1 is not None:
324 321 sys.ps1 = ps1
325 322 sys.ps2 = ps2
General Comments 0
You need to be logged in to leave comments. Login now