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