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