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