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