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