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