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