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