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