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