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