Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- lib/python3.12/site-packages/IPython/core/__init__.py +0 -0
- lib/python3.12/site-packages/IPython/core/alias.py +268 -0
- lib/python3.12/site-packages/IPython/core/application.py +492 -0
- lib/python3.12/site-packages/IPython/core/async_helpers.py +150 -0
- lib/python3.12/site-packages/IPython/core/autocall.py +70 -0
- lib/python3.12/site-packages/IPython/core/builtin_trap.py +93 -0
- lib/python3.12/site-packages/IPython/core/completer.py +0 -0
- lib/python3.12/site-packages/IPython/core/debugger.py +1376 -0
- lib/python3.12/site-packages/IPython/core/debugger_backport.py +206 -0
- lib/python3.12/site-packages/IPython/core/display.py +1266 -0
- lib/python3.12/site-packages/IPython/core/display_functions.py +371 -0
- lib/python3.12/site-packages/IPython/core/display_trap.py +74 -0
- lib/python3.12/site-packages/IPython/core/displayhook.py +346 -0
- lib/python3.12/site-packages/IPython/core/doctb.py +445 -0
- lib/python3.12/site-packages/IPython/core/events.py +172 -0
- lib/python3.12/site-packages/IPython/core/formatters.py +1090 -0
- lib/python3.12/site-packages/IPython/core/historyapp.py +158 -0
- lib/python3.12/site-packages/IPython/core/inputtransformer2.py +898 -0
- lib/python3.12/site-packages/IPython/core/interactiveshell.py +0 -0
- lib/python3.12/site-packages/IPython/core/macro.py +53 -0
- lib/python3.12/site-packages/IPython/core/magic_arguments.py +312 -0
- lib/python3.12/site-packages/IPython/core/oinspect.py +1215 -0
- lib/python3.12/site-packages/IPython/core/page.py +348 -0
- lib/python3.12/site-packages/IPython/core/payload.py +54 -0
- lib/python3.12/site-packages/IPython/core/payloadpage.py +41 -0
- lib/python3.12/site-packages/IPython/core/prefilter.py +707 -0
- lib/python3.12/site-packages/IPython/core/profileapp.py +315 -0
- lib/python3.12/site-packages/IPython/core/profiledir.py +244 -0
- lib/python3.12/site-packages/IPython/core/pylabtools.py +514 -0
- lib/python3.12/site-packages/IPython/core/shellapp.py +500 -0
- lib/python3.12/site-packages/IPython/core/splitinput.py +155 -0
- lib/python3.12/site-packages/IPython/core/tips.py +128 -0
- lib/python3.12/site-packages/IPython/core/ultratb.py +1263 -0
- lib/python3.12/site-packages/IPython/core/usage.py +341 -0
- lib/python3.12/site-packages/IPython/lib/__init__.py +11 -0
- lib/python3.12/site-packages/IPython/lib/__pycache__/__init__.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/IPython/lib/__pycache__/backgroundjobs.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/IPython/lib/__pycache__/clipboard.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/IPython/lib/__pycache__/deepreload.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/IPython/lib/__pycache__/demo.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/IPython/lib/__pycache__/display.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/IPython/lib/__pycache__/editorhooks.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/IPython/lib/__pycache__/guisupport.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/IPython/lib/__pycache__/latextools.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/IPython/lib/__pycache__/lexers.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/IPython/lib/__pycache__/pretty.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/IPython/lib/backgroundjobs.py +491 -0
- lib/python3.12/site-packages/IPython/lib/clipboard.py +102 -0
- lib/python3.12/site-packages/IPython/lib/deepreload.py +310 -0
- lib/python3.12/site-packages/IPython/lib/demo.py +672 -0
lib/python3.12/site-packages/IPython/core/__init__.py
ADDED
|
File without changes
|
lib/python3.12/site-packages/IPython/core/alias.py
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# encoding: utf-8
|
| 2 |
+
"""
|
| 3 |
+
System command aliases.
|
| 4 |
+
|
| 5 |
+
Authors:
|
| 6 |
+
|
| 7 |
+
* Fernando Perez
|
| 8 |
+
* Brian Granger
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
#-----------------------------------------------------------------------------
|
| 12 |
+
# Copyright (C) 2008-2011 The IPython Development Team
|
| 13 |
+
#
|
| 14 |
+
# Distributed under the terms of the BSD License.
|
| 15 |
+
#
|
| 16 |
+
# The full license is in the file COPYING.txt, distributed with this software.
|
| 17 |
+
#-----------------------------------------------------------------------------
|
| 18 |
+
|
| 19 |
+
#-----------------------------------------------------------------------------
|
| 20 |
+
# Imports
|
| 21 |
+
#-----------------------------------------------------------------------------
|
| 22 |
+
|
| 23 |
+
import os
|
| 24 |
+
import re
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
from traitlets.config.configurable import Configurable
|
| 28 |
+
from .error import UsageError
|
| 29 |
+
|
| 30 |
+
from traitlets import List, Instance
|
| 31 |
+
from logging import error
|
| 32 |
+
|
| 33 |
+
import typing as t
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
#-----------------------------------------------------------------------------
|
| 37 |
+
# Utilities
|
| 38 |
+
#-----------------------------------------------------------------------------
|
| 39 |
+
|
| 40 |
+
# This is used as the pattern for calls to split_user_input.
|
| 41 |
+
shell_line_split = re.compile(r'^(\s*)()(\S+)(.*$)')
|
| 42 |
+
|
| 43 |
+
def default_aliases() -> t.List[t.Tuple[str, str]]:
|
| 44 |
+
"""Return list of shell aliases to auto-define.
|
| 45 |
+
"""
|
| 46 |
+
# Note: the aliases defined here should be safe to use on a kernel
|
| 47 |
+
# regardless of what frontend it is attached to. Frontends that use a
|
| 48 |
+
# kernel in-process can define additional aliases that will only work in
|
| 49 |
+
# their case. For example, things like 'less' or 'clear' that manipulate
|
| 50 |
+
# the terminal should NOT be declared here, as they will only work if the
|
| 51 |
+
# kernel is running inside a true terminal, and not over the network.
|
| 52 |
+
|
| 53 |
+
if os.name == 'posix':
|
| 54 |
+
default_aliases = [('mkdir', 'mkdir'), ('rmdir', 'rmdir'),
|
| 55 |
+
('mv', 'mv'), ('rm', 'rm'), ('cp', 'cp'),
|
| 56 |
+
('cat', 'cat'),
|
| 57 |
+
]
|
| 58 |
+
# Useful set of ls aliases. The GNU and BSD options are a little
|
| 59 |
+
# different, so we make aliases that provide as similar as possible
|
| 60 |
+
# behavior in ipython, by passing the right flags for each platform
|
| 61 |
+
if sys.platform.startswith('linux'):
|
| 62 |
+
ls_aliases = [('ls', 'ls -F --color'),
|
| 63 |
+
# long ls
|
| 64 |
+
('ll', 'ls -F -o --color'),
|
| 65 |
+
# ls normal files only
|
| 66 |
+
('lf', 'ls -F -o --color %l | grep ^-'),
|
| 67 |
+
# ls symbolic links
|
| 68 |
+
('lk', 'ls -F -o --color %l | grep ^l'),
|
| 69 |
+
# directories or links to directories,
|
| 70 |
+
('ldir', 'ls -F -o --color %l | grep /$'),
|
| 71 |
+
# things which are executable
|
| 72 |
+
('lx', 'ls -F -o --color %l | grep ^-..x'),
|
| 73 |
+
]
|
| 74 |
+
elif sys.platform.startswith('openbsd') or sys.platform.startswith('netbsd'):
|
| 75 |
+
# OpenBSD, NetBSD. The ls implementation on these platforms do not support
|
| 76 |
+
# the -G switch and lack the ability to use colorized output.
|
| 77 |
+
ls_aliases = [('ls', 'ls -F'),
|
| 78 |
+
# long ls
|
| 79 |
+
('ll', 'ls -F -l'),
|
| 80 |
+
# ls normal files only
|
| 81 |
+
('lf', 'ls -F -l %l | grep ^-'),
|
| 82 |
+
# ls symbolic links
|
| 83 |
+
('lk', 'ls -F -l %l | grep ^l'),
|
| 84 |
+
# directories or links to directories,
|
| 85 |
+
('ldir', 'ls -F -l %l | grep /$'),
|
| 86 |
+
# things which are executable
|
| 87 |
+
('lx', 'ls -F -l %l | grep ^-..x'),
|
| 88 |
+
]
|
| 89 |
+
else:
|
| 90 |
+
# BSD, OSX, etc.
|
| 91 |
+
ls_aliases = [('ls', 'ls -F -G'),
|
| 92 |
+
# long ls
|
| 93 |
+
('ll', 'ls -F -l -G'),
|
| 94 |
+
# ls normal files only
|
| 95 |
+
('lf', 'ls -F -l -G %l | grep ^-'),
|
| 96 |
+
# ls symbolic links
|
| 97 |
+
('lk', 'ls -F -l -G %l | grep ^l'),
|
| 98 |
+
# directories or links to directories,
|
| 99 |
+
('ldir', 'ls -F -G -l %l | grep /$'),
|
| 100 |
+
# things which are executable
|
| 101 |
+
('lx', 'ls -F -l -G %l | grep ^-..x'),
|
| 102 |
+
]
|
| 103 |
+
default_aliases = default_aliases + ls_aliases
|
| 104 |
+
elif os.name in ['nt', 'dos']:
|
| 105 |
+
default_aliases = [('ls', 'dir /on'),
|
| 106 |
+
('ddir', 'dir /ad /on'), ('ldir', 'dir /ad /on'),
|
| 107 |
+
('mkdir', 'mkdir'), ('rmdir', 'rmdir'),
|
| 108 |
+
('echo', 'echo'), ('ren', 'ren'), ('copy', 'copy'),
|
| 109 |
+
]
|
| 110 |
+
else:
|
| 111 |
+
default_aliases = []
|
| 112 |
+
|
| 113 |
+
return default_aliases
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class AliasError(Exception):
|
| 117 |
+
pass
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class InvalidAliasError(AliasError):
|
| 121 |
+
pass
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class Alias:
|
| 125 |
+
"""Callable object storing the details of one alias.
|
| 126 |
+
|
| 127 |
+
Instances are registered as magic functions to allow use of aliases.
|
| 128 |
+
"""
|
| 129 |
+
|
| 130 |
+
# Prepare blacklist
|
| 131 |
+
blacklist = {'cd','popd','pushd','dhist','alias','unalias'}
|
| 132 |
+
|
| 133 |
+
def __init__(self, shell, name, cmd):
|
| 134 |
+
self.shell = shell
|
| 135 |
+
self.name = name
|
| 136 |
+
self.cmd = cmd
|
| 137 |
+
self.__doc__ = "Alias for `!{}`".format(cmd)
|
| 138 |
+
self.nargs = self.validate()
|
| 139 |
+
|
| 140 |
+
def validate(self):
|
| 141 |
+
"""Validate the alias, and return the number of arguments."""
|
| 142 |
+
if self.name in self.blacklist:
|
| 143 |
+
raise InvalidAliasError("The name %s can't be aliased "
|
| 144 |
+
"because it is a keyword or builtin." % self.name)
|
| 145 |
+
try:
|
| 146 |
+
caller = self.shell.magics_manager.magics['line'][self.name]
|
| 147 |
+
except KeyError:
|
| 148 |
+
pass
|
| 149 |
+
else:
|
| 150 |
+
if not isinstance(caller, Alias):
|
| 151 |
+
raise InvalidAliasError("The name %s can't be aliased "
|
| 152 |
+
"because it is another magic command." % self.name)
|
| 153 |
+
|
| 154 |
+
if not (isinstance(self.cmd, str)):
|
| 155 |
+
raise InvalidAliasError("An alias command must be a string, "
|
| 156 |
+
"got: %r" % self.cmd)
|
| 157 |
+
|
| 158 |
+
nargs = self.cmd.count('%s') - self.cmd.count('%%s')
|
| 159 |
+
|
| 160 |
+
if (nargs > 0) and (self.cmd.find('%l') >= 0):
|
| 161 |
+
raise InvalidAliasError('The %s and %l specifiers are mutually '
|
| 162 |
+
'exclusive in alias definitions.')
|
| 163 |
+
|
| 164 |
+
return nargs
|
| 165 |
+
|
| 166 |
+
def __repr__(self):
|
| 167 |
+
return "<alias {} for {!r}>".format(self.name, self.cmd)
|
| 168 |
+
|
| 169 |
+
def __call__(self, rest=''):
|
| 170 |
+
cmd = self.cmd
|
| 171 |
+
nargs = self.nargs
|
| 172 |
+
# Expand the %l special to be the user's input line
|
| 173 |
+
if cmd.find('%l') >= 0:
|
| 174 |
+
cmd = cmd.replace('%l', rest)
|
| 175 |
+
rest = ''
|
| 176 |
+
|
| 177 |
+
if nargs==0:
|
| 178 |
+
if cmd.find('%%s') >= 1:
|
| 179 |
+
cmd = cmd.replace('%%s', '%s')
|
| 180 |
+
# Simple, argument-less aliases
|
| 181 |
+
cmd = '%s %s' % (cmd, rest)
|
| 182 |
+
else:
|
| 183 |
+
# Handle aliases with positional arguments
|
| 184 |
+
args = rest.split(None, nargs)
|
| 185 |
+
if len(args) < nargs:
|
| 186 |
+
raise UsageError('Alias <%s> requires %s arguments, %s given.' %
|
| 187 |
+
(self.name, nargs, len(args)))
|
| 188 |
+
cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
|
| 189 |
+
|
| 190 |
+
self.shell.system(cmd)
|
| 191 |
+
|
| 192 |
+
#-----------------------------------------------------------------------------
|
| 193 |
+
# Main AliasManager class
|
| 194 |
+
#-----------------------------------------------------------------------------
|
| 195 |
+
|
| 196 |
+
class AliasManager(Configurable):
|
| 197 |
+
default_aliases: List = List(default_aliases()).tag(config=True)
|
| 198 |
+
user_aliases: List = List(default_value=[]).tag(config=True)
|
| 199 |
+
shell = Instance(
|
| 200 |
+
"IPython.core.interactiveshell.InteractiveShellABC", allow_none=True
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
def __init__(self, shell=None, **kwargs):
|
| 204 |
+
super(AliasManager, self).__init__(shell=shell, **kwargs)
|
| 205 |
+
# For convenient access
|
| 206 |
+
if self.shell is not None:
|
| 207 |
+
self.linemagics = self.shell.magics_manager.magics["line"]
|
| 208 |
+
self.init_aliases()
|
| 209 |
+
|
| 210 |
+
def init_aliases(self):
|
| 211 |
+
# Load default & user aliases
|
| 212 |
+
for name, cmd in self.default_aliases + self.user_aliases:
|
| 213 |
+
if (
|
| 214 |
+
cmd.startswith("ls ")
|
| 215 |
+
and self.shell is not None
|
| 216 |
+
and self.shell.colors == "nocolor"
|
| 217 |
+
):
|
| 218 |
+
cmd = cmd.replace(" --color", "")
|
| 219 |
+
self.soft_define_alias(name, cmd)
|
| 220 |
+
|
| 221 |
+
@property
|
| 222 |
+
def aliases(self):
|
| 223 |
+
return [(n, func.cmd) for (n, func) in self.linemagics.items()
|
| 224 |
+
if isinstance(func, Alias)]
|
| 225 |
+
|
| 226 |
+
def soft_define_alias(self, name, cmd):
|
| 227 |
+
"""Define an alias, but don't raise on an AliasError."""
|
| 228 |
+
try:
|
| 229 |
+
self.define_alias(name, cmd)
|
| 230 |
+
except AliasError as e:
|
| 231 |
+
error("Invalid alias: %s" % e)
|
| 232 |
+
|
| 233 |
+
def define_alias(self, name, cmd):
|
| 234 |
+
"""Define a new alias after validating it.
|
| 235 |
+
|
| 236 |
+
This will raise an :exc:`AliasError` if there are validation
|
| 237 |
+
problems.
|
| 238 |
+
"""
|
| 239 |
+
caller = Alias(shell=self.shell, name=name, cmd=cmd)
|
| 240 |
+
self.shell.magics_manager.register_function(caller, magic_kind='line',
|
| 241 |
+
magic_name=name)
|
| 242 |
+
|
| 243 |
+
def get_alias(self, name):
|
| 244 |
+
"""Return an alias, or None if no alias by that name exists."""
|
| 245 |
+
aname = self.linemagics.get(name, None)
|
| 246 |
+
return aname if isinstance(aname, Alias) else None
|
| 247 |
+
|
| 248 |
+
def is_alias(self, name):
|
| 249 |
+
"""Return whether or not a given name has been defined as an alias"""
|
| 250 |
+
return self.get_alias(name) is not None
|
| 251 |
+
|
| 252 |
+
def undefine_alias(self, name):
|
| 253 |
+
if self.is_alias(name):
|
| 254 |
+
del self.linemagics[name]
|
| 255 |
+
else:
|
| 256 |
+
raise ValueError('%s is not an alias' % name)
|
| 257 |
+
|
| 258 |
+
def clear_aliases(self):
|
| 259 |
+
for name, _ in self.aliases:
|
| 260 |
+
self.undefine_alias(name)
|
| 261 |
+
|
| 262 |
+
def retrieve_alias(self, name):
|
| 263 |
+
"""Retrieve the command to which an alias expands."""
|
| 264 |
+
caller = self.get_alias(name)
|
| 265 |
+
if caller:
|
| 266 |
+
return caller.cmd
|
| 267 |
+
else:
|
| 268 |
+
raise ValueError('%s is not an alias' % name)
|
lib/python3.12/site-packages/IPython/core/application.py
ADDED
|
@@ -0,0 +1,492 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# encoding: utf-8
|
| 2 |
+
"""
|
| 3 |
+
An application for IPython.
|
| 4 |
+
|
| 5 |
+
All top-level applications should use the classes in this module for
|
| 6 |
+
handling configuration and creating configurables.
|
| 7 |
+
|
| 8 |
+
The job of an :class:`Application` is to create the master configuration
|
| 9 |
+
object and then create the configurable objects, passing the config to them.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
# Copyright (c) IPython Development Team.
|
| 13 |
+
# Distributed under the terms of the Modified BSD License.
|
| 14 |
+
|
| 15 |
+
import atexit
|
| 16 |
+
from copy import deepcopy
|
| 17 |
+
import logging
|
| 18 |
+
import os
|
| 19 |
+
import shutil
|
| 20 |
+
import sys
|
| 21 |
+
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
|
| 24 |
+
from traitlets.config.application import Application, catch_config_error
|
| 25 |
+
from traitlets.config.loader import ConfigFileNotFound, PyFileConfigLoader
|
| 26 |
+
from IPython.core import release, crashhandler
|
| 27 |
+
from IPython.core.profiledir import ProfileDir, ProfileDirError
|
| 28 |
+
from IPython.paths import get_ipython_dir, get_ipython_package_dir
|
| 29 |
+
from IPython.utils.path import ensure_dir_exists
|
| 30 |
+
from traitlets import (
|
| 31 |
+
List, Unicode, Type, Bool, Set, Instance, Undefined,
|
| 32 |
+
default, observe,
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
if os.name == "nt":
|
| 36 |
+
programdata = os.environ.get("PROGRAMDATA", None)
|
| 37 |
+
if programdata is not None:
|
| 38 |
+
SYSTEM_CONFIG_DIRS = [str(Path(programdata) / "ipython")]
|
| 39 |
+
else: # PROGRAMDATA is not defined by default on XP.
|
| 40 |
+
SYSTEM_CONFIG_DIRS = []
|
| 41 |
+
else:
|
| 42 |
+
SYSTEM_CONFIG_DIRS = [
|
| 43 |
+
"/usr/local/etc/ipython",
|
| 44 |
+
"/etc/ipython",
|
| 45 |
+
]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
ENV_CONFIG_DIRS = []
|
| 49 |
+
_env_config_dir = os.path.join(sys.prefix, 'etc', 'ipython')
|
| 50 |
+
if _env_config_dir not in SYSTEM_CONFIG_DIRS:
|
| 51 |
+
# only add ENV_CONFIG if sys.prefix is not already included
|
| 52 |
+
ENV_CONFIG_DIRS.append(_env_config_dir)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
_envvar = os.environ.get('IPYTHON_SUPPRESS_CONFIG_ERRORS')
|
| 56 |
+
if _envvar in {None, ''}:
|
| 57 |
+
IPYTHON_SUPPRESS_CONFIG_ERRORS = None
|
| 58 |
+
else:
|
| 59 |
+
if _envvar.lower() in {'1','true'}:
|
| 60 |
+
IPYTHON_SUPPRESS_CONFIG_ERRORS = True
|
| 61 |
+
elif _envvar.lower() in {'0','false'} :
|
| 62 |
+
IPYTHON_SUPPRESS_CONFIG_ERRORS = False
|
| 63 |
+
else:
|
| 64 |
+
sys.exit("Unsupported value for environment variable: 'IPYTHON_SUPPRESS_CONFIG_ERRORS' is set to '%s' which is none of {'0', '1', 'false', 'true', ''}."% _envvar )
|
| 65 |
+
|
| 66 |
+
# aliases and flags
|
| 67 |
+
|
| 68 |
+
base_aliases = {}
|
| 69 |
+
if isinstance(Application.aliases, dict):
|
| 70 |
+
# traitlets 5
|
| 71 |
+
base_aliases.update(Application.aliases)
|
| 72 |
+
base_aliases.update(
|
| 73 |
+
{
|
| 74 |
+
"profile-dir": "ProfileDir.location",
|
| 75 |
+
"profile": "BaseIPythonApplication.profile",
|
| 76 |
+
"ipython-dir": "BaseIPythonApplication.ipython_dir",
|
| 77 |
+
"log-level": "Application.log_level",
|
| 78 |
+
"config": "BaseIPythonApplication.extra_config_file",
|
| 79 |
+
}
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
base_flags = dict()
|
| 83 |
+
if isinstance(Application.flags, dict):
|
| 84 |
+
# traitlets 5
|
| 85 |
+
base_flags.update(Application.flags)
|
| 86 |
+
base_flags.update(
|
| 87 |
+
dict(
|
| 88 |
+
debug=(
|
| 89 |
+
{"Application": {"log_level": logging.DEBUG}},
|
| 90 |
+
"set log level to logging.DEBUG (maximize logging output)",
|
| 91 |
+
),
|
| 92 |
+
quiet=(
|
| 93 |
+
{"Application": {"log_level": logging.CRITICAL}},
|
| 94 |
+
"set log level to logging.CRITICAL (minimize logging output)",
|
| 95 |
+
),
|
| 96 |
+
init=(
|
| 97 |
+
{
|
| 98 |
+
"BaseIPythonApplication": {
|
| 99 |
+
"copy_config_files": True,
|
| 100 |
+
"auto_create": True,
|
| 101 |
+
}
|
| 102 |
+
},
|
| 103 |
+
"""Initialize profile with default config files. This is equivalent
|
| 104 |
+
to running `ipython profile create <profile>` prior to startup.
|
| 105 |
+
""",
|
| 106 |
+
),
|
| 107 |
+
)
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class ProfileAwareConfigLoader(PyFileConfigLoader):
|
| 112 |
+
"""A Python file config loader that is aware of IPython profiles."""
|
| 113 |
+
def load_subconfig(self, fname, path=None, profile=None):
|
| 114 |
+
if profile is not None:
|
| 115 |
+
try:
|
| 116 |
+
profile_dir = ProfileDir.find_profile_dir_by_name(
|
| 117 |
+
get_ipython_dir(),
|
| 118 |
+
profile,
|
| 119 |
+
)
|
| 120 |
+
except ProfileDirError:
|
| 121 |
+
return
|
| 122 |
+
path = profile_dir.location
|
| 123 |
+
return super(ProfileAwareConfigLoader, self).load_subconfig(fname, path=path)
|
| 124 |
+
|
| 125 |
+
class BaseIPythonApplication(Application):
|
| 126 |
+
name = "ipython"
|
| 127 |
+
description = "IPython: an enhanced interactive Python shell."
|
| 128 |
+
version = Unicode(release.version)
|
| 129 |
+
|
| 130 |
+
aliases = base_aliases
|
| 131 |
+
flags = base_flags
|
| 132 |
+
classes = List([ProfileDir])
|
| 133 |
+
|
| 134 |
+
# enable `load_subconfig('cfg.py', profile='name')`
|
| 135 |
+
python_config_loader_class = ProfileAwareConfigLoader
|
| 136 |
+
|
| 137 |
+
# Track whether the config_file has changed,
|
| 138 |
+
# because some logic happens only if we aren't using the default.
|
| 139 |
+
config_file_specified = Set()
|
| 140 |
+
|
| 141 |
+
config_file_name = Unicode()
|
| 142 |
+
@default('config_file_name')
|
| 143 |
+
def _config_file_name_default(self):
|
| 144 |
+
return self.name.replace('-','_') + u'_config.py'
|
| 145 |
+
@observe('config_file_name')
|
| 146 |
+
def _config_file_name_changed(self, change):
|
| 147 |
+
if change['new'] != change['old']:
|
| 148 |
+
self.config_file_specified.add(change['new'])
|
| 149 |
+
|
| 150 |
+
# The directory that contains IPython's builtin profiles.
|
| 151 |
+
builtin_profile_dir = Unicode(
|
| 152 |
+
os.path.join(get_ipython_package_dir(), u'config', u'profile', u'default')
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
config_file_paths = List(Unicode())
|
| 156 |
+
@default('config_file_paths')
|
| 157 |
+
def _config_file_paths_default(self):
|
| 158 |
+
return []
|
| 159 |
+
|
| 160 |
+
extra_config_file = Unicode(
|
| 161 |
+
help="""Path to an extra config file to load.
|
| 162 |
+
|
| 163 |
+
If specified, load this config file in addition to any other IPython config.
|
| 164 |
+
""").tag(config=True)
|
| 165 |
+
@observe('extra_config_file')
|
| 166 |
+
def _extra_config_file_changed(self, change):
|
| 167 |
+
old = change['old']
|
| 168 |
+
new = change['new']
|
| 169 |
+
try:
|
| 170 |
+
self.config_files.remove(old)
|
| 171 |
+
except ValueError:
|
| 172 |
+
pass
|
| 173 |
+
self.config_file_specified.add(new)
|
| 174 |
+
self.config_files.append(new)
|
| 175 |
+
|
| 176 |
+
profile = Unicode(u'default',
|
| 177 |
+
help="""The IPython profile to use."""
|
| 178 |
+
).tag(config=True)
|
| 179 |
+
|
| 180 |
+
@observe('profile')
|
| 181 |
+
def _profile_changed(self, change):
|
| 182 |
+
self.builtin_profile_dir = os.path.join(
|
| 183 |
+
get_ipython_package_dir(), u'config', u'profile', change['new']
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
add_ipython_dir_to_sys_path = Bool(
|
| 187 |
+
False,
|
| 188 |
+
"""Should the IPython profile directory be added to sys path ?
|
| 189 |
+
|
| 190 |
+
This option was non-existing before IPython 8.0, and ipython_dir was added to
|
| 191 |
+
sys path to allow import of extensions present there. This was historical
|
| 192 |
+
baggage from when pip did not exist. This now default to false,
|
| 193 |
+
but can be set to true for legacy reasons.
|
| 194 |
+
""",
|
| 195 |
+
).tag(config=True)
|
| 196 |
+
|
| 197 |
+
ipython_dir = Unicode(
|
| 198 |
+
help="""
|
| 199 |
+
The name of the IPython directory. This directory is used for logging
|
| 200 |
+
configuration (through profiles), history storage, etc. The default
|
| 201 |
+
is usually $HOME/.ipython. This option can also be specified through
|
| 202 |
+
the environment variable IPYTHONDIR.
|
| 203 |
+
"""
|
| 204 |
+
).tag(config=True)
|
| 205 |
+
@default('ipython_dir')
|
| 206 |
+
def _ipython_dir_default(self):
|
| 207 |
+
d = get_ipython_dir()
|
| 208 |
+
self._ipython_dir_changed({
|
| 209 |
+
'name': 'ipython_dir',
|
| 210 |
+
'old': d,
|
| 211 |
+
'new': d,
|
| 212 |
+
})
|
| 213 |
+
return d
|
| 214 |
+
|
| 215 |
+
_in_init_profile_dir = False
|
| 216 |
+
|
| 217 |
+
profile_dir = Instance(ProfileDir, allow_none=True)
|
| 218 |
+
|
| 219 |
+
@default('profile_dir')
|
| 220 |
+
def _profile_dir_default(self):
|
| 221 |
+
# avoid recursion
|
| 222 |
+
if self._in_init_profile_dir:
|
| 223 |
+
return
|
| 224 |
+
# profile_dir requested early, force initialization
|
| 225 |
+
self.init_profile_dir()
|
| 226 |
+
return self.profile_dir
|
| 227 |
+
|
| 228 |
+
overwrite = Bool(False,
|
| 229 |
+
help="""Whether to overwrite existing config files when copying"""
|
| 230 |
+
).tag(config=True)
|
| 231 |
+
|
| 232 |
+
auto_create = Bool(False,
|
| 233 |
+
help="""Whether to create profile dir if it doesn't exist"""
|
| 234 |
+
).tag(config=True)
|
| 235 |
+
|
| 236 |
+
config_files = List(Unicode())
|
| 237 |
+
|
| 238 |
+
@default('config_files')
|
| 239 |
+
def _config_files_default(self):
|
| 240 |
+
return [self.config_file_name]
|
| 241 |
+
|
| 242 |
+
copy_config_files = Bool(False,
|
| 243 |
+
help="""Whether to install the default config files into the profile dir.
|
| 244 |
+
If a new profile is being created, and IPython contains config files for that
|
| 245 |
+
profile, then they will be staged into the new directory. Otherwise,
|
| 246 |
+
default config files will be automatically generated.
|
| 247 |
+
""").tag(config=True)
|
| 248 |
+
|
| 249 |
+
verbose_crash = Bool(False,
|
| 250 |
+
help="""Create a massive crash report when IPython encounters what may be an
|
| 251 |
+
internal error. The default is to append a short message to the
|
| 252 |
+
usual traceback""").tag(config=True)
|
| 253 |
+
|
| 254 |
+
# The class to use as the crash handler.
|
| 255 |
+
crash_handler_class = Type(crashhandler.CrashHandler)
|
| 256 |
+
|
| 257 |
+
@catch_config_error
|
| 258 |
+
def __init__(self, **kwargs):
|
| 259 |
+
super(BaseIPythonApplication, self).__init__(**kwargs)
|
| 260 |
+
# ensure current working directory exists
|
| 261 |
+
try:
|
| 262 |
+
os.getcwd()
|
| 263 |
+
except:
|
| 264 |
+
# exit if cwd doesn't exist
|
| 265 |
+
self.log.error("Current working directory doesn't exist.")
|
| 266 |
+
self.exit(1)
|
| 267 |
+
|
| 268 |
+
#-------------------------------------------------------------------------
|
| 269 |
+
# Various stages of Application creation
|
| 270 |
+
#-------------------------------------------------------------------------
|
| 271 |
+
|
| 272 |
+
def init_crash_handler(self):
|
| 273 |
+
"""Create a crash handler, typically setting sys.excepthook to it."""
|
| 274 |
+
self.crash_handler = self.crash_handler_class(self)
|
| 275 |
+
sys.excepthook = self.excepthook
|
| 276 |
+
def unset_crashhandler():
|
| 277 |
+
sys.excepthook = sys.__excepthook__
|
| 278 |
+
atexit.register(unset_crashhandler)
|
| 279 |
+
|
| 280 |
+
def excepthook(self, etype, evalue, tb):
|
| 281 |
+
"""this is sys.excepthook after init_crashhandler
|
| 282 |
+
|
| 283 |
+
set self.verbose_crash=True to use our full crashhandler, instead of
|
| 284 |
+
a regular traceback with a short message (crash_handler_lite)
|
| 285 |
+
"""
|
| 286 |
+
|
| 287 |
+
if self.verbose_crash:
|
| 288 |
+
return self.crash_handler(etype, evalue, tb)
|
| 289 |
+
else:
|
| 290 |
+
return crashhandler.crash_handler_lite(etype, evalue, tb)
|
| 291 |
+
|
| 292 |
+
@observe('ipython_dir')
|
| 293 |
+
def _ipython_dir_changed(self, change):
|
| 294 |
+
old = change['old']
|
| 295 |
+
new = change['new']
|
| 296 |
+
if old is not Undefined:
|
| 297 |
+
str_old = os.path.abspath(old)
|
| 298 |
+
if str_old in sys.path:
|
| 299 |
+
sys.path.remove(str_old)
|
| 300 |
+
if self.add_ipython_dir_to_sys_path:
|
| 301 |
+
str_path = os.path.abspath(new)
|
| 302 |
+
sys.path.append(str_path)
|
| 303 |
+
ensure_dir_exists(new)
|
| 304 |
+
readme = os.path.join(new, "README")
|
| 305 |
+
readme_src = os.path.join(
|
| 306 |
+
get_ipython_package_dir(), "config", "profile", "README"
|
| 307 |
+
)
|
| 308 |
+
if not os.path.exists(readme) and os.path.exists(readme_src):
|
| 309 |
+
shutil.copy(readme_src, readme)
|
| 310 |
+
for d in ("extensions", "nbextensions"):
|
| 311 |
+
path = os.path.join(new, d)
|
| 312 |
+
try:
|
| 313 |
+
ensure_dir_exists(path)
|
| 314 |
+
except OSError as e:
|
| 315 |
+
# this will not be EEXIST
|
| 316 |
+
self.log.error("couldn't create path %s: %s", path, e)
|
| 317 |
+
self.log.debug("IPYTHONDIR set to: %s", new)
|
| 318 |
+
|
| 319 |
+
def load_config_file(self, suppress_errors=IPYTHON_SUPPRESS_CONFIG_ERRORS):
|
| 320 |
+
"""Load the config file.
|
| 321 |
+
|
| 322 |
+
By default, errors in loading config are handled, and a warning
|
| 323 |
+
printed on screen. For testing, the suppress_errors option is set
|
| 324 |
+
to False, so errors will make tests fail.
|
| 325 |
+
|
| 326 |
+
`suppress_errors` default value is to be `None` in which case the
|
| 327 |
+
behavior default to the one of `traitlets.Application`.
|
| 328 |
+
|
| 329 |
+
The default value can be set :
|
| 330 |
+
- to `False` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '0', or 'false' (case insensitive).
|
| 331 |
+
- to `True` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '1' or 'true' (case insensitive).
|
| 332 |
+
- to `None` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '' (empty string) or leaving it unset.
|
| 333 |
+
|
| 334 |
+
Any other value are invalid, and will make IPython exit with a non-zero return code.
|
| 335 |
+
"""
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
self.log.debug("Searching path %s for config files", self.config_file_paths)
|
| 339 |
+
base_config = 'ipython_config.py'
|
| 340 |
+
self.log.debug("Attempting to load config file: %s" %
|
| 341 |
+
base_config)
|
| 342 |
+
try:
|
| 343 |
+
if suppress_errors is not None:
|
| 344 |
+
old_value = Application.raise_config_file_errors
|
| 345 |
+
Application.raise_config_file_errors = not suppress_errors
|
| 346 |
+
Application.load_config_file(
|
| 347 |
+
self,
|
| 348 |
+
base_config,
|
| 349 |
+
path=self.config_file_paths
|
| 350 |
+
)
|
| 351 |
+
except ConfigFileNotFound:
|
| 352 |
+
# ignore errors loading parent
|
| 353 |
+
self.log.debug("Config file %s not found", base_config)
|
| 354 |
+
pass
|
| 355 |
+
if suppress_errors is not None:
|
| 356 |
+
Application.raise_config_file_errors = old_value
|
| 357 |
+
|
| 358 |
+
for config_file_name in self.config_files:
|
| 359 |
+
if not config_file_name or config_file_name == base_config:
|
| 360 |
+
continue
|
| 361 |
+
self.log.debug("Attempting to load config file: %s" %
|
| 362 |
+
self.config_file_name)
|
| 363 |
+
try:
|
| 364 |
+
Application.load_config_file(
|
| 365 |
+
self,
|
| 366 |
+
config_file_name,
|
| 367 |
+
path=self.config_file_paths
|
| 368 |
+
)
|
| 369 |
+
except ConfigFileNotFound:
|
| 370 |
+
# Only warn if the default config file was NOT being used.
|
| 371 |
+
if config_file_name in self.config_file_specified:
|
| 372 |
+
msg = self.log.warning
|
| 373 |
+
else:
|
| 374 |
+
msg = self.log.debug
|
| 375 |
+
msg("Config file not found, skipping: %s", config_file_name)
|
| 376 |
+
except Exception:
|
| 377 |
+
# For testing purposes.
|
| 378 |
+
if not suppress_errors:
|
| 379 |
+
raise
|
| 380 |
+
self.log.warning("Error loading config file: %s" %
|
| 381 |
+
self.config_file_name, exc_info=True)
|
| 382 |
+
|
| 383 |
+
def init_profile_dir(self):
|
| 384 |
+
"""initialize the profile dir"""
|
| 385 |
+
self._in_init_profile_dir = True
|
| 386 |
+
if self.profile_dir is not None:
|
| 387 |
+
# already ran
|
| 388 |
+
return
|
| 389 |
+
if 'ProfileDir.location' not in self.config:
|
| 390 |
+
# location not specified, find by profile name
|
| 391 |
+
try:
|
| 392 |
+
p = ProfileDir.find_profile_dir_by_name(self.ipython_dir, self.profile, self.config)
|
| 393 |
+
except ProfileDirError:
|
| 394 |
+
# not found, maybe create it (always create default profile)
|
| 395 |
+
if self.auto_create or self.profile == 'default':
|
| 396 |
+
try:
|
| 397 |
+
p = ProfileDir.create_profile_dir_by_name(self.ipython_dir, self.profile, self.config)
|
| 398 |
+
except ProfileDirError:
|
| 399 |
+
self.log.fatal("Could not create profile: %r"%self.profile)
|
| 400 |
+
self.exit(1)
|
| 401 |
+
else:
|
| 402 |
+
self.log.info("Created profile dir: %r"%p.location)
|
| 403 |
+
else:
|
| 404 |
+
self.log.fatal("Profile %r not found."%self.profile)
|
| 405 |
+
self.exit(1)
|
| 406 |
+
else:
|
| 407 |
+
self.log.debug("Using existing profile dir: %r", p.location)
|
| 408 |
+
else:
|
| 409 |
+
location = self.config.ProfileDir.location
|
| 410 |
+
# location is fully specified
|
| 411 |
+
try:
|
| 412 |
+
p = ProfileDir.find_profile_dir(location, self.config)
|
| 413 |
+
except ProfileDirError:
|
| 414 |
+
# not found, maybe create it
|
| 415 |
+
if self.auto_create:
|
| 416 |
+
try:
|
| 417 |
+
p = ProfileDir.create_profile_dir(location, self.config)
|
| 418 |
+
except ProfileDirError:
|
| 419 |
+
self.log.fatal("Could not create profile directory: %r"%location)
|
| 420 |
+
self.exit(1)
|
| 421 |
+
else:
|
| 422 |
+
self.log.debug("Creating new profile dir: %r"%location)
|
| 423 |
+
else:
|
| 424 |
+
self.log.fatal("Profile directory %r not found."%location)
|
| 425 |
+
self.exit(1)
|
| 426 |
+
else:
|
| 427 |
+
self.log.debug("Using existing profile dir: %r", p.location)
|
| 428 |
+
# if profile_dir is specified explicitly, set profile name
|
| 429 |
+
dir_name = os.path.basename(p.location)
|
| 430 |
+
if dir_name.startswith('profile_'):
|
| 431 |
+
self.profile = dir_name[8:]
|
| 432 |
+
|
| 433 |
+
self.profile_dir = p
|
| 434 |
+
self.config_file_paths.append(p.location)
|
| 435 |
+
self._in_init_profile_dir = False
|
| 436 |
+
|
| 437 |
+
def init_config_files(self):
|
| 438 |
+
"""[optionally] copy default config files into profile dir."""
|
| 439 |
+
self.config_file_paths.extend(ENV_CONFIG_DIRS)
|
| 440 |
+
self.config_file_paths.extend(SYSTEM_CONFIG_DIRS)
|
| 441 |
+
# copy config files
|
| 442 |
+
path = Path(self.builtin_profile_dir)
|
| 443 |
+
if self.copy_config_files:
|
| 444 |
+
src = self.profile
|
| 445 |
+
|
| 446 |
+
cfg = self.config_file_name
|
| 447 |
+
if path and (path / cfg).exists():
|
| 448 |
+
self.log.warning(
|
| 449 |
+
"Staging %r from %s into %r [overwrite=%s]"
|
| 450 |
+
% (cfg, src, self.profile_dir.location, self.overwrite)
|
| 451 |
+
)
|
| 452 |
+
self.profile_dir.copy_config_file(cfg, path=path, overwrite=self.overwrite)
|
| 453 |
+
else:
|
| 454 |
+
self.stage_default_config_file()
|
| 455 |
+
else:
|
| 456 |
+
# Still stage *bundled* config files, but not generated ones
|
| 457 |
+
# This is necessary for `ipython profile=sympy` to load the profile
|
| 458 |
+
# on the first go
|
| 459 |
+
files = path.glob("*.py")
|
| 460 |
+
for fullpath in files:
|
| 461 |
+
cfg = fullpath.name
|
| 462 |
+
if self.profile_dir.copy_config_file(cfg, path=path, overwrite=False):
|
| 463 |
+
# file was copied
|
| 464 |
+
self.log.warning("Staging bundled %s from %s into %r"%(
|
| 465 |
+
cfg, self.profile, self.profile_dir.location)
|
| 466 |
+
)
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
def stage_default_config_file(self):
|
| 470 |
+
"""auto generate default config file, and stage it into the profile."""
|
| 471 |
+
s = self.generate_config_file()
|
| 472 |
+
config_file = Path(self.profile_dir.location) / self.config_file_name
|
| 473 |
+
if self.overwrite or not config_file.exists():
|
| 474 |
+
self.log.warning("Generating default config file: %r", (config_file))
|
| 475 |
+
config_file.write_text(s, encoding="utf-8")
|
| 476 |
+
|
| 477 |
+
@catch_config_error
|
| 478 |
+
def initialize(self, argv=None):
|
| 479 |
+
# don't hook up crash handler before parsing command-line
|
| 480 |
+
self.parse_command_line(argv)
|
| 481 |
+
self.init_crash_handler()
|
| 482 |
+
if self.subapp is not None:
|
| 483 |
+
# stop here if subapp is taking over
|
| 484 |
+
return
|
| 485 |
+
# save a copy of CLI config to re-load after config files
|
| 486 |
+
# so that it has highest priority
|
| 487 |
+
cl_config = deepcopy(self.config)
|
| 488 |
+
self.init_profile_dir()
|
| 489 |
+
self.init_config_files()
|
| 490 |
+
self.load_config_file()
|
| 491 |
+
# enforce cl-opts override configfile opts:
|
| 492 |
+
self.update_config(cl_config)
|
lib/python3.12/site-packages/IPython/core/async_helpers.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Async helper function that are invalid syntax on Python 3.5 and below.
|
| 3 |
+
|
| 4 |
+
This code is best effort, and may have edge cases not behaving as expected. In
|
| 5 |
+
particular it contain a number of heuristics to detect whether code is
|
| 6 |
+
effectively async and need to run in an event loop or not.
|
| 7 |
+
|
| 8 |
+
Some constructs (like top-level `return`, or `yield`) are taken care of
|
| 9 |
+
explicitly to actually raise a SyntaxError and stay as close as possible to
|
| 10 |
+
Python semantics.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import ast
|
| 14 |
+
import asyncio
|
| 15 |
+
import inspect
|
| 16 |
+
from functools import wraps
|
| 17 |
+
|
| 18 |
+
_asyncio_event_loop = None
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def get_asyncio_loop():
|
| 22 |
+
"""asyncio has deprecated get_event_loop
|
| 23 |
+
|
| 24 |
+
Replicate it here, with our desired semantics:
|
| 25 |
+
|
| 26 |
+
- always returns a valid, not-closed loop
|
| 27 |
+
- not thread-local like asyncio's,
|
| 28 |
+
because we only want one loop for IPython
|
| 29 |
+
- if called from inside a coroutine (e.g. in ipykernel),
|
| 30 |
+
return the running loop
|
| 31 |
+
|
| 32 |
+
.. versionadded:: 8.0
|
| 33 |
+
"""
|
| 34 |
+
try:
|
| 35 |
+
return asyncio.get_running_loop()
|
| 36 |
+
except RuntimeError:
|
| 37 |
+
# not inside a coroutine,
|
| 38 |
+
# track our own global
|
| 39 |
+
pass
|
| 40 |
+
|
| 41 |
+
# not thread-local like asyncio's,
|
| 42 |
+
# because we only track one event loop to run for IPython itself,
|
| 43 |
+
# always in the main thread.
|
| 44 |
+
global _asyncio_event_loop
|
| 45 |
+
if _asyncio_event_loop is None or _asyncio_event_loop.is_closed():
|
| 46 |
+
_asyncio_event_loop = asyncio.new_event_loop()
|
| 47 |
+
return _asyncio_event_loop
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class _AsyncIORunner:
|
| 51 |
+
def __call__(self, coro):
|
| 52 |
+
"""
|
| 53 |
+
Handler for asyncio autoawait
|
| 54 |
+
"""
|
| 55 |
+
return get_asyncio_loop().run_until_complete(coro)
|
| 56 |
+
|
| 57 |
+
def __str__(self):
|
| 58 |
+
return "asyncio"
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
_asyncio_runner = _AsyncIORunner()
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class _AsyncIOProxy:
|
| 65 |
+
"""Proxy-object for an asyncio
|
| 66 |
+
|
| 67 |
+
Any coroutine methods will be wrapped in event_loop.run_
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
def __init__(self, obj, event_loop):
|
| 71 |
+
self._obj = obj
|
| 72 |
+
self._event_loop = event_loop
|
| 73 |
+
|
| 74 |
+
def __repr__(self):
|
| 75 |
+
return f"<_AsyncIOProxy({self._obj!r})>"
|
| 76 |
+
|
| 77 |
+
def __getattr__(self, key):
|
| 78 |
+
attr = getattr(self._obj, key)
|
| 79 |
+
if inspect.iscoroutinefunction(attr):
|
| 80 |
+
# if it's a coroutine method,
|
| 81 |
+
# return a threadsafe wrapper onto the _current_ asyncio loop
|
| 82 |
+
@wraps(attr)
|
| 83 |
+
def _wrapped(*args, **kwargs):
|
| 84 |
+
concurrent_future = asyncio.run_coroutine_threadsafe(
|
| 85 |
+
attr(*args, **kwargs), self._event_loop
|
| 86 |
+
)
|
| 87 |
+
return asyncio.wrap_future(concurrent_future)
|
| 88 |
+
|
| 89 |
+
return _wrapped
|
| 90 |
+
else:
|
| 91 |
+
return attr
|
| 92 |
+
|
| 93 |
+
def __dir__(self):
|
| 94 |
+
return dir(self._obj)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _curio_runner(coroutine):
|
| 98 |
+
"""
|
| 99 |
+
handler for curio autoawait
|
| 100 |
+
"""
|
| 101 |
+
import curio
|
| 102 |
+
|
| 103 |
+
return curio.run(coroutine)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def _trio_runner(async_fn):
|
| 107 |
+
import trio
|
| 108 |
+
|
| 109 |
+
async def loc(coro):
|
| 110 |
+
"""
|
| 111 |
+
We need the dummy no-op async def to protect from
|
| 112 |
+
trio's internal. See https://github.com/python-trio/trio/issues/89
|
| 113 |
+
"""
|
| 114 |
+
return await coro
|
| 115 |
+
|
| 116 |
+
return trio.run(loc, async_fn)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def _pseudo_sync_runner(coro):
|
| 120 |
+
"""
|
| 121 |
+
A runner that does not really allow async execution, and just advance the coroutine.
|
| 122 |
+
|
| 123 |
+
See discussion in https://github.com/python-trio/trio/issues/608,
|
| 124 |
+
|
| 125 |
+
Credit to Nathaniel Smith
|
| 126 |
+
"""
|
| 127 |
+
try:
|
| 128 |
+
coro.send(None)
|
| 129 |
+
except StopIteration as exc:
|
| 130 |
+
return exc.value
|
| 131 |
+
else:
|
| 132 |
+
# TODO: do not raise but return an execution result with the right info.
|
| 133 |
+
raise RuntimeError(
|
| 134 |
+
"{coro_name!r} needs a real async loop".format(coro_name=coro.__name__)
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _should_be_async(cell: str) -> bool:
|
| 139 |
+
"""Detect if a block of code needs to be wrapped in an `async def`
|
| 140 |
+
|
| 141 |
+
If the code block has a top-level return statement or is otherwise
|
| 142 |
+
invalid, `False` will be returned.
|
| 143 |
+
"""
|
| 144 |
+
try:
|
| 145 |
+
code = compile(
|
| 146 |
+
cell, "<>", "exec", flags=getattr(ast, "PyCF_ALLOW_TOP_LEVEL_AWAIT", 0x0)
|
| 147 |
+
)
|
| 148 |
+
return inspect.CO_COROUTINE & code.co_flags == inspect.CO_COROUTINE
|
| 149 |
+
except (SyntaxError, ValueError, MemoryError):
|
| 150 |
+
return False
|
lib/python3.12/site-packages/IPython/core/autocall.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# encoding: utf-8
|
| 2 |
+
"""
|
| 3 |
+
Autocall capabilities for IPython.core.
|
| 4 |
+
|
| 5 |
+
Authors:
|
| 6 |
+
|
| 7 |
+
* Brian Granger
|
| 8 |
+
* Fernando Perez
|
| 9 |
+
* Thomas Kluyver
|
| 10 |
+
|
| 11 |
+
Notes
|
| 12 |
+
-----
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
#-----------------------------------------------------------------------------
|
| 16 |
+
# Copyright (C) 2008-2011 The IPython Development Team
|
| 17 |
+
#
|
| 18 |
+
# Distributed under the terms of the BSD License. The full license is in
|
| 19 |
+
# the file COPYING, distributed as part of this software.
|
| 20 |
+
#-----------------------------------------------------------------------------
|
| 21 |
+
|
| 22 |
+
#-----------------------------------------------------------------------------
|
| 23 |
+
# Imports
|
| 24 |
+
#-----------------------------------------------------------------------------
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
#-----------------------------------------------------------------------------
|
| 28 |
+
# Code
|
| 29 |
+
#-----------------------------------------------------------------------------
|
| 30 |
+
|
| 31 |
+
class IPyAutocall:
|
| 32 |
+
""" Instances of this class are always autocalled
|
| 33 |
+
|
| 34 |
+
This happens regardless of 'autocall' variable state. Use this to
|
| 35 |
+
develop macro-like mechanisms.
|
| 36 |
+
"""
|
| 37 |
+
_ip = None
|
| 38 |
+
rewrite = True
|
| 39 |
+
def __init__(self, ip=None):
|
| 40 |
+
self._ip = ip
|
| 41 |
+
|
| 42 |
+
def set_ip(self, ip):
|
| 43 |
+
"""Will be used to set _ip point to current ipython instance b/f call
|
| 44 |
+
|
| 45 |
+
Override this method if you don't want this to happen.
|
| 46 |
+
|
| 47 |
+
"""
|
| 48 |
+
self._ip = ip
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class ExitAutocall(IPyAutocall):
|
| 52 |
+
"""An autocallable object which will be added to the user namespace so that
|
| 53 |
+
exit, exit(), quit or quit() are all valid ways to close the shell."""
|
| 54 |
+
rewrite = False
|
| 55 |
+
|
| 56 |
+
def __call__(self):
|
| 57 |
+
self._ip.ask_exit()
|
| 58 |
+
|
| 59 |
+
class ZMQExitAutocall(ExitAutocall):
|
| 60 |
+
"""Exit IPython. Autocallable, so it needn't be explicitly called.
|
| 61 |
+
|
| 62 |
+
Parameters
|
| 63 |
+
----------
|
| 64 |
+
keep_kernel : bool
|
| 65 |
+
If True, leave the kernel alive. Otherwise, tell the kernel to exit too
|
| 66 |
+
(default).
|
| 67 |
+
"""
|
| 68 |
+
def __call__(self, keep_kernel=False):
|
| 69 |
+
self._ip.keepkernel_on_exit = keep_kernel
|
| 70 |
+
self._ip.ask_exit()
|
lib/python3.12/site-packages/IPython/core/builtin_trap.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A context manager for managing things injected into :mod:`builtins`.
|
| 3 |
+
"""
|
| 4 |
+
# Copyright (c) IPython Development Team.
|
| 5 |
+
# Distributed under the terms of the Modified BSD License.
|
| 6 |
+
import builtins as builtin_mod
|
| 7 |
+
|
| 8 |
+
from traitlets.config.configurable import Configurable
|
| 9 |
+
|
| 10 |
+
from traitlets import Instance
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class __BuiltinUndefined:
|
| 14 |
+
pass
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
BuiltinUndefined = __BuiltinUndefined()
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class __HideBuiltin:
|
| 21 |
+
pass
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
HideBuiltin = __HideBuiltin()
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class BuiltinTrap(Configurable):
|
| 28 |
+
|
| 29 |
+
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
|
| 30 |
+
allow_none=True)
|
| 31 |
+
|
| 32 |
+
def __init__(self, shell=None):
|
| 33 |
+
super(BuiltinTrap, self).__init__(shell=shell, config=None)
|
| 34 |
+
self._orig_builtins = {}
|
| 35 |
+
# We define this to track if a single BuiltinTrap is nested.
|
| 36 |
+
# Only turn off the trap when the outermost call to __exit__ is made.
|
| 37 |
+
self._nested_level = 0
|
| 38 |
+
self.shell = shell
|
| 39 |
+
# builtins we always add - if set to HideBuiltin, they will just
|
| 40 |
+
# be removed instead of being replaced by something else
|
| 41 |
+
self.auto_builtins = {'exit': HideBuiltin,
|
| 42 |
+
'quit': HideBuiltin,
|
| 43 |
+
'get_ipython': self.shell.get_ipython,
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
def __enter__(self):
|
| 47 |
+
if self._nested_level == 0:
|
| 48 |
+
self.activate()
|
| 49 |
+
self._nested_level += 1
|
| 50 |
+
# I return self, so callers can use add_builtin in a with clause.
|
| 51 |
+
return self
|
| 52 |
+
|
| 53 |
+
def __exit__(self, type, value, traceback):
|
| 54 |
+
if self._nested_level == 1:
|
| 55 |
+
self.deactivate()
|
| 56 |
+
self._nested_level -= 1
|
| 57 |
+
# Returning False will cause exceptions to propagate
|
| 58 |
+
return False
|
| 59 |
+
|
| 60 |
+
def add_builtin(self, key, value):
|
| 61 |
+
"""Add a builtin and save the original."""
|
| 62 |
+
bdict = builtin_mod.__dict__
|
| 63 |
+
orig = bdict.get(key, BuiltinUndefined)
|
| 64 |
+
if value is HideBuiltin:
|
| 65 |
+
if orig is not BuiltinUndefined: #same as 'key in bdict'
|
| 66 |
+
self._orig_builtins[key] = orig
|
| 67 |
+
del bdict[key]
|
| 68 |
+
else:
|
| 69 |
+
self._orig_builtins[key] = orig
|
| 70 |
+
bdict[key] = value
|
| 71 |
+
|
| 72 |
+
def remove_builtin(self, key, orig):
|
| 73 |
+
"""Remove an added builtin and re-set the original."""
|
| 74 |
+
if orig is BuiltinUndefined:
|
| 75 |
+
del builtin_mod.__dict__[key]
|
| 76 |
+
else:
|
| 77 |
+
builtin_mod.__dict__[key] = orig
|
| 78 |
+
|
| 79 |
+
def activate(self):
|
| 80 |
+
"""Store ipython references in the __builtin__ namespace."""
|
| 81 |
+
|
| 82 |
+
add_builtin = self.add_builtin
|
| 83 |
+
for name, func in self.auto_builtins.items():
|
| 84 |
+
add_builtin(name, func)
|
| 85 |
+
|
| 86 |
+
def deactivate(self):
|
| 87 |
+
"""Remove any builtins which might have been added by add_builtins, or
|
| 88 |
+
restore overwritten ones to their previous values."""
|
| 89 |
+
remove_builtin = self.remove_builtin
|
| 90 |
+
for key, val in self._orig_builtins.items():
|
| 91 |
+
remove_builtin(key, val)
|
| 92 |
+
self._orig_builtins.clear()
|
| 93 |
+
self._builtins_added = False
|
lib/python3.12/site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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Pdb debugger class.
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
This is an extension to PDB which adds a number of new features.
|
| 6 |
+
Note that there is also the `IPython.terminal.debugger` class which provides UI
|
| 7 |
+
improvements.
|
| 8 |
+
|
| 9 |
+
We also strongly recommend to use this via the `ipdb` package, which provides
|
| 10 |
+
extra configuration options.
|
| 11 |
+
|
| 12 |
+
Among other things, this subclass of PDB:
|
| 13 |
+
- supports many IPython magics like pdef/psource
|
| 14 |
+
- hide frames in tracebacks based on `__tracebackhide__`
|
| 15 |
+
- allows to skip frames based on `__debuggerskip__`
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
Global Configuration
|
| 19 |
+
--------------------
|
| 20 |
+
|
| 21 |
+
The IPython debugger will by read the global ``~/.pdbrc`` file.
|
| 22 |
+
That is to say you can list all commands supported by ipdb in your `~/.pdbrc`
|
| 23 |
+
configuration file, to globally configure pdb.
|
| 24 |
+
|
| 25 |
+
Example::
|
| 26 |
+
|
| 27 |
+
# ~/.pdbrc
|
| 28 |
+
skip_predicates debuggerskip false
|
| 29 |
+
skip_hidden false
|
| 30 |
+
context 25
|
| 31 |
+
|
| 32 |
+
Features
|
| 33 |
+
--------
|
| 34 |
+
|
| 35 |
+
The IPython debugger can hide and skip frames when printing or moving through
|
| 36 |
+
the stack. This can have a performance impact, so can be configures.
|
| 37 |
+
|
| 38 |
+
The skipping and hiding frames are configurable via the `skip_predicates`
|
| 39 |
+
command.
|
| 40 |
+
|
| 41 |
+
By default, frames from readonly files will be hidden, frames containing
|
| 42 |
+
``__tracebackhide__ = True`` will be hidden.
|
| 43 |
+
|
| 44 |
+
Frames containing ``__debuggerskip__`` will be stepped over, frames whose parent
|
| 45 |
+
frames value of ``__debuggerskip__`` is ``True`` will also be skipped.
|
| 46 |
+
|
| 47 |
+
>>> def helpers_helper():
|
| 48 |
+
... pass
|
| 49 |
+
...
|
| 50 |
+
... def helper_1():
|
| 51 |
+
... print("don't step in me")
|
| 52 |
+
... helpers_helpers() # will be stepped over unless breakpoint set.
|
| 53 |
+
...
|
| 54 |
+
...
|
| 55 |
+
... def helper_2():
|
| 56 |
+
... print("in me neither")
|
| 57 |
+
...
|
| 58 |
+
|
| 59 |
+
One can define a decorator that wraps a function between the two helpers:
|
| 60 |
+
|
| 61 |
+
>>> def pdb_skipped_decorator(function):
|
| 62 |
+
...
|
| 63 |
+
...
|
| 64 |
+
... def wrapped_fn(*args, **kwargs):
|
| 65 |
+
... __debuggerskip__ = True
|
| 66 |
+
... helper_1()
|
| 67 |
+
... __debuggerskip__ = False
|
| 68 |
+
... result = function(*args, **kwargs)
|
| 69 |
+
... __debuggerskip__ = True
|
| 70 |
+
... helper_2()
|
| 71 |
+
... # setting __debuggerskip__ to False again is not necessary
|
| 72 |
+
... return result
|
| 73 |
+
...
|
| 74 |
+
... return wrapped_fn
|
| 75 |
+
|
| 76 |
+
When decorating a function, ipdb will directly step into ``bar()`` by
|
| 77 |
+
default:
|
| 78 |
+
|
| 79 |
+
>>> @foo_decorator
|
| 80 |
+
... def bar(x, y):
|
| 81 |
+
... return x * y
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
You can toggle the behavior with
|
| 85 |
+
|
| 86 |
+
ipdb> skip_predicates debuggerskip false
|
| 87 |
+
|
| 88 |
+
or configure it in your ``.pdbrc``
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
License
|
| 93 |
+
-------
|
| 94 |
+
|
| 95 |
+
Modified from the standard pdb.Pdb class to avoid including readline, so that
|
| 96 |
+
the command line completion of other programs which include this isn't
|
| 97 |
+
damaged.
|
| 98 |
+
|
| 99 |
+
In the future, this class will be expanded with improvements over the standard
|
| 100 |
+
pdb.
|
| 101 |
+
|
| 102 |
+
The original code in this file is mainly lifted out of cmd.py in Python 2.2,
|
| 103 |
+
with minor changes. Licensing should therefore be under the standard Python
|
| 104 |
+
terms. For details on the PSF (Python Software Foundation) standard license,
|
| 105 |
+
see:
|
| 106 |
+
|
| 107 |
+
https://docs.python.org/2/license.html
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
All the changes since then are under the same license as IPython.
|
| 111 |
+
|
| 112 |
+
"""
|
| 113 |
+
|
| 114 |
+
# *****************************************************************************
|
| 115 |
+
#
|
| 116 |
+
# This file is licensed under the PSF license.
|
| 117 |
+
#
|
| 118 |
+
# Copyright (C) 2001 Python Software Foundation, www.python.org
|
| 119 |
+
# Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
|
| 120 |
+
#
|
| 121 |
+
#
|
| 122 |
+
# *****************************************************************************
|
| 123 |
+
|
| 124 |
+
from __future__ import annotations
|
| 125 |
+
|
| 126 |
+
import inspect
|
| 127 |
+
import linecache
|
| 128 |
+
import os
|
| 129 |
+
import re
|
| 130 |
+
import sys
|
| 131 |
+
import warnings
|
| 132 |
+
from contextlib import contextmanager
|
| 133 |
+
from functools import lru_cache
|
| 134 |
+
|
| 135 |
+
from IPython import get_ipython
|
| 136 |
+
from IPython.core.debugger_backport import PdbClosureBackport
|
| 137 |
+
from IPython.utils import PyColorize
|
| 138 |
+
from IPython.utils.PyColorize import TokenStream
|
| 139 |
+
|
| 140 |
+
from typing import TYPE_CHECKING
|
| 141 |
+
from types import FrameType
|
| 142 |
+
|
| 143 |
+
# We have to check this directly from sys.argv, config struct not yet available
|
| 144 |
+
from pdb import Pdb as _OldPdb
|
| 145 |
+
from pygments.token import Token
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
if sys.version_info < (3, 13):
|
| 149 |
+
|
| 150 |
+
class OldPdb(PdbClosureBackport, _OldPdb):
|
| 151 |
+
pass
|
| 152 |
+
|
| 153 |
+
else:
|
| 154 |
+
OldPdb = _OldPdb
|
| 155 |
+
|
| 156 |
+
if TYPE_CHECKING:
|
| 157 |
+
# otherwise circular import
|
| 158 |
+
from IPython.core.interactiveshell import InteractiveShell
|
| 159 |
+
|
| 160 |
+
# skip module docstests
|
| 161 |
+
__skip_doctest__ = True
|
| 162 |
+
|
| 163 |
+
prompt = "ipdb> "
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
# Allow the set_trace code to operate outside of an ipython instance, even if
|
| 167 |
+
# it does so with some limitations. The rest of this support is implemented in
|
| 168 |
+
# the Tracer constructor.
|
| 169 |
+
|
| 170 |
+
DEBUGGERSKIP = "__debuggerskip__"
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
# this has been implemented in Pdb in Python 3.13 (https://github.com/python/cpython/pull/106676
|
| 174 |
+
# on lower python versions, we backported the feature.
|
| 175 |
+
CHAIN_EXCEPTIONS = sys.version_info < (3, 13)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def BdbQuit_excepthook(et, ev, tb, excepthook=None):
|
| 179 |
+
"""Exception hook which handles `BdbQuit` exceptions.
|
| 180 |
+
|
| 181 |
+
All other exceptions are processed using the `excepthook`
|
| 182 |
+
parameter.
|
| 183 |
+
"""
|
| 184 |
+
raise ValueError(
|
| 185 |
+
"`BdbQuit_excepthook` is deprecated since version 5.1. It is still around only because it is still imported by ipdb.",
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
RGX_EXTRA_INDENT = re.compile(r"(?<=\n)\s+")
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def strip_indentation(multiline_string):
|
| 193 |
+
return RGX_EXTRA_INDENT.sub("", multiline_string)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
|
| 197 |
+
"""Make new_fn have old_fn's doc string. This is particularly useful
|
| 198 |
+
for the ``do_...`` commands that hook into the help system.
|
| 199 |
+
Adapted from from a comp.lang.python posting
|
| 200 |
+
by Duncan Booth."""
|
| 201 |
+
|
| 202 |
+
def wrapper(*args, **kw):
|
| 203 |
+
return new_fn(*args, **kw)
|
| 204 |
+
|
| 205 |
+
if old_fn.__doc__:
|
| 206 |
+
wrapper.__doc__ = strip_indentation(old_fn.__doc__) + additional_text
|
| 207 |
+
return wrapper
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
class Pdb(OldPdb):
|
| 211 |
+
"""Modified Pdb class, does not load readline.
|
| 212 |
+
|
| 213 |
+
for a standalone version that uses prompt_toolkit, see
|
| 214 |
+
`IPython.terminal.debugger.TerminalPdb` and
|
| 215 |
+
`IPython.terminal.debugger.set_trace()`
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
This debugger can hide and skip frames that are tagged according to some predicates.
|
| 219 |
+
See the `skip_predicates` commands.
|
| 220 |
+
|
| 221 |
+
"""
|
| 222 |
+
|
| 223 |
+
shell: InteractiveShell
|
| 224 |
+
_theme_name: str
|
| 225 |
+
_context: int
|
| 226 |
+
|
| 227 |
+
_chained_exceptions: tuple[Exception, ...]
|
| 228 |
+
_chained_exception_index: int
|
| 229 |
+
|
| 230 |
+
if CHAIN_EXCEPTIONS:
|
| 231 |
+
MAX_CHAINED_EXCEPTION_DEPTH = 999
|
| 232 |
+
|
| 233 |
+
default_predicates = {
|
| 234 |
+
"tbhide": True,
|
| 235 |
+
"readonly": False,
|
| 236 |
+
"ipython_internal": True,
|
| 237 |
+
"debuggerskip": True,
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
def __init__(
|
| 241 |
+
self,
|
| 242 |
+
completekey=None,
|
| 243 |
+
stdin=None,
|
| 244 |
+
stdout=None,
|
| 245 |
+
context: int | None | str = 5,
|
| 246 |
+
**kwargs,
|
| 247 |
+
):
|
| 248 |
+
"""Create a new IPython debugger.
|
| 249 |
+
|
| 250 |
+
Parameters
|
| 251 |
+
----------
|
| 252 |
+
completekey : default None
|
| 253 |
+
Passed to pdb.Pdb.
|
| 254 |
+
stdin : default None
|
| 255 |
+
Passed to pdb.Pdb.
|
| 256 |
+
stdout : default None
|
| 257 |
+
Passed to pdb.Pdb.
|
| 258 |
+
context : int
|
| 259 |
+
Number of lines of source code context to show when
|
| 260 |
+
displaying stacktrace information.
|
| 261 |
+
**kwargs
|
| 262 |
+
Passed to pdb.Pdb.
|
| 263 |
+
|
| 264 |
+
Notes
|
| 265 |
+
-----
|
| 266 |
+
The possibilities are python version dependent, see the python
|
| 267 |
+
docs for more info.
|
| 268 |
+
"""
|
| 269 |
+
# ipdb issue, see https://github.com/ipython/ipython/issues/14811
|
| 270 |
+
if context is None:
|
| 271 |
+
context = 5
|
| 272 |
+
if isinstance(context, str):
|
| 273 |
+
context = int(context)
|
| 274 |
+
self.context = context
|
| 275 |
+
|
| 276 |
+
# `kwargs` ensures full compatibility with stdlib's `pdb.Pdb`.
|
| 277 |
+
OldPdb.__init__(self, completekey, stdin, stdout, **kwargs)
|
| 278 |
+
# Python 3.15+ should define this, so no need to initialize
|
| 279 |
+
# this avoids some getattr(self, 'curframe')
|
| 280 |
+
if sys.version_info < (3, 15):
|
| 281 |
+
self.curframe = None
|
| 282 |
+
|
| 283 |
+
# IPython changes...
|
| 284 |
+
self.shell = get_ipython()
|
| 285 |
+
|
| 286 |
+
if self.shell is None:
|
| 287 |
+
save_main = sys.modules["__main__"]
|
| 288 |
+
# No IPython instance running, we must create one
|
| 289 |
+
from IPython.terminal.interactiveshell import TerminalInteractiveShell
|
| 290 |
+
|
| 291 |
+
self.shell = TerminalInteractiveShell.instance()
|
| 292 |
+
# needed by any code which calls __import__("__main__") after
|
| 293 |
+
# the debugger was entered. See also #9941.
|
| 294 |
+
sys.modules["__main__"] = save_main
|
| 295 |
+
|
| 296 |
+
self.aliases = {}
|
| 297 |
+
|
| 298 |
+
theme_name = self.shell.colors
|
| 299 |
+
assert isinstance(theme_name, str)
|
| 300 |
+
assert theme_name.lower() == theme_name
|
| 301 |
+
|
| 302 |
+
# Add a python parser so we can syntax highlight source while
|
| 303 |
+
# debugging.
|
| 304 |
+
self.parser = PyColorize.Parser(theme_name=theme_name)
|
| 305 |
+
self.set_theme_name(theme_name)
|
| 306 |
+
|
| 307 |
+
# Set the prompt - the default prompt is '(Pdb)'
|
| 308 |
+
self.prompt = prompt
|
| 309 |
+
self.skip_hidden = True
|
| 310 |
+
self.report_skipped = True
|
| 311 |
+
|
| 312 |
+
# list of predicates we use to skip frames
|
| 313 |
+
self._predicates = self.default_predicates
|
| 314 |
+
|
| 315 |
+
if CHAIN_EXCEPTIONS:
|
| 316 |
+
self._chained_exceptions = tuple()
|
| 317 |
+
self._chained_exception_index = 0
|
| 318 |
+
|
| 319 |
+
@property
|
| 320 |
+
def context(self) -> int:
|
| 321 |
+
return self._context
|
| 322 |
+
|
| 323 |
+
@context.setter
|
| 324 |
+
def context(self, value: int | str) -> None:
|
| 325 |
+
# ipdb issue see https://github.com/ipython/ipython/issues/14811
|
| 326 |
+
if not isinstance(value, int):
|
| 327 |
+
value = int(value)
|
| 328 |
+
assert isinstance(value, int)
|
| 329 |
+
assert value >= 0
|
| 330 |
+
self._context = value
|
| 331 |
+
|
| 332 |
+
def set_theme_name(self, name):
|
| 333 |
+
assert name.lower() == name
|
| 334 |
+
assert isinstance(name, str)
|
| 335 |
+
self._theme_name = name
|
| 336 |
+
self.parser.theme_name = name
|
| 337 |
+
|
| 338 |
+
@property
|
| 339 |
+
def theme(self):
|
| 340 |
+
return PyColorize.theme_table[self._theme_name]
|
| 341 |
+
|
| 342 |
+
#
|
| 343 |
+
def set_colors(self, scheme):
|
| 344 |
+
"""Shorthand access to the color table scheme selector method."""
|
| 345 |
+
warnings.warn(
|
| 346 |
+
"set_colors is deprecated since IPython 9.0, use set_theme_name instead",
|
| 347 |
+
DeprecationWarning,
|
| 348 |
+
stacklevel=2,
|
| 349 |
+
)
|
| 350 |
+
assert scheme == scheme.lower()
|
| 351 |
+
self._theme_name = scheme.lower()
|
| 352 |
+
self.parser.theme_name = scheme.lower()
|
| 353 |
+
|
| 354 |
+
def set_trace(self, frame=None):
|
| 355 |
+
if frame is None:
|
| 356 |
+
frame = sys._getframe().f_back
|
| 357 |
+
self.initial_frame = frame
|
| 358 |
+
return super().set_trace(frame)
|
| 359 |
+
|
| 360 |
+
def get_stack(self, *args, **kwargs):
|
| 361 |
+
stack, pos = super().get_stack(*args, **kwargs)
|
| 362 |
+
if len(stack) >= 0 and self._is_internal_frame(stack[0][0]):
|
| 363 |
+
stack.pop(0)
|
| 364 |
+
pos -= 1
|
| 365 |
+
return stack, pos
|
| 366 |
+
|
| 367 |
+
def _is_internal_frame(self, frame):
|
| 368 |
+
"""Determine if this frame should be skipped as internal"""
|
| 369 |
+
filename = frame.f_code.co_filename
|
| 370 |
+
|
| 371 |
+
# Skip bdb.py runcall and internal operations
|
| 372 |
+
if filename.endswith("bdb.py"):
|
| 373 |
+
func_name = frame.f_code.co_name
|
| 374 |
+
# Skip internal bdb operations but allow breakpoint hits
|
| 375 |
+
if func_name in ("runcall", "run", "runeval"):
|
| 376 |
+
return True
|
| 377 |
+
|
| 378 |
+
return False
|
| 379 |
+
|
| 380 |
+
def _hidden_predicate(self, frame):
|
| 381 |
+
"""
|
| 382 |
+
Given a frame return whether it it should be hidden or not by IPython.
|
| 383 |
+
"""
|
| 384 |
+
|
| 385 |
+
if self._predicates["readonly"]:
|
| 386 |
+
fname = frame.f_code.co_filename
|
| 387 |
+
# we need to check for file existence and interactively define
|
| 388 |
+
# function would otherwise appear as RO.
|
| 389 |
+
if os.path.isfile(fname) and not os.access(fname, os.W_OK):
|
| 390 |
+
return True
|
| 391 |
+
|
| 392 |
+
if self._predicates["tbhide"]:
|
| 393 |
+
if frame in (self.curframe, getattr(self, "initial_frame", None)):
|
| 394 |
+
return False
|
| 395 |
+
frame_locals = self._get_frame_locals(frame)
|
| 396 |
+
if "__tracebackhide__" not in frame_locals:
|
| 397 |
+
return False
|
| 398 |
+
return frame_locals["__tracebackhide__"]
|
| 399 |
+
return False
|
| 400 |
+
|
| 401 |
+
def hidden_frames(self, stack):
|
| 402 |
+
"""
|
| 403 |
+
Given an index in the stack return whether it should be skipped.
|
| 404 |
+
|
| 405 |
+
This is used in up/down and where to skip frames.
|
| 406 |
+
"""
|
| 407 |
+
# The f_locals dictionary is updated from the actual frame
|
| 408 |
+
# locals whenever the .f_locals accessor is called, so we
|
| 409 |
+
# avoid calling it here to preserve self.curframe_locals.
|
| 410 |
+
# Furthermore, there is no good reason to hide the current frame.
|
| 411 |
+
ip_hide = [self._hidden_predicate(s[0]) for s in stack]
|
| 412 |
+
ip_start = [i for i, s in enumerate(ip_hide) if s == "__ipython_bottom__"]
|
| 413 |
+
if ip_start and self._predicates["ipython_internal"]:
|
| 414 |
+
ip_hide = [h if i > ip_start[0] else True for (i, h) in enumerate(ip_hide)]
|
| 415 |
+
return ip_hide
|
| 416 |
+
|
| 417 |
+
if CHAIN_EXCEPTIONS:
|
| 418 |
+
|
| 419 |
+
def _get_tb_and_exceptions(self, tb_or_exc):
|
| 420 |
+
"""
|
| 421 |
+
Given a tracecack or an exception, return a tuple of chained exceptions
|
| 422 |
+
and current traceback to inspect.
|
| 423 |
+
This will deal with selecting the right ``__cause__`` or ``__context__``
|
| 424 |
+
as well as handling cycles, and return a flattened list of exceptions we
|
| 425 |
+
can jump to with do_exceptions.
|
| 426 |
+
"""
|
| 427 |
+
_exceptions = []
|
| 428 |
+
if isinstance(tb_or_exc, BaseException):
|
| 429 |
+
traceback, current = tb_or_exc.__traceback__, tb_or_exc
|
| 430 |
+
|
| 431 |
+
while current is not None:
|
| 432 |
+
if current in _exceptions:
|
| 433 |
+
break
|
| 434 |
+
_exceptions.append(current)
|
| 435 |
+
if current.__cause__ is not None:
|
| 436 |
+
current = current.__cause__
|
| 437 |
+
elif (
|
| 438 |
+
current.__context__ is not None
|
| 439 |
+
and not current.__suppress_context__
|
| 440 |
+
):
|
| 441 |
+
current = current.__context__
|
| 442 |
+
|
| 443 |
+
if len(_exceptions) >= self.MAX_CHAINED_EXCEPTION_DEPTH:
|
| 444 |
+
self.message(
|
| 445 |
+
f"More than {self.MAX_CHAINED_EXCEPTION_DEPTH}"
|
| 446 |
+
" chained exceptions found, not all exceptions"
|
| 447 |
+
"will be browsable with `exceptions`."
|
| 448 |
+
)
|
| 449 |
+
break
|
| 450 |
+
else:
|
| 451 |
+
traceback = tb_or_exc
|
| 452 |
+
return tuple(reversed(_exceptions)), traceback
|
| 453 |
+
|
| 454 |
+
@contextmanager
|
| 455 |
+
def _hold_exceptions(self, exceptions):
|
| 456 |
+
"""
|
| 457 |
+
Context manager to ensure proper cleaning of exceptions references
|
| 458 |
+
When given a chained exception instead of a traceback,
|
| 459 |
+
pdb may hold references to many objects which may leak memory.
|
| 460 |
+
We use this context manager to make sure everything is properly cleaned
|
| 461 |
+
"""
|
| 462 |
+
try:
|
| 463 |
+
self._chained_exceptions = exceptions
|
| 464 |
+
self._chained_exception_index = len(exceptions) - 1
|
| 465 |
+
yield
|
| 466 |
+
finally:
|
| 467 |
+
# we can't put those in forget as otherwise they would
|
| 468 |
+
# be cleared on exception change
|
| 469 |
+
self._chained_exceptions = tuple()
|
| 470 |
+
self._chained_exception_index = 0
|
| 471 |
+
|
| 472 |
+
def do_exceptions(self, arg):
|
| 473 |
+
"""exceptions [number]
|
| 474 |
+
List or change current exception in an exception chain.
|
| 475 |
+
Without arguments, list all the current exception in the exception
|
| 476 |
+
chain. Exceptions will be numbered, with the current exception indicated
|
| 477 |
+
with an arrow.
|
| 478 |
+
If given an integer as argument, switch to the exception at that index.
|
| 479 |
+
"""
|
| 480 |
+
if not self._chained_exceptions:
|
| 481 |
+
self.message(
|
| 482 |
+
"Did not find chained exceptions. To move between"
|
| 483 |
+
" exceptions, pdb/post_mortem must be given an exception"
|
| 484 |
+
" object rather than a traceback."
|
| 485 |
+
)
|
| 486 |
+
return
|
| 487 |
+
if not arg:
|
| 488 |
+
for ix, exc in enumerate(self._chained_exceptions):
|
| 489 |
+
prompt = ">" if ix == self._chained_exception_index else " "
|
| 490 |
+
rep = repr(exc)
|
| 491 |
+
if len(rep) > 80:
|
| 492 |
+
rep = rep[:77] + "..."
|
| 493 |
+
indicator = (
|
| 494 |
+
" -"
|
| 495 |
+
if self._chained_exceptions[ix].__traceback__ is None
|
| 496 |
+
else f"{ix:>3}"
|
| 497 |
+
)
|
| 498 |
+
self.message(f"{prompt} {indicator} {rep}")
|
| 499 |
+
else:
|
| 500 |
+
try:
|
| 501 |
+
number = int(arg)
|
| 502 |
+
except ValueError:
|
| 503 |
+
self.error("Argument must be an integer")
|
| 504 |
+
return
|
| 505 |
+
if 0 <= number < len(self._chained_exceptions):
|
| 506 |
+
if self._chained_exceptions[number].__traceback__ is None:
|
| 507 |
+
self.error(
|
| 508 |
+
"This exception does not have a traceback, cannot jump to it"
|
| 509 |
+
)
|
| 510 |
+
return
|
| 511 |
+
|
| 512 |
+
self._chained_exception_index = number
|
| 513 |
+
self.setup(None, self._chained_exceptions[number].__traceback__)
|
| 514 |
+
self.print_stack_entry(self.stack[self.curindex])
|
| 515 |
+
else:
|
| 516 |
+
self.error("No exception with that number")
|
| 517 |
+
|
| 518 |
+
def interaction(self, frame, tb_or_exc):
|
| 519 |
+
try:
|
| 520 |
+
if CHAIN_EXCEPTIONS:
|
| 521 |
+
# this context manager is part of interaction in 3.13
|
| 522 |
+
_chained_exceptions, tb = self._get_tb_and_exceptions(tb_or_exc)
|
| 523 |
+
if isinstance(tb_or_exc, BaseException):
|
| 524 |
+
assert tb is not None, "main exception must have a traceback"
|
| 525 |
+
with self._hold_exceptions(_chained_exceptions):
|
| 526 |
+
OldPdb.interaction(self, frame, tb)
|
| 527 |
+
else:
|
| 528 |
+
OldPdb.interaction(self, frame, tb_or_exc)
|
| 529 |
+
|
| 530 |
+
except KeyboardInterrupt:
|
| 531 |
+
self.stdout.write("\n" + self.shell.get_exception_only())
|
| 532 |
+
|
| 533 |
+
def precmd(self, line):
|
| 534 |
+
"""Perform useful escapes on the command before it is executed."""
|
| 535 |
+
|
| 536 |
+
if line.endswith("??"):
|
| 537 |
+
line = "pinfo2 " + line[:-2]
|
| 538 |
+
elif line.endswith("?"):
|
| 539 |
+
line = "pinfo " + line[:-1]
|
| 540 |
+
|
| 541 |
+
line = super().precmd(line)
|
| 542 |
+
|
| 543 |
+
return line
|
| 544 |
+
|
| 545 |
+
def new_do_quit(self, arg):
|
| 546 |
+
return OldPdb.do_quit(self, arg)
|
| 547 |
+
|
| 548 |
+
do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
|
| 549 |
+
|
| 550 |
+
def print_stack_trace(self, context: int | None = None):
|
| 551 |
+
if context is None:
|
| 552 |
+
context = self.context
|
| 553 |
+
try:
|
| 554 |
+
skipped = 0
|
| 555 |
+
to_print = ""
|
| 556 |
+
for hidden, frame_lineno in zip(self.hidden_frames(self.stack), self.stack):
|
| 557 |
+
if hidden and self.skip_hidden:
|
| 558 |
+
skipped += 1
|
| 559 |
+
continue
|
| 560 |
+
if skipped:
|
| 561 |
+
to_print += self.theme.format(
|
| 562 |
+
[
|
| 563 |
+
(
|
| 564 |
+
Token.ExcName,
|
| 565 |
+
f" [... skipping {skipped} hidden frame(s)]",
|
| 566 |
+
),
|
| 567 |
+
(Token, "\n"),
|
| 568 |
+
]
|
| 569 |
+
)
|
| 570 |
+
|
| 571 |
+
skipped = 0
|
| 572 |
+
to_print += self.format_stack_entry(frame_lineno)
|
| 573 |
+
if skipped:
|
| 574 |
+
to_print += self.theme.format(
|
| 575 |
+
[
|
| 576 |
+
(
|
| 577 |
+
Token.ExcName,
|
| 578 |
+
f" [... skipping {skipped} hidden frame(s)]",
|
| 579 |
+
),
|
| 580 |
+
(Token, "\n"),
|
| 581 |
+
]
|
| 582 |
+
)
|
| 583 |
+
print(to_print, file=self.stdout)
|
| 584 |
+
except KeyboardInterrupt:
|
| 585 |
+
pass
|
| 586 |
+
|
| 587 |
+
def print_stack_entry(
|
| 588 |
+
self, frame_lineno: tuple[FrameType, int], prompt_prefix: str = "\n-> "
|
| 589 |
+
) -> None:
|
| 590 |
+
"""
|
| 591 |
+
Overwrite print_stack_entry from superclass (PDB)
|
| 592 |
+
"""
|
| 593 |
+
print(self.format_stack_entry(frame_lineno, ""), file=self.stdout)
|
| 594 |
+
|
| 595 |
+
frame, lineno = frame_lineno
|
| 596 |
+
filename = frame.f_code.co_filename
|
| 597 |
+
self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
|
| 598 |
+
|
| 599 |
+
def _get_frame_locals(self, frame):
|
| 600 |
+
""" "
|
| 601 |
+
Accessing f_local of current frame reset the namespace, so we want to avoid
|
| 602 |
+
that or the following can happen
|
| 603 |
+
|
| 604 |
+
ipdb> foo
|
| 605 |
+
"old"
|
| 606 |
+
ipdb> foo = "new"
|
| 607 |
+
ipdb> foo
|
| 608 |
+
"new"
|
| 609 |
+
ipdb> where
|
| 610 |
+
ipdb> foo
|
| 611 |
+
"old"
|
| 612 |
+
|
| 613 |
+
So if frame is self.current_frame we instead return self.curframe_locals
|
| 614 |
+
|
| 615 |
+
"""
|
| 616 |
+
if frame is self.curframe:
|
| 617 |
+
return self.curframe_locals
|
| 618 |
+
else:
|
| 619 |
+
return frame.f_locals
|
| 620 |
+
|
| 621 |
+
def format_stack_entry(
|
| 622 |
+
self,
|
| 623 |
+
frame_lineno: tuple[FrameType, int], # type: ignore[override] # stubs are wrong
|
| 624 |
+
lprefix: str = ": ",
|
| 625 |
+
) -> str:
|
| 626 |
+
"""
|
| 627 |
+
overwrite from super class so must -> str
|
| 628 |
+
"""
|
| 629 |
+
context = self.context
|
| 630 |
+
try:
|
| 631 |
+
context = int(context)
|
| 632 |
+
if context <= 0:
|
| 633 |
+
print("Context must be a positive integer", file=self.stdout)
|
| 634 |
+
except (TypeError, ValueError):
|
| 635 |
+
print("Context must be a positive integer", file=self.stdout)
|
| 636 |
+
|
| 637 |
+
import reprlib
|
| 638 |
+
|
| 639 |
+
ret_tok = []
|
| 640 |
+
|
| 641 |
+
frame, lineno = frame_lineno
|
| 642 |
+
|
| 643 |
+
return_value = ""
|
| 644 |
+
loc_frame = self._get_frame_locals(frame)
|
| 645 |
+
if "__return__" in loc_frame:
|
| 646 |
+
rv = loc_frame["__return__"]
|
| 647 |
+
# return_value += '->'
|
| 648 |
+
return_value += reprlib.repr(rv) + "\n"
|
| 649 |
+
ret_tok.extend([(Token, return_value)])
|
| 650 |
+
|
| 651 |
+
# s = filename + '(' + `lineno` + ')'
|
| 652 |
+
filename = self.canonic(frame.f_code.co_filename)
|
| 653 |
+
link_tok = (Token.FilenameEm, filename)
|
| 654 |
+
|
| 655 |
+
if frame.f_code.co_name:
|
| 656 |
+
func = frame.f_code.co_name
|
| 657 |
+
else:
|
| 658 |
+
func = "<lambda>"
|
| 659 |
+
|
| 660 |
+
call_toks = []
|
| 661 |
+
if func != "?":
|
| 662 |
+
if "__args__" in loc_frame:
|
| 663 |
+
args = reprlib.repr(loc_frame["__args__"])
|
| 664 |
+
else:
|
| 665 |
+
args = "()"
|
| 666 |
+
call_toks = [(Token.VName, func), (Token.ValEm, args)]
|
| 667 |
+
|
| 668 |
+
# The level info should be generated in the same format pdb uses, to
|
| 669 |
+
# avoid breaking the pdbtrack functionality of python-mode in *emacs.
|
| 670 |
+
if frame is self.curframe:
|
| 671 |
+
ret_tok.append((Token.CurrentFrame, self.theme.make_arrow(2)))
|
| 672 |
+
else:
|
| 673 |
+
ret_tok.append((Token, " "))
|
| 674 |
+
|
| 675 |
+
ret_tok.extend(
|
| 676 |
+
[
|
| 677 |
+
link_tok,
|
| 678 |
+
(Token, "("),
|
| 679 |
+
(Token.Lineno, str(lineno)),
|
| 680 |
+
(Token, ")"),
|
| 681 |
+
*call_toks,
|
| 682 |
+
(Token, "\n"),
|
| 683 |
+
]
|
| 684 |
+
)
|
| 685 |
+
|
| 686 |
+
start = lineno - 1 - context // 2
|
| 687 |
+
lines = linecache.getlines(filename)
|
| 688 |
+
start = min(start, len(lines) - context)
|
| 689 |
+
start = max(start, 0)
|
| 690 |
+
lines = lines[start : start + context]
|
| 691 |
+
|
| 692 |
+
for i, line in enumerate(lines):
|
| 693 |
+
show_arrow = start + 1 + i == lineno
|
| 694 |
+
|
| 695 |
+
bp, num, colored_line = self.__line_content(
|
| 696 |
+
filename,
|
| 697 |
+
start + 1 + i,
|
| 698 |
+
line,
|
| 699 |
+
arrow=show_arrow,
|
| 700 |
+
)
|
| 701 |
+
if frame is self.curframe or show_arrow:
|
| 702 |
+
rlt = [
|
| 703 |
+
bp,
|
| 704 |
+
(Token.LinenoEm, num),
|
| 705 |
+
(Token, " "),
|
| 706 |
+
# TODO: investigate Toke.Line here, likely LineEm,
|
| 707 |
+
# Token is problematic here as line is already colored, a
|
| 708 |
+
# and this changes the full style of the colored line.
|
| 709 |
+
# ideally, __line_content returns the token and we modify the style.
|
| 710 |
+
(Token, colored_line),
|
| 711 |
+
]
|
| 712 |
+
else:
|
| 713 |
+
rlt = [
|
| 714 |
+
bp,
|
| 715 |
+
(Token.Lineno, num),
|
| 716 |
+
(Token, " "),
|
| 717 |
+
# TODO: investigate Toke.Line here, likely Line
|
| 718 |
+
# Token is problematic here as line is already colored, a
|
| 719 |
+
# and this changes the full style of the colored line.
|
| 720 |
+
# ideally, __line_content returns the token and we modify the style.
|
| 721 |
+
(Token.Line, colored_line),
|
| 722 |
+
]
|
| 723 |
+
ret_tok.extend(rlt)
|
| 724 |
+
|
| 725 |
+
return self.theme.format(ret_tok)
|
| 726 |
+
|
| 727 |
+
def __line_content(
|
| 728 |
+
self, filename: str, lineno: int, line: str, arrow: bool = False
|
| 729 |
+
):
|
| 730 |
+
bp_mark = ""
|
| 731 |
+
BreakpointToken = Token.Breakpoint
|
| 732 |
+
|
| 733 |
+
new_line, err = self.parser.format2(line, "str")
|
| 734 |
+
if not err:
|
| 735 |
+
assert new_line is not None
|
| 736 |
+
line = new_line
|
| 737 |
+
|
| 738 |
+
bp = None
|
| 739 |
+
if lineno in self.get_file_breaks(filename):
|
| 740 |
+
bps = self.get_breaks(filename, lineno)
|
| 741 |
+
bp = bps[-1]
|
| 742 |
+
|
| 743 |
+
if bp:
|
| 744 |
+
bp_mark = str(bp.number)
|
| 745 |
+
BreakpointToken = Token.Breakpoint.Enabled
|
| 746 |
+
if not bp.enabled:
|
| 747 |
+
BreakpointToken = Token.Breakpoint.Disabled
|
| 748 |
+
numbers_width = 7
|
| 749 |
+
if arrow:
|
| 750 |
+
# This is the line with the error
|
| 751 |
+
pad = numbers_width - len(str(lineno)) - len(bp_mark)
|
| 752 |
+
num = "%s%s" % (self.theme.make_arrow(pad), str(lineno))
|
| 753 |
+
else:
|
| 754 |
+
num = "%*s" % (numbers_width - len(bp_mark), str(lineno))
|
| 755 |
+
bp_str = (BreakpointToken, bp_mark)
|
| 756 |
+
return (bp_str, num, line)
|
| 757 |
+
|
| 758 |
+
def print_list_lines(self, filename: str, first: int, last: int) -> None:
|
| 759 |
+
"""The printing (as opposed to the parsing part of a 'list'
|
| 760 |
+
command."""
|
| 761 |
+
toks: TokenStream = []
|
| 762 |
+
try:
|
| 763 |
+
if filename == "<string>" and hasattr(self, "_exec_filename"):
|
| 764 |
+
filename = self._exec_filename
|
| 765 |
+
|
| 766 |
+
for lineno in range(first, last + 1):
|
| 767 |
+
line = linecache.getline(filename, lineno)
|
| 768 |
+
if not line:
|
| 769 |
+
break
|
| 770 |
+
|
| 771 |
+
assert self.curframe is not None
|
| 772 |
+
|
| 773 |
+
if lineno == self.curframe.f_lineno:
|
| 774 |
+
bp, num, colored_line = self.__line_content(
|
| 775 |
+
filename, lineno, line, arrow=True
|
| 776 |
+
)
|
| 777 |
+
toks.extend(
|
| 778 |
+
[
|
| 779 |
+
bp,
|
| 780 |
+
(Token.LinenoEm, num),
|
| 781 |
+
(Token, " "),
|
| 782 |
+
# TODO: investigate Token.Line here
|
| 783 |
+
(Token, colored_line),
|
| 784 |
+
]
|
| 785 |
+
)
|
| 786 |
+
else:
|
| 787 |
+
bp, num, colored_line = self.__line_content(
|
| 788 |
+
filename, lineno, line, arrow=False
|
| 789 |
+
)
|
| 790 |
+
toks.extend(
|
| 791 |
+
[
|
| 792 |
+
bp,
|
| 793 |
+
(Token.Lineno, num),
|
| 794 |
+
(Token, " "),
|
| 795 |
+
(Token, colored_line),
|
| 796 |
+
]
|
| 797 |
+
)
|
| 798 |
+
|
| 799 |
+
self.lineno = lineno
|
| 800 |
+
|
| 801 |
+
print(self.theme.format(toks), file=self.stdout)
|
| 802 |
+
|
| 803 |
+
except KeyboardInterrupt:
|
| 804 |
+
pass
|
| 805 |
+
|
| 806 |
+
def do_skip_predicates(self, args):
|
| 807 |
+
"""
|
| 808 |
+
Turn on/off individual predicates as to whether a frame should be hidden/skip.
|
| 809 |
+
|
| 810 |
+
The global option to skip (or not) hidden frames is set with skip_hidden
|
| 811 |
+
|
| 812 |
+
To change the value of a predicate
|
| 813 |
+
|
| 814 |
+
skip_predicates key [true|false]
|
| 815 |
+
|
| 816 |
+
Call without arguments to see the current values.
|
| 817 |
+
|
| 818 |
+
To permanently change the value of an option add the corresponding
|
| 819 |
+
command to your ``~/.pdbrc`` file. If you are programmatically using the
|
| 820 |
+
Pdb instance you can also change the ``default_predicates`` class
|
| 821 |
+
attribute.
|
| 822 |
+
"""
|
| 823 |
+
if not args.strip():
|
| 824 |
+
print("current predicates:")
|
| 825 |
+
for p, v in self._predicates.items():
|
| 826 |
+
print(" ", p, ":", v)
|
| 827 |
+
return
|
| 828 |
+
type_value = args.strip().split(" ")
|
| 829 |
+
if len(type_value) != 2:
|
| 830 |
+
print(
|
| 831 |
+
f"Usage: skip_predicates <type> <value>, with <type> one of {set(self._predicates.keys())}"
|
| 832 |
+
)
|
| 833 |
+
return
|
| 834 |
+
|
| 835 |
+
type_, value = type_value
|
| 836 |
+
if type_ not in self._predicates:
|
| 837 |
+
print(f"{type_!r} not in {set(self._predicates.keys())}")
|
| 838 |
+
return
|
| 839 |
+
if value.lower() not in ("true", "yes", "1", "no", "false", "0"):
|
| 840 |
+
print(
|
| 841 |
+
f"{value!r} is invalid - use one of ('true', 'yes', '1', 'no', 'false', '0')"
|
| 842 |
+
)
|
| 843 |
+
return
|
| 844 |
+
|
| 845 |
+
self._predicates[type_] = value.lower() in ("true", "yes", "1")
|
| 846 |
+
if not any(self._predicates.values()):
|
| 847 |
+
print(
|
| 848 |
+
"Warning, all predicates set to False, skip_hidden may not have any effects."
|
| 849 |
+
)
|
| 850 |
+
|
| 851 |
+
def do_skip_hidden(self, arg):
|
| 852 |
+
"""
|
| 853 |
+
Change whether or not we should skip frames with the
|
| 854 |
+
__tracebackhide__ attribute.
|
| 855 |
+
"""
|
| 856 |
+
if not arg.strip():
|
| 857 |
+
print(
|
| 858 |
+
f"skip_hidden = {self.skip_hidden}, use 'yes','no', 'true', or 'false' to change."
|
| 859 |
+
)
|
| 860 |
+
elif arg.strip().lower() in ("true", "yes"):
|
| 861 |
+
self.skip_hidden = True
|
| 862 |
+
elif arg.strip().lower() in ("false", "no"):
|
| 863 |
+
self.skip_hidden = False
|
| 864 |
+
if not any(self._predicates.values()):
|
| 865 |
+
print(
|
| 866 |
+
"Warning, all predicates set to False, skip_hidden may not have any effects."
|
| 867 |
+
)
|
| 868 |
+
|
| 869 |
+
def do_list(self, arg):
|
| 870 |
+
"""Print lines of code from the current stack frame"""
|
| 871 |
+
self.lastcmd = "list"
|
| 872 |
+
last = None
|
| 873 |
+
if arg and arg != ".":
|
| 874 |
+
try:
|
| 875 |
+
x = eval(arg, {}, {})
|
| 876 |
+
if type(x) == type(()):
|
| 877 |
+
first, last = x
|
| 878 |
+
first = int(first)
|
| 879 |
+
last = int(last)
|
| 880 |
+
if last < first:
|
| 881 |
+
# Assume it's a count
|
| 882 |
+
last = first + last
|
| 883 |
+
else:
|
| 884 |
+
first = max(1, int(x) - 5)
|
| 885 |
+
except:
|
| 886 |
+
print("*** Error in argument:", repr(arg), file=self.stdout)
|
| 887 |
+
return
|
| 888 |
+
elif self.lineno is None or arg == ".":
|
| 889 |
+
assert self.curframe is not None
|
| 890 |
+
first = max(1, self.curframe.f_lineno - 5)
|
| 891 |
+
else:
|
| 892 |
+
first = self.lineno + 1
|
| 893 |
+
if last is None:
|
| 894 |
+
last = first + 10
|
| 895 |
+
assert self.curframe is not None
|
| 896 |
+
self.print_list_lines(self.curframe.f_code.co_filename, first, last)
|
| 897 |
+
|
| 898 |
+
lineno = first
|
| 899 |
+
filename = self.curframe.f_code.co_filename
|
| 900 |
+
self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
|
| 901 |
+
|
| 902 |
+
do_l = do_list
|
| 903 |
+
|
| 904 |
+
def getsourcelines(self, obj):
|
| 905 |
+
lines, lineno = inspect.findsource(obj)
|
| 906 |
+
if inspect.isframe(obj) and obj.f_globals is self._get_frame_locals(obj):
|
| 907 |
+
# must be a module frame: do not try to cut a block out of it
|
| 908 |
+
return lines, 1
|
| 909 |
+
elif inspect.ismodule(obj):
|
| 910 |
+
return lines, 1
|
| 911 |
+
return inspect.getblock(lines[lineno:]), lineno + 1
|
| 912 |
+
|
| 913 |
+
def do_longlist(self, arg):
|
| 914 |
+
"""Print lines of code from the current stack frame.
|
| 915 |
+
|
| 916 |
+
Shows more lines than 'list' does.
|
| 917 |
+
"""
|
| 918 |
+
self.lastcmd = "longlist"
|
| 919 |
+
try:
|
| 920 |
+
lines, lineno = self.getsourcelines(self.curframe)
|
| 921 |
+
except OSError as err:
|
| 922 |
+
self.error(str(err))
|
| 923 |
+
return
|
| 924 |
+
last = lineno + len(lines)
|
| 925 |
+
assert self.curframe is not None
|
| 926 |
+
self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
|
| 927 |
+
|
| 928 |
+
do_ll = do_longlist
|
| 929 |
+
|
| 930 |
+
def do_debug(self, arg):
|
| 931 |
+
"""debug code
|
| 932 |
+
Enter a recursive debugger that steps through the code
|
| 933 |
+
argument (which is an arbitrary expression or statement to be
|
| 934 |
+
executed in the current environment).
|
| 935 |
+
"""
|
| 936 |
+
trace_function = sys.gettrace()
|
| 937 |
+
sys.settrace(None)
|
| 938 |
+
assert self.curframe is not None
|
| 939 |
+
globals = self.curframe.f_globals
|
| 940 |
+
locals = self.curframe_locals
|
| 941 |
+
p = self.__class__(
|
| 942 |
+
completekey=self.completekey, stdin=self.stdin, stdout=self.stdout
|
| 943 |
+
)
|
| 944 |
+
p.use_rawinput = self.use_rawinput
|
| 945 |
+
p.prompt = "(%s) " % self.prompt.strip()
|
| 946 |
+
self.message("ENTERING RECURSIVE DEBUGGER")
|
| 947 |
+
sys.call_tracing(p.run, (arg, globals, locals))
|
| 948 |
+
self.message("LEAVING RECURSIVE DEBUGGER")
|
| 949 |
+
sys.settrace(trace_function)
|
| 950 |
+
self.lastcmd = p.lastcmd
|
| 951 |
+
|
| 952 |
+
def do_pdef(self, arg):
|
| 953 |
+
"""Print the call signature for any callable object.
|
| 954 |
+
|
| 955 |
+
The debugger interface to %pdef"""
|
| 956 |
+
assert self.curframe is not None
|
| 957 |
+
namespaces = [
|
| 958 |
+
("Locals", self.curframe_locals),
|
| 959 |
+
("Globals", self.curframe.f_globals),
|
| 960 |
+
]
|
| 961 |
+
self.shell.find_line_magic("pdef")(arg, namespaces=namespaces)
|
| 962 |
+
|
| 963 |
+
def do_pdoc(self, arg):
|
| 964 |
+
"""Print the docstring for an object.
|
| 965 |
+
|
| 966 |
+
The debugger interface to %pdoc."""
|
| 967 |
+
assert self.curframe is not None
|
| 968 |
+
namespaces = [
|
| 969 |
+
("Locals", self.curframe_locals),
|
| 970 |
+
("Globals", self.curframe.f_globals),
|
| 971 |
+
]
|
| 972 |
+
self.shell.find_line_magic("pdoc")(arg, namespaces=namespaces)
|
| 973 |
+
|
| 974 |
+
def do_pfile(self, arg):
|
| 975 |
+
"""Print (or run through pager) the file where an object is defined.
|
| 976 |
+
|
| 977 |
+
The debugger interface to %pfile.
|
| 978 |
+
"""
|
| 979 |
+
assert self.curframe is not None
|
| 980 |
+
namespaces = [
|
| 981 |
+
("Locals", self.curframe_locals),
|
| 982 |
+
("Globals", self.curframe.f_globals),
|
| 983 |
+
]
|
| 984 |
+
self.shell.find_line_magic("pfile")(arg, namespaces=namespaces)
|
| 985 |
+
|
| 986 |
+
def do_pinfo(self, arg):
|
| 987 |
+
"""Provide detailed information about an object.
|
| 988 |
+
|
| 989 |
+
The debugger interface to %pinfo, i.e., obj?."""
|
| 990 |
+
assert self.curframe is not None
|
| 991 |
+
namespaces = [
|
| 992 |
+
("Locals", self.curframe_locals),
|
| 993 |
+
("Globals", self.curframe.f_globals),
|
| 994 |
+
]
|
| 995 |
+
self.shell.find_line_magic("pinfo")(arg, namespaces=namespaces)
|
| 996 |
+
|
| 997 |
+
def do_pinfo2(self, arg):
|
| 998 |
+
"""Provide extra detailed information about an object.
|
| 999 |
+
|
| 1000 |
+
The debugger interface to %pinfo2, i.e., obj??."""
|
| 1001 |
+
assert self.curframe is not None
|
| 1002 |
+
namespaces = [
|
| 1003 |
+
("Locals", self.curframe_locals),
|
| 1004 |
+
("Globals", self.curframe.f_globals),
|
| 1005 |
+
]
|
| 1006 |
+
self.shell.find_line_magic("pinfo2")(arg, namespaces=namespaces)
|
| 1007 |
+
|
| 1008 |
+
def do_psource(self, arg):
|
| 1009 |
+
"""Print (or run through pager) the source code for an object."""
|
| 1010 |
+
assert self.curframe is not None
|
| 1011 |
+
namespaces = [
|
| 1012 |
+
("Locals", self.curframe_locals),
|
| 1013 |
+
("Globals", self.curframe.f_globals),
|
| 1014 |
+
]
|
| 1015 |
+
self.shell.find_line_magic("psource")(arg, namespaces=namespaces)
|
| 1016 |
+
|
| 1017 |
+
def do_where(self, arg: str):
|
| 1018 |
+
"""w(here)
|
| 1019 |
+
Print a stack trace, with the most recent frame at the bottom.
|
| 1020 |
+
An arrow indicates the "current frame", which determines the
|
| 1021 |
+
context of most commands. 'bt' is an alias for this command.
|
| 1022 |
+
|
| 1023 |
+
Take a number as argument as an (optional) number of context line to
|
| 1024 |
+
print"""
|
| 1025 |
+
if arg:
|
| 1026 |
+
try:
|
| 1027 |
+
context = int(arg)
|
| 1028 |
+
except ValueError as err:
|
| 1029 |
+
self.error(str(err))
|
| 1030 |
+
return
|
| 1031 |
+
self.print_stack_trace(context)
|
| 1032 |
+
else:
|
| 1033 |
+
self.print_stack_trace()
|
| 1034 |
+
|
| 1035 |
+
do_w = do_where
|
| 1036 |
+
|
| 1037 |
+
def break_anywhere(self, frame):
|
| 1038 |
+
"""
|
| 1039 |
+
_stop_in_decorator_internals is overly restrictive, as we may still want
|
| 1040 |
+
to trace function calls, so we need to also update break_anywhere so
|
| 1041 |
+
that is we don't `stop_here`, because of debugger skip, we may still
|
| 1042 |
+
stop at any point inside the function
|
| 1043 |
+
|
| 1044 |
+
"""
|
| 1045 |
+
|
| 1046 |
+
sup = super().break_anywhere(frame)
|
| 1047 |
+
if sup:
|
| 1048 |
+
return sup
|
| 1049 |
+
if self._predicates["debuggerskip"]:
|
| 1050 |
+
if DEBUGGERSKIP in frame.f_code.co_varnames:
|
| 1051 |
+
return True
|
| 1052 |
+
if frame.f_back and self._get_frame_locals(frame.f_back).get(DEBUGGERSKIP):
|
| 1053 |
+
return True
|
| 1054 |
+
return False
|
| 1055 |
+
|
| 1056 |
+
def _is_in_decorator_internal_and_should_skip(self, frame):
|
| 1057 |
+
"""
|
| 1058 |
+
Utility to tell us whether we are in a decorator internal and should stop.
|
| 1059 |
+
|
| 1060 |
+
"""
|
| 1061 |
+
# if we are disabled don't skip
|
| 1062 |
+
if not self._predicates["debuggerskip"]:
|
| 1063 |
+
return False
|
| 1064 |
+
|
| 1065 |
+
return self._cachable_skip(frame)
|
| 1066 |
+
|
| 1067 |
+
@lru_cache(1024)
|
| 1068 |
+
def _cached_one_parent_frame_debuggerskip(self, frame):
|
| 1069 |
+
"""
|
| 1070 |
+
Cache looking up for DEBUGGERSKIP on parent frame.
|
| 1071 |
+
|
| 1072 |
+
This should speedup walking through deep frame when one of the highest
|
| 1073 |
+
one does have a debugger skip.
|
| 1074 |
+
|
| 1075 |
+
This is likely to introduce fake positive though.
|
| 1076 |
+
"""
|
| 1077 |
+
while getattr(frame, "f_back", None):
|
| 1078 |
+
frame = frame.f_back
|
| 1079 |
+
if self._get_frame_locals(frame).get(DEBUGGERSKIP):
|
| 1080 |
+
return True
|
| 1081 |
+
return None
|
| 1082 |
+
|
| 1083 |
+
@lru_cache(1024)
|
| 1084 |
+
def _cachable_skip(self, frame):
|
| 1085 |
+
# if frame is tagged, skip by default.
|
| 1086 |
+
if DEBUGGERSKIP in frame.f_code.co_varnames:
|
| 1087 |
+
return True
|
| 1088 |
+
|
| 1089 |
+
# if one of the parent frame value set to True skip as well.
|
| 1090 |
+
if self._cached_one_parent_frame_debuggerskip(frame):
|
| 1091 |
+
return True
|
| 1092 |
+
|
| 1093 |
+
return False
|
| 1094 |
+
|
| 1095 |
+
def stop_here(self, frame):
|
| 1096 |
+
if self._is_in_decorator_internal_and_should_skip(frame) is True:
|
| 1097 |
+
return False
|
| 1098 |
+
|
| 1099 |
+
hidden = False
|
| 1100 |
+
if self.skip_hidden:
|
| 1101 |
+
hidden = self._hidden_predicate(frame)
|
| 1102 |
+
if hidden:
|
| 1103 |
+
if self.report_skipped:
|
| 1104 |
+
print(
|
| 1105 |
+
self.theme.format(
|
| 1106 |
+
[
|
| 1107 |
+
(
|
| 1108 |
+
Token.ExcName,
|
| 1109 |
+
" [... skipped 1 hidden frame(s)]",
|
| 1110 |
+
),
|
| 1111 |
+
(Token, "\n"),
|
| 1112 |
+
]
|
| 1113 |
+
)
|
| 1114 |
+
)
|
| 1115 |
+
if self.skip and self.is_skipped_module(frame.f_globals.get("__name__", "")):
|
| 1116 |
+
print(
|
| 1117 |
+
self.theme.format(
|
| 1118 |
+
[
|
| 1119 |
+
(
|
| 1120 |
+
Token.ExcName,
|
| 1121 |
+
" [... skipped 1 ignored module(s)]",
|
| 1122 |
+
),
|
| 1123 |
+
(Token, "\n"),
|
| 1124 |
+
]
|
| 1125 |
+
)
|
| 1126 |
+
)
|
| 1127 |
+
|
| 1128 |
+
return False
|
| 1129 |
+
|
| 1130 |
+
return super().stop_here(frame)
|
| 1131 |
+
|
| 1132 |
+
def do_up(self, arg):
|
| 1133 |
+
"""u(p) [count]
|
| 1134 |
+
Move the current frame count (default one) levels up in the
|
| 1135 |
+
stack trace (to an older frame).
|
| 1136 |
+
|
| 1137 |
+
Will skip hidden frames and ignored modules.
|
| 1138 |
+
"""
|
| 1139 |
+
# modified version of upstream that skips
|
| 1140 |
+
# frames with __tracebackhide__ and ignored modules
|
| 1141 |
+
if self.curindex == 0:
|
| 1142 |
+
self.error("Oldest frame")
|
| 1143 |
+
return
|
| 1144 |
+
try:
|
| 1145 |
+
count = int(arg or 1)
|
| 1146 |
+
except ValueError:
|
| 1147 |
+
self.error("Invalid frame count (%s)" % arg)
|
| 1148 |
+
return
|
| 1149 |
+
|
| 1150 |
+
hidden_skipped = 0
|
| 1151 |
+
module_skipped = 0
|
| 1152 |
+
|
| 1153 |
+
if count < 0:
|
| 1154 |
+
_newframe = 0
|
| 1155 |
+
else:
|
| 1156 |
+
counter = 0
|
| 1157 |
+
hidden_frames = self.hidden_frames(self.stack)
|
| 1158 |
+
|
| 1159 |
+
for i in range(self.curindex - 1, -1, -1):
|
| 1160 |
+
should_skip_hidden = hidden_frames[i] and self.skip_hidden
|
| 1161 |
+
should_skip_module = self.skip and self.is_skipped_module(
|
| 1162 |
+
self.stack[i][0].f_globals.get("__name__", "")
|
| 1163 |
+
)
|
| 1164 |
+
|
| 1165 |
+
if should_skip_hidden or should_skip_module:
|
| 1166 |
+
if should_skip_hidden:
|
| 1167 |
+
hidden_skipped += 1
|
| 1168 |
+
if should_skip_module:
|
| 1169 |
+
module_skipped += 1
|
| 1170 |
+
continue
|
| 1171 |
+
counter += 1
|
| 1172 |
+
if counter >= count:
|
| 1173 |
+
break
|
| 1174 |
+
else:
|
| 1175 |
+
# if no break occurred.
|
| 1176 |
+
self.error(
|
| 1177 |
+
"all frames above skipped (hidden frames and ignored modules). Use `skip_hidden False` for hidden frames or unignore_module for ignored modules."
|
| 1178 |
+
)
|
| 1179 |
+
return
|
| 1180 |
+
|
| 1181 |
+
_newframe = i
|
| 1182 |
+
self._select_frame(_newframe)
|
| 1183 |
+
|
| 1184 |
+
total_skipped = hidden_skipped + module_skipped
|
| 1185 |
+
if total_skipped:
|
| 1186 |
+
print(
|
| 1187 |
+
self.theme.format(
|
| 1188 |
+
[
|
| 1189 |
+
(
|
| 1190 |
+
Token.ExcName,
|
| 1191 |
+
f" [... skipped {total_skipped} frame(s): {hidden_skipped} hidden frames + {module_skipped} ignored modules]",
|
| 1192 |
+
),
|
| 1193 |
+
(Token, "\n"),
|
| 1194 |
+
]
|
| 1195 |
+
)
|
| 1196 |
+
)
|
| 1197 |
+
|
| 1198 |
+
def do_down(self, arg):
|
| 1199 |
+
"""d(own) [count]
|
| 1200 |
+
Move the current frame count (default one) levels down in the
|
| 1201 |
+
stack trace (to a newer frame).
|
| 1202 |
+
|
| 1203 |
+
Will skip hidden frames and ignored modules.
|
| 1204 |
+
"""
|
| 1205 |
+
if self.curindex + 1 == len(self.stack):
|
| 1206 |
+
self.error("Newest frame")
|
| 1207 |
+
return
|
| 1208 |
+
try:
|
| 1209 |
+
count = int(arg or 1)
|
| 1210 |
+
except ValueError:
|
| 1211 |
+
self.error("Invalid frame count (%s)" % arg)
|
| 1212 |
+
return
|
| 1213 |
+
if count < 0:
|
| 1214 |
+
_newframe = len(self.stack) - 1
|
| 1215 |
+
else:
|
| 1216 |
+
counter = 0
|
| 1217 |
+
hidden_skipped = 0
|
| 1218 |
+
module_skipped = 0
|
| 1219 |
+
hidden_frames = self.hidden_frames(self.stack)
|
| 1220 |
+
|
| 1221 |
+
for i in range(self.curindex + 1, len(self.stack)):
|
| 1222 |
+
should_skip_hidden = hidden_frames[i] and self.skip_hidden
|
| 1223 |
+
should_skip_module = self.skip and self.is_skipped_module(
|
| 1224 |
+
self.stack[i][0].f_globals.get("__name__", "")
|
| 1225 |
+
)
|
| 1226 |
+
|
| 1227 |
+
if should_skip_hidden or should_skip_module:
|
| 1228 |
+
if should_skip_hidden:
|
| 1229 |
+
hidden_skipped += 1
|
| 1230 |
+
if should_skip_module:
|
| 1231 |
+
module_skipped += 1
|
| 1232 |
+
continue
|
| 1233 |
+
counter += 1
|
| 1234 |
+
if counter >= count:
|
| 1235 |
+
break
|
| 1236 |
+
else:
|
| 1237 |
+
self.error(
|
| 1238 |
+
"all frames below skipped (hidden frames and ignored modules). Use `skip_hidden False` for hidden frames or unignore_module for ignored modules."
|
| 1239 |
+
)
|
| 1240 |
+
return
|
| 1241 |
+
|
| 1242 |
+
total_skipped = hidden_skipped + module_skipped
|
| 1243 |
+
if total_skipped:
|
| 1244 |
+
print(
|
| 1245 |
+
self.theme.format(
|
| 1246 |
+
[
|
| 1247 |
+
(
|
| 1248 |
+
Token.ExcName,
|
| 1249 |
+
f" [... skipped {total_skipped} frame(s): {hidden_skipped} hidden frames + {module_skipped} ignored modules]",
|
| 1250 |
+
),
|
| 1251 |
+
(Token, "\n"),
|
| 1252 |
+
]
|
| 1253 |
+
)
|
| 1254 |
+
)
|
| 1255 |
+
_newframe = i
|
| 1256 |
+
|
| 1257 |
+
self._select_frame(_newframe)
|
| 1258 |
+
|
| 1259 |
+
do_d = do_down
|
| 1260 |
+
do_u = do_up
|
| 1261 |
+
|
| 1262 |
+
def _show_ignored_modules(self):
|
| 1263 |
+
"""Display currently ignored modules."""
|
| 1264 |
+
if self.skip:
|
| 1265 |
+
print(f"Currently ignored modules: {sorted(self.skip)}")
|
| 1266 |
+
else:
|
| 1267 |
+
print("No modules are currently ignored.")
|
| 1268 |
+
|
| 1269 |
+
def do_ignore_module(self, arg):
|
| 1270 |
+
"""ignore_module <module_name>
|
| 1271 |
+
|
| 1272 |
+
Add a module to the list of modules to skip when navigating frames.
|
| 1273 |
+
When a module is ignored, the debugger will automatically skip over
|
| 1274 |
+
frames from that module.
|
| 1275 |
+
|
| 1276 |
+
Supports wildcard patterns using fnmatch syntax:
|
| 1277 |
+
|
| 1278 |
+
Usage:
|
| 1279 |
+
ignore_module threading # Skip threading module frames
|
| 1280 |
+
ignore_module asyncio.\\* # Skip all asyncio submodules
|
| 1281 |
+
ignore_module \\*.tests # Skip all test modules
|
| 1282 |
+
ignore_module # List currently ignored modules
|
| 1283 |
+
"""
|
| 1284 |
+
|
| 1285 |
+
if self.skip is None:
|
| 1286 |
+
self.skip = set()
|
| 1287 |
+
|
| 1288 |
+
module_name = arg.strip()
|
| 1289 |
+
|
| 1290 |
+
if not module_name:
|
| 1291 |
+
self._show_ignored_modules()
|
| 1292 |
+
return
|
| 1293 |
+
|
| 1294 |
+
self.skip.add(module_name)
|
| 1295 |
+
|
| 1296 |
+
def do_unignore_module(self, arg):
|
| 1297 |
+
"""unignore_module <module_name>
|
| 1298 |
+
|
| 1299 |
+
Remove a module from the list of modules to skip when navigating frames.
|
| 1300 |
+
This will allow the debugger to step into frames from the specified module.
|
| 1301 |
+
|
| 1302 |
+
Usage:
|
| 1303 |
+
unignore_module threading # Stop ignoring threading module frames
|
| 1304 |
+
unignore_module asyncio.\\* # Remove asyncio.* pattern
|
| 1305 |
+
unignore_module # List currently ignored modules
|
| 1306 |
+
"""
|
| 1307 |
+
|
| 1308 |
+
if self.skip is None:
|
| 1309 |
+
self.skip = set()
|
| 1310 |
+
|
| 1311 |
+
module_name = arg.strip()
|
| 1312 |
+
|
| 1313 |
+
if not module_name:
|
| 1314 |
+
self._show_ignored_modules()
|
| 1315 |
+
return
|
| 1316 |
+
|
| 1317 |
+
try:
|
| 1318 |
+
self.skip.remove(module_name)
|
| 1319 |
+
except KeyError:
|
| 1320 |
+
print(f"Module {module_name} is not currently ignored")
|
| 1321 |
+
self._show_ignored_modules()
|
| 1322 |
+
|
| 1323 |
+
def do_context(self, context: str):
|
| 1324 |
+
"""context number_of_lines
|
| 1325 |
+
Set the number of lines of source code to show when displaying
|
| 1326 |
+
stacktrace information.
|
| 1327 |
+
"""
|
| 1328 |
+
try:
|
| 1329 |
+
new_context = int(context)
|
| 1330 |
+
if new_context <= 0:
|
| 1331 |
+
raise ValueError()
|
| 1332 |
+
self.context = new_context
|
| 1333 |
+
except ValueError:
|
| 1334 |
+
self.error(
|
| 1335 |
+
f"The 'context' command requires a positive integer argument (current value {self.context})."
|
| 1336 |
+
)
|
| 1337 |
+
|
| 1338 |
+
|
| 1339 |
+
class InterruptiblePdb(Pdb):
|
| 1340 |
+
"""Version of debugger where KeyboardInterrupt exits the debugger altogether."""
|
| 1341 |
+
|
| 1342 |
+
def cmdloop(self, intro=None):
|
| 1343 |
+
"""Wrap cmdloop() such that KeyboardInterrupt stops the debugger."""
|
| 1344 |
+
try:
|
| 1345 |
+
return OldPdb.cmdloop(self, intro=intro)
|
| 1346 |
+
except KeyboardInterrupt:
|
| 1347 |
+
self.stop_here = lambda frame: False # type: ignore[method-assign]
|
| 1348 |
+
self.do_quit("")
|
| 1349 |
+
sys.settrace(None)
|
| 1350 |
+
self.quitting = False
|
| 1351 |
+
raise
|
| 1352 |
+
|
| 1353 |
+
def _cmdloop(self):
|
| 1354 |
+
while True:
|
| 1355 |
+
try:
|
| 1356 |
+
# keyboard interrupts allow for an easy way to cancel
|
| 1357 |
+
# the current command, so allow them during interactive input
|
| 1358 |
+
self.allow_kbdint = True
|
| 1359 |
+
self.cmdloop()
|
| 1360 |
+
self.allow_kbdint = False
|
| 1361 |
+
break
|
| 1362 |
+
except KeyboardInterrupt:
|
| 1363 |
+
self.message("--KeyboardInterrupt--")
|
| 1364 |
+
raise
|
| 1365 |
+
|
| 1366 |
+
|
| 1367 |
+
def set_trace(frame=None, header=None):
|
| 1368 |
+
"""
|
| 1369 |
+
Start debugging from `frame`.
|
| 1370 |
+
|
| 1371 |
+
If frame is not specified, debugging starts from caller's frame.
|
| 1372 |
+
"""
|
| 1373 |
+
pdb = Pdb()
|
| 1374 |
+
if header is not None:
|
| 1375 |
+
pdb.message(header)
|
| 1376 |
+
pdb.set_trace(frame or sys._getframe().f_back)
|
lib/python3.12/site-packages/IPython/core/debugger_backport.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
The code in this module is a backport of cPython changes in Pdb
|
| 3 |
+
that were introduced in Python 3.13 by gh-83151: Make closure work on pdb
|
| 4 |
+
https://github.com/python/cpython/pull/111094.
|
| 5 |
+
This file should be removed once IPython drops supports for Python 3.12.
|
| 6 |
+
|
| 7 |
+
The only changes are:
|
| 8 |
+
- reformatting by darker (black) formatter
|
| 9 |
+
- addition of type-ignore comments to satisfy mypy
|
| 10 |
+
|
| 11 |
+
Copyright (c) 2001 Python Software Foundation; All Rights Reserved
|
| 12 |
+
|
| 13 |
+
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
|
| 14 |
+
--------------------------------------------
|
| 15 |
+
|
| 16 |
+
1. This LICENSE AGREEMENT is between the Python Software Foundation
|
| 17 |
+
("PSF"), and the Individual or Organization ("Licensee") accessing and
|
| 18 |
+
otherwise using this software ("Python") in source or binary form and
|
| 19 |
+
its associated documentation.
|
| 20 |
+
|
| 21 |
+
2. Subject to the terms and conditions of this License Agreement, PSF hereby
|
| 22 |
+
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
|
| 23 |
+
analyze, test, perform and/or display publicly, prepare derivative works,
|
| 24 |
+
distribute, and otherwise use Python alone or in any derivative version,
|
| 25 |
+
provided, however, that PSF's License Agreement and PSF's notice of copyright,
|
| 26 |
+
i.e., "Copyright (c) 2001 Python Software Foundation; All Rights Reserved"
|
| 27 |
+
are retained in Python alone or in any derivative version prepared by Licensee.
|
| 28 |
+
|
| 29 |
+
3. In the event Licensee prepares a derivative work that is based on
|
| 30 |
+
or incorporates Python or any part thereof, and wants to make
|
| 31 |
+
the derivative work available to others as provided herein, then
|
| 32 |
+
Licensee hereby agrees to include in any such work a brief summary of
|
| 33 |
+
the changes made to Python.
|
| 34 |
+
|
| 35 |
+
4. PSF is making Python available to Licensee on an "AS IS"
|
| 36 |
+
basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
|
| 37 |
+
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
|
| 38 |
+
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
|
| 39 |
+
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
|
| 40 |
+
INFRINGE ANY THIRD PARTY RIGHTS.
|
| 41 |
+
|
| 42 |
+
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
|
| 43 |
+
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
|
| 44 |
+
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
|
| 45 |
+
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
|
| 46 |
+
|
| 47 |
+
6. This License Agreement will automatically terminate upon a material
|
| 48 |
+
breach of its terms and conditions.
|
| 49 |
+
|
| 50 |
+
7. Nothing in this License Agreement shall be deemed to create any
|
| 51 |
+
relationship of agency, partnership, or joint venture between PSF and
|
| 52 |
+
Licensee. This License Agreement does not grant permission to use PSF
|
| 53 |
+
trademarks or trade name in a trademark sense to endorse or promote
|
| 54 |
+
products or services of Licensee, or any third party.
|
| 55 |
+
|
| 56 |
+
8. By copying, installing or otherwise using Python, Licensee
|
| 57 |
+
agrees to be bound by the terms and conditions of this License
|
| 58 |
+
Agreement.
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
import sys
|
| 62 |
+
import types
|
| 63 |
+
import codeop
|
| 64 |
+
import textwrap
|
| 65 |
+
from types import CodeType
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class PdbClosureBackport:
|
| 69 |
+
def _exec_in_closure(self, source, globals, locals): # type: ignore[no-untyped-def]
|
| 70 |
+
"""Run source code in closure so code object created within source
|
| 71 |
+
can find variables in locals correctly
|
| 72 |
+
returns True if the source is executed, False otherwise
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
# Determine if the source should be executed in closure. Only when the
|
| 76 |
+
# source compiled to multiple code objects, we should use this feature.
|
| 77 |
+
# Otherwise, we can just raise an exception and normal exec will be used.
|
| 78 |
+
|
| 79 |
+
code = compile(source, "<string>", "exec")
|
| 80 |
+
if not any(isinstance(const, CodeType) for const in code.co_consts):
|
| 81 |
+
return False
|
| 82 |
+
|
| 83 |
+
# locals could be a proxy which does not support pop
|
| 84 |
+
# copy it first to avoid modifying the original locals
|
| 85 |
+
locals_copy = dict(locals)
|
| 86 |
+
|
| 87 |
+
locals_copy["__pdb_eval__"] = {"result": None, "write_back": {}}
|
| 88 |
+
|
| 89 |
+
# If the source is an expression, we need to print its value
|
| 90 |
+
try:
|
| 91 |
+
compile(source, "<string>", "eval")
|
| 92 |
+
except SyntaxError:
|
| 93 |
+
pass
|
| 94 |
+
else:
|
| 95 |
+
source = "__pdb_eval__['result'] = " + source
|
| 96 |
+
|
| 97 |
+
# Add write-back to update the locals
|
| 98 |
+
source = (
|
| 99 |
+
"try:\n"
|
| 100 |
+
+ textwrap.indent(source, " ")
|
| 101 |
+
+ "\n"
|
| 102 |
+
+ "finally:\n"
|
| 103 |
+
+ " __pdb_eval__['write_back'] = locals()"
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
# Build a closure source code with freevars from locals like:
|
| 107 |
+
# def __pdb_outer():
|
| 108 |
+
# var = None
|
| 109 |
+
# def __pdb_scope(): # This is the code object we want to execute
|
| 110 |
+
# nonlocal var
|
| 111 |
+
# <source>
|
| 112 |
+
# return __pdb_scope.__code__
|
| 113 |
+
source_with_closure = (
|
| 114 |
+
"def __pdb_outer():\n"
|
| 115 |
+
+ "\n".join(f" {var} = None" for var in locals_copy)
|
| 116 |
+
+ "\n"
|
| 117 |
+
+ " def __pdb_scope():\n"
|
| 118 |
+
+ "\n".join(f" nonlocal {var}" for var in locals_copy)
|
| 119 |
+
+ "\n"
|
| 120 |
+
+ textwrap.indent(source, " ")
|
| 121 |
+
+ "\n"
|
| 122 |
+
+ " return __pdb_scope.__code__"
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
# Get the code object of __pdb_scope()
|
| 126 |
+
# The exec fills locals_copy with the __pdb_outer() function and we can call
|
| 127 |
+
# that to get the code object of __pdb_scope()
|
| 128 |
+
ns = {}
|
| 129 |
+
try:
|
| 130 |
+
exec(source_with_closure, {}, ns)
|
| 131 |
+
except Exception:
|
| 132 |
+
return False
|
| 133 |
+
code = ns["__pdb_outer"]()
|
| 134 |
+
|
| 135 |
+
cells = tuple(types.CellType(locals_copy.get(var)) for var in code.co_freevars)
|
| 136 |
+
|
| 137 |
+
try:
|
| 138 |
+
exec(code, globals, locals_copy, closure=cells)
|
| 139 |
+
except Exception:
|
| 140 |
+
return False
|
| 141 |
+
|
| 142 |
+
# get the data we need from the statement
|
| 143 |
+
pdb_eval = locals_copy["__pdb_eval__"]
|
| 144 |
+
|
| 145 |
+
# __pdb_eval__ should not be updated back to locals
|
| 146 |
+
pdb_eval["write_back"].pop("__pdb_eval__")
|
| 147 |
+
|
| 148 |
+
# Write all local variables back to locals
|
| 149 |
+
locals.update(pdb_eval["write_back"])
|
| 150 |
+
eval_result = pdb_eval["result"]
|
| 151 |
+
if eval_result is not None:
|
| 152 |
+
print(repr(eval_result))
|
| 153 |
+
|
| 154 |
+
return True
|
| 155 |
+
|
| 156 |
+
def default(self, line): # type: ignore[no-untyped-def]
|
| 157 |
+
if line[:1] == "!":
|
| 158 |
+
line = line[1:].strip()
|
| 159 |
+
locals = self.curframe_locals
|
| 160 |
+
globals = self.curframe.f_globals
|
| 161 |
+
try:
|
| 162 |
+
buffer = line
|
| 163 |
+
if (
|
| 164 |
+
code := codeop.compile_command(line + "\n", "<stdin>", "single")
|
| 165 |
+
) is None:
|
| 166 |
+
# Multi-line mode
|
| 167 |
+
with self._disable_command_completion():
|
| 168 |
+
buffer = line
|
| 169 |
+
continue_prompt = "... "
|
| 170 |
+
while (
|
| 171 |
+
code := codeop.compile_command(buffer, "<stdin>", "single")
|
| 172 |
+
) is None:
|
| 173 |
+
if self.use_rawinput:
|
| 174 |
+
try:
|
| 175 |
+
line = input(continue_prompt)
|
| 176 |
+
except (EOFError, KeyboardInterrupt):
|
| 177 |
+
self.lastcmd = ""
|
| 178 |
+
print("\n")
|
| 179 |
+
return
|
| 180 |
+
else:
|
| 181 |
+
self.stdout.write(continue_prompt)
|
| 182 |
+
self.stdout.flush()
|
| 183 |
+
line = self.stdin.readline()
|
| 184 |
+
if not len(line):
|
| 185 |
+
self.lastcmd = ""
|
| 186 |
+
self.stdout.write("\n")
|
| 187 |
+
self.stdout.flush()
|
| 188 |
+
return
|
| 189 |
+
else:
|
| 190 |
+
line = line.rstrip("\r\n")
|
| 191 |
+
buffer += "\n" + line
|
| 192 |
+
save_stdout = sys.stdout
|
| 193 |
+
save_stdin = sys.stdin
|
| 194 |
+
save_displayhook = sys.displayhook
|
| 195 |
+
try:
|
| 196 |
+
sys.stdin = self.stdin
|
| 197 |
+
sys.stdout = self.stdout
|
| 198 |
+
sys.displayhook = self.displayhook
|
| 199 |
+
if not self._exec_in_closure(buffer, globals, locals):
|
| 200 |
+
exec(code, globals, locals)
|
| 201 |
+
finally:
|
| 202 |
+
sys.stdout = save_stdout
|
| 203 |
+
sys.stdin = save_stdin
|
| 204 |
+
sys.displayhook = save_displayhook
|
| 205 |
+
except:
|
| 206 |
+
self._error_exc()
|
lib/python3.12/site-packages/IPython/core/display.py
ADDED
|
@@ -0,0 +1,1266 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Top-level display functions for displaying object in different formats."""
|
| 2 |
+
|
| 3 |
+
# Copyright (c) IPython Development Team.
|
| 4 |
+
# Distributed under the terms of the Modified BSD License.
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
from binascii import b2a_base64, hexlify
|
| 8 |
+
import html
|
| 9 |
+
import json
|
| 10 |
+
import mimetypes
|
| 11 |
+
import os
|
| 12 |
+
import struct
|
| 13 |
+
import warnings
|
| 14 |
+
from copy import deepcopy
|
| 15 |
+
from os.path import splitext
|
| 16 |
+
from pathlib import Path, PurePath
|
| 17 |
+
|
| 18 |
+
from typing import Optional
|
| 19 |
+
|
| 20 |
+
from IPython.testing.skipdoctest import skip_doctest
|
| 21 |
+
from . import display_functions
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
__all__ = [
|
| 25 |
+
"display_pretty",
|
| 26 |
+
"display_html",
|
| 27 |
+
"display_markdown",
|
| 28 |
+
"display_svg",
|
| 29 |
+
"display_png",
|
| 30 |
+
"display_jpeg",
|
| 31 |
+
"display_webp",
|
| 32 |
+
"display_latex",
|
| 33 |
+
"display_json",
|
| 34 |
+
"display_javascript",
|
| 35 |
+
"display_pdf",
|
| 36 |
+
"DisplayObject",
|
| 37 |
+
"TextDisplayObject",
|
| 38 |
+
"Pretty",
|
| 39 |
+
"HTML",
|
| 40 |
+
"Markdown",
|
| 41 |
+
"Math",
|
| 42 |
+
"Latex",
|
| 43 |
+
"SVG",
|
| 44 |
+
"ProgressBar",
|
| 45 |
+
"JSON",
|
| 46 |
+
"GeoJSON",
|
| 47 |
+
"Javascript",
|
| 48 |
+
"Image",
|
| 49 |
+
"Video",
|
| 50 |
+
]
|
| 51 |
+
|
| 52 |
+
#-----------------------------------------------------------------------------
|
| 53 |
+
# utility functions
|
| 54 |
+
#-----------------------------------------------------------------------------
|
| 55 |
+
|
| 56 |
+
def _safe_exists(path):
|
| 57 |
+
"""Check path, but don't let exceptions raise"""
|
| 58 |
+
try:
|
| 59 |
+
return os.path.exists(path)
|
| 60 |
+
except Exception:
|
| 61 |
+
return False
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _display_mimetype(mimetype, objs, raw=False, metadata=None):
|
| 65 |
+
"""internal implementation of all display_foo methods
|
| 66 |
+
|
| 67 |
+
Parameters
|
| 68 |
+
----------
|
| 69 |
+
mimetype : str
|
| 70 |
+
The mimetype to be published (e.g. 'image/png')
|
| 71 |
+
*objs : object
|
| 72 |
+
The Python objects to display, or if raw=True raw text data to
|
| 73 |
+
display.
|
| 74 |
+
raw : bool
|
| 75 |
+
Are the data objects raw data or Python objects that need to be
|
| 76 |
+
formatted before display? [default: False]
|
| 77 |
+
metadata : dict (optional)
|
| 78 |
+
Metadata to be associated with the specific mimetype output.
|
| 79 |
+
"""
|
| 80 |
+
if metadata:
|
| 81 |
+
metadata = {mimetype: metadata}
|
| 82 |
+
if raw:
|
| 83 |
+
# turn list of pngdata into list of { 'image/png': pngdata }
|
| 84 |
+
objs = [ {mimetype: obj} for obj in objs ]
|
| 85 |
+
display_functions.display(*objs, raw=raw, metadata=metadata, include=[mimetype])
|
| 86 |
+
|
| 87 |
+
#-----------------------------------------------------------------------------
|
| 88 |
+
# Main functions
|
| 89 |
+
#-----------------------------------------------------------------------------
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def display_pretty(*objs, **kwargs):
|
| 93 |
+
"""Display the pretty (default) representation of an object.
|
| 94 |
+
|
| 95 |
+
Parameters
|
| 96 |
+
----------
|
| 97 |
+
*objs : object
|
| 98 |
+
The Python objects to display, or if raw=True raw text data to
|
| 99 |
+
display.
|
| 100 |
+
raw : bool
|
| 101 |
+
Are the data objects raw data or Python objects that need to be
|
| 102 |
+
formatted before display? [default: False]
|
| 103 |
+
metadata : dict (optional)
|
| 104 |
+
Metadata to be associated with the specific mimetype output.
|
| 105 |
+
"""
|
| 106 |
+
_display_mimetype('text/plain', objs, **kwargs)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def display_html(*objs, **kwargs):
|
| 110 |
+
"""Display the HTML representation of an object.
|
| 111 |
+
|
| 112 |
+
Note: If raw=False and the object does not have a HTML
|
| 113 |
+
representation, no HTML will be shown.
|
| 114 |
+
|
| 115 |
+
Parameters
|
| 116 |
+
----------
|
| 117 |
+
*objs : object
|
| 118 |
+
The Python objects to display, or if raw=True raw HTML data to
|
| 119 |
+
display.
|
| 120 |
+
raw : bool
|
| 121 |
+
Are the data objects raw data or Python objects that need to be
|
| 122 |
+
formatted before display? [default: False]
|
| 123 |
+
metadata : dict (optional)
|
| 124 |
+
Metadata to be associated with the specific mimetype output.
|
| 125 |
+
"""
|
| 126 |
+
_display_mimetype('text/html', objs, **kwargs)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def display_markdown(*objs, **kwargs):
|
| 130 |
+
"""Displays the Markdown representation of an object.
|
| 131 |
+
|
| 132 |
+
Parameters
|
| 133 |
+
----------
|
| 134 |
+
*objs : object
|
| 135 |
+
The Python objects to display, or if raw=True raw markdown data to
|
| 136 |
+
display.
|
| 137 |
+
raw : bool
|
| 138 |
+
Are the data objects raw data or Python objects that need to be
|
| 139 |
+
formatted before display? [default: False]
|
| 140 |
+
metadata : dict (optional)
|
| 141 |
+
Metadata to be associated with the specific mimetype output.
|
| 142 |
+
"""
|
| 143 |
+
|
| 144 |
+
_display_mimetype('text/markdown', objs, **kwargs)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def display_svg(*objs, **kwargs):
|
| 148 |
+
"""Display the SVG representation of an object.
|
| 149 |
+
|
| 150 |
+
Parameters
|
| 151 |
+
----------
|
| 152 |
+
*objs : object
|
| 153 |
+
The Python objects to display, or if raw=True raw svg data to
|
| 154 |
+
display.
|
| 155 |
+
raw : bool
|
| 156 |
+
Are the data objects raw data or Python objects that need to be
|
| 157 |
+
formatted before display? [default: False]
|
| 158 |
+
metadata : dict (optional)
|
| 159 |
+
Metadata to be associated with the specific mimetype output.
|
| 160 |
+
"""
|
| 161 |
+
_display_mimetype('image/svg+xml', objs, **kwargs)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def display_png(*objs, **kwargs):
|
| 165 |
+
"""Display the PNG representation of an object.
|
| 166 |
+
|
| 167 |
+
Parameters
|
| 168 |
+
----------
|
| 169 |
+
*objs : object
|
| 170 |
+
The Python objects to display, or if raw=True raw png data to
|
| 171 |
+
display.
|
| 172 |
+
raw : bool
|
| 173 |
+
Are the data objects raw data or Python objects that need to be
|
| 174 |
+
formatted before display? [default: False]
|
| 175 |
+
metadata : dict (optional)
|
| 176 |
+
Metadata to be associated with the specific mimetype output.
|
| 177 |
+
"""
|
| 178 |
+
_display_mimetype('image/png', objs, **kwargs)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def display_jpeg(*objs, **kwargs):
|
| 182 |
+
"""Display the JPEG representation of an object.
|
| 183 |
+
|
| 184 |
+
Parameters
|
| 185 |
+
----------
|
| 186 |
+
*objs : object
|
| 187 |
+
The Python objects to display, or if raw=True raw JPEG data to
|
| 188 |
+
display.
|
| 189 |
+
raw : bool
|
| 190 |
+
Are the data objects raw data or Python objects that need to be
|
| 191 |
+
formatted before display? [default: False]
|
| 192 |
+
metadata : dict (optional)
|
| 193 |
+
Metadata to be associated with the specific mimetype output.
|
| 194 |
+
"""
|
| 195 |
+
_display_mimetype('image/jpeg', objs, **kwargs)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def display_webp(*objs, **kwargs):
|
| 199 |
+
"""Display the WEBP representation of an object.
|
| 200 |
+
|
| 201 |
+
Parameters
|
| 202 |
+
----------
|
| 203 |
+
*objs : object
|
| 204 |
+
The Python objects to display, or if raw=True raw JPEG data to
|
| 205 |
+
display.
|
| 206 |
+
raw : bool
|
| 207 |
+
Are the data objects raw data or Python objects that need to be
|
| 208 |
+
formatted before display? [default: False]
|
| 209 |
+
metadata : dict (optional)
|
| 210 |
+
Metadata to be associated with the specific mimetype output.
|
| 211 |
+
"""
|
| 212 |
+
_display_mimetype("image/webp", objs, **kwargs)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def display_latex(*objs, **kwargs):
|
| 216 |
+
"""Display the LaTeX representation of an object.
|
| 217 |
+
|
| 218 |
+
Parameters
|
| 219 |
+
----------
|
| 220 |
+
*objs : object
|
| 221 |
+
The Python objects to display, or if raw=True raw latex data to
|
| 222 |
+
display.
|
| 223 |
+
raw : bool
|
| 224 |
+
Are the data objects raw data or Python objects that need to be
|
| 225 |
+
formatted before display? [default: False]
|
| 226 |
+
metadata : dict (optional)
|
| 227 |
+
Metadata to be associated with the specific mimetype output.
|
| 228 |
+
"""
|
| 229 |
+
_display_mimetype('text/latex', objs, **kwargs)
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def display_json(*objs, **kwargs):
|
| 233 |
+
"""Display the JSON representation of an object.
|
| 234 |
+
|
| 235 |
+
Note that not many frontends support displaying JSON.
|
| 236 |
+
|
| 237 |
+
Parameters
|
| 238 |
+
----------
|
| 239 |
+
*objs : object
|
| 240 |
+
The Python objects to display, or if raw=True raw json data to
|
| 241 |
+
display.
|
| 242 |
+
raw : bool
|
| 243 |
+
Are the data objects raw data or Python objects that need to be
|
| 244 |
+
formatted before display? [default: False]
|
| 245 |
+
metadata : dict (optional)
|
| 246 |
+
Metadata to be associated with the specific mimetype output.
|
| 247 |
+
"""
|
| 248 |
+
_display_mimetype('application/json', objs, **kwargs)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def display_javascript(*objs, **kwargs):
|
| 252 |
+
"""Display the Javascript representation of an object.
|
| 253 |
+
|
| 254 |
+
Parameters
|
| 255 |
+
----------
|
| 256 |
+
*objs : object
|
| 257 |
+
The Python objects to display, or if raw=True raw javascript data to
|
| 258 |
+
display.
|
| 259 |
+
raw : bool
|
| 260 |
+
Are the data objects raw data or Python objects that need to be
|
| 261 |
+
formatted before display? [default: False]
|
| 262 |
+
metadata : dict (optional)
|
| 263 |
+
Metadata to be associated with the specific mimetype output.
|
| 264 |
+
"""
|
| 265 |
+
_display_mimetype('application/javascript', objs, **kwargs)
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def display_pdf(*objs, **kwargs):
|
| 269 |
+
"""Display the PDF representation of an object.
|
| 270 |
+
|
| 271 |
+
Parameters
|
| 272 |
+
----------
|
| 273 |
+
*objs : object
|
| 274 |
+
The Python objects to display, or if raw=True raw javascript data to
|
| 275 |
+
display.
|
| 276 |
+
raw : bool
|
| 277 |
+
Are the data objects raw data or Python objects that need to be
|
| 278 |
+
formatted before display? [default: False]
|
| 279 |
+
metadata : dict (optional)
|
| 280 |
+
Metadata to be associated with the specific mimetype output.
|
| 281 |
+
"""
|
| 282 |
+
_display_mimetype('application/pdf', objs, **kwargs)
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
#-----------------------------------------------------------------------------
|
| 286 |
+
# Smart classes
|
| 287 |
+
#-----------------------------------------------------------------------------
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
class DisplayObject:
|
| 291 |
+
"""An object that wraps data to be displayed."""
|
| 292 |
+
|
| 293 |
+
_read_flags = 'r'
|
| 294 |
+
_show_mem_addr = False
|
| 295 |
+
metadata = None
|
| 296 |
+
|
| 297 |
+
def __init__(self, data=None, url=None, filename=None, metadata=None):
|
| 298 |
+
"""Create a display object given raw data.
|
| 299 |
+
|
| 300 |
+
When this object is returned by an expression or passed to the
|
| 301 |
+
display function, it will result in the data being displayed
|
| 302 |
+
in the frontend. The MIME type of the data should match the
|
| 303 |
+
subclasses used, so the Png subclass should be used for 'image/png'
|
| 304 |
+
data. If the data is a URL, the data will first be downloaded
|
| 305 |
+
and then displayed.
|
| 306 |
+
|
| 307 |
+
Parameters
|
| 308 |
+
----------
|
| 309 |
+
data : unicode, str or bytes
|
| 310 |
+
The raw data or a URL or file to load the data from
|
| 311 |
+
url : unicode
|
| 312 |
+
A URL to download the data from.
|
| 313 |
+
filename : unicode
|
| 314 |
+
Path to a local file to load the data from.
|
| 315 |
+
metadata : dict
|
| 316 |
+
Dict of metadata associated to be the object when displayed
|
| 317 |
+
"""
|
| 318 |
+
if isinstance(data, (Path, PurePath)):
|
| 319 |
+
data = str(data)
|
| 320 |
+
|
| 321 |
+
if data is not None and isinstance(data, str):
|
| 322 |
+
if data.startswith('http') and url is None:
|
| 323 |
+
url = data
|
| 324 |
+
filename = None
|
| 325 |
+
data = None
|
| 326 |
+
elif _safe_exists(data) and filename is None:
|
| 327 |
+
url = None
|
| 328 |
+
filename = data
|
| 329 |
+
data = None
|
| 330 |
+
|
| 331 |
+
self.url = url
|
| 332 |
+
self.filename = filename
|
| 333 |
+
# because of @data.setter methods in
|
| 334 |
+
# subclasses ensure url and filename are set
|
| 335 |
+
# before assigning to self.data
|
| 336 |
+
self.data = data
|
| 337 |
+
|
| 338 |
+
if metadata is not None:
|
| 339 |
+
self.metadata = metadata
|
| 340 |
+
elif self.metadata is None:
|
| 341 |
+
self.metadata = {}
|
| 342 |
+
|
| 343 |
+
self.reload()
|
| 344 |
+
self._check_data()
|
| 345 |
+
|
| 346 |
+
def __repr__(self):
|
| 347 |
+
if not self._show_mem_addr:
|
| 348 |
+
cls = self.__class__
|
| 349 |
+
r = "<%s.%s object>" % (cls.__module__, cls.__name__)
|
| 350 |
+
else:
|
| 351 |
+
r = super(DisplayObject, self).__repr__()
|
| 352 |
+
return r
|
| 353 |
+
|
| 354 |
+
def _check_data(self):
|
| 355 |
+
"""Override in subclasses if there's something to check."""
|
| 356 |
+
pass
|
| 357 |
+
|
| 358 |
+
def _data_and_metadata(self):
|
| 359 |
+
"""shortcut for returning metadata with shape information, if defined"""
|
| 360 |
+
if self.metadata:
|
| 361 |
+
return self.data, deepcopy(self.metadata)
|
| 362 |
+
else:
|
| 363 |
+
return self.data
|
| 364 |
+
|
| 365 |
+
def reload(self):
|
| 366 |
+
"""Reload the raw data from file or URL."""
|
| 367 |
+
if self.filename is not None:
|
| 368 |
+
encoding = None if "b" in self._read_flags else "utf-8"
|
| 369 |
+
with open(self.filename, self._read_flags, encoding=encoding) as f:
|
| 370 |
+
self.data = f.read()
|
| 371 |
+
elif self.url is not None:
|
| 372 |
+
# Deferred import
|
| 373 |
+
from urllib.request import urlopen
|
| 374 |
+
response = urlopen(self.url)
|
| 375 |
+
data = response.read()
|
| 376 |
+
# extract encoding from header, if there is one:
|
| 377 |
+
encoding = None
|
| 378 |
+
if 'content-type' in response.headers:
|
| 379 |
+
for sub in response.headers['content-type'].split(';'):
|
| 380 |
+
sub = sub.strip()
|
| 381 |
+
if sub.startswith('charset'):
|
| 382 |
+
encoding = sub.split('=')[-1].strip()
|
| 383 |
+
break
|
| 384 |
+
if 'content-encoding' in response.headers:
|
| 385 |
+
# TODO: do deflate?
|
| 386 |
+
if 'gzip' in response.headers['content-encoding']:
|
| 387 |
+
import gzip
|
| 388 |
+
from io import BytesIO
|
| 389 |
+
|
| 390 |
+
# assume utf-8 if encoding is not specified
|
| 391 |
+
with gzip.open(
|
| 392 |
+
BytesIO(data), "rt", encoding=encoding or "utf-8"
|
| 393 |
+
) as fp:
|
| 394 |
+
encoding = None
|
| 395 |
+
data = fp.read()
|
| 396 |
+
|
| 397 |
+
# decode data, if an encoding was specified
|
| 398 |
+
# We only touch self.data once since
|
| 399 |
+
# subclasses such as SVG have @data.setter methods
|
| 400 |
+
# that transform self.data into ... well svg.
|
| 401 |
+
if encoding:
|
| 402 |
+
self.data = data.decode(encoding, 'replace')
|
| 403 |
+
else:
|
| 404 |
+
self.data = data
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
class TextDisplayObject(DisplayObject):
|
| 408 |
+
"""Create a text display object given raw data.
|
| 409 |
+
|
| 410 |
+
Parameters
|
| 411 |
+
----------
|
| 412 |
+
data : str or unicode
|
| 413 |
+
The raw data or a URL or file to load the data from.
|
| 414 |
+
url : unicode
|
| 415 |
+
A URL to download the data from.
|
| 416 |
+
filename : unicode
|
| 417 |
+
Path to a local file to load the data from.
|
| 418 |
+
metadata : dict
|
| 419 |
+
Dict of metadata associated to be the object when displayed
|
| 420 |
+
"""
|
| 421 |
+
def _check_data(self):
|
| 422 |
+
if self.data is not None and not isinstance(self.data, str):
|
| 423 |
+
raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data))
|
| 424 |
+
|
| 425 |
+
class Pretty(TextDisplayObject):
|
| 426 |
+
|
| 427 |
+
def _repr_pretty_(self, pp, cycle):
|
| 428 |
+
return pp.text(self.data)
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
class HTML(TextDisplayObject):
|
| 432 |
+
|
| 433 |
+
def __init__(self, data=None, url=None, filename=None, metadata=None):
|
| 434 |
+
def warn():
|
| 435 |
+
if not data:
|
| 436 |
+
return False
|
| 437 |
+
|
| 438 |
+
#
|
| 439 |
+
# Avoid calling lower() on the entire data, because it could be a
|
| 440 |
+
# long string and we're only interested in its beginning and end.
|
| 441 |
+
#
|
| 442 |
+
prefix = data[:10].lower()
|
| 443 |
+
suffix = data[-10:].lower()
|
| 444 |
+
return prefix.startswith("<iframe ") and suffix.endswith("</iframe>")
|
| 445 |
+
|
| 446 |
+
if warn():
|
| 447 |
+
warnings.warn("Consider using IPython.display.IFrame instead")
|
| 448 |
+
super(HTML, self).__init__(data=data, url=url, filename=filename, metadata=metadata)
|
| 449 |
+
|
| 450 |
+
def _repr_html_(self):
|
| 451 |
+
return self._data_and_metadata()
|
| 452 |
+
|
| 453 |
+
def __html__(self):
|
| 454 |
+
"""
|
| 455 |
+
This method exists to inform other HTML-using modules (e.g. Markupsafe,
|
| 456 |
+
htmltag, etc) that this object is HTML and does not need things like
|
| 457 |
+
special characters (<>&) escaped.
|
| 458 |
+
"""
|
| 459 |
+
return self._repr_html_()
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
class Markdown(TextDisplayObject):
|
| 463 |
+
|
| 464 |
+
def _repr_markdown_(self):
|
| 465 |
+
return self._data_and_metadata()
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
class Math(TextDisplayObject):
|
| 469 |
+
|
| 470 |
+
def _repr_latex_(self):
|
| 471 |
+
s = r"$\displaystyle %s$" % self.data.strip('$')
|
| 472 |
+
if self.metadata:
|
| 473 |
+
return s, deepcopy(self.metadata)
|
| 474 |
+
else:
|
| 475 |
+
return s
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
class Latex(TextDisplayObject):
|
| 479 |
+
|
| 480 |
+
def _repr_latex_(self):
|
| 481 |
+
return self._data_and_metadata()
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
class SVG(DisplayObject):
|
| 485 |
+
"""Embed an SVG into the display.
|
| 486 |
+
|
| 487 |
+
Note if you just want to view a svg image via a URL use `:class:Image` with
|
| 488 |
+
a url=URL keyword argument.
|
| 489 |
+
"""
|
| 490 |
+
|
| 491 |
+
_read_flags = 'rb'
|
| 492 |
+
# wrap data in a property, which extracts the <svg> tag, discarding
|
| 493 |
+
# document headers
|
| 494 |
+
_data: Optional[str] = None
|
| 495 |
+
|
| 496 |
+
@property
|
| 497 |
+
def data(self):
|
| 498 |
+
return self._data
|
| 499 |
+
|
| 500 |
+
@data.setter
|
| 501 |
+
def data(self, svg):
|
| 502 |
+
if svg is None:
|
| 503 |
+
self._data = None
|
| 504 |
+
return
|
| 505 |
+
# parse into dom object
|
| 506 |
+
from xml.dom import minidom
|
| 507 |
+
x = minidom.parseString(svg)
|
| 508 |
+
# get svg tag (should be 1)
|
| 509 |
+
found_svg = x.getElementsByTagName('svg')
|
| 510 |
+
if found_svg:
|
| 511 |
+
svg = found_svg[0].toxml()
|
| 512 |
+
else:
|
| 513 |
+
# fallback on the input, trust the user
|
| 514 |
+
# but this is probably an error.
|
| 515 |
+
pass
|
| 516 |
+
if isinstance(svg, bytes):
|
| 517 |
+
self._data = svg.decode(errors="replace")
|
| 518 |
+
else:
|
| 519 |
+
self._data = svg
|
| 520 |
+
|
| 521 |
+
def _repr_svg_(self):
|
| 522 |
+
return self._data_and_metadata()
|
| 523 |
+
|
| 524 |
+
class ProgressBar(DisplayObject):
|
| 525 |
+
"""Progressbar supports displaying a progressbar like element
|
| 526 |
+
"""
|
| 527 |
+
def __init__(self, total):
|
| 528 |
+
"""Creates a new progressbar
|
| 529 |
+
|
| 530 |
+
Parameters
|
| 531 |
+
----------
|
| 532 |
+
total : int
|
| 533 |
+
maximum size of the progressbar
|
| 534 |
+
"""
|
| 535 |
+
self.total = total
|
| 536 |
+
self._progress = 0
|
| 537 |
+
self.html_width = '60ex'
|
| 538 |
+
self.text_width = 60
|
| 539 |
+
self._display_id = hexlify(os.urandom(8)).decode('ascii')
|
| 540 |
+
|
| 541 |
+
def __repr__(self):
|
| 542 |
+
fraction = self.progress / self.total
|
| 543 |
+
filled = '=' * int(fraction * self.text_width)
|
| 544 |
+
rest = ' ' * (self.text_width - len(filled))
|
| 545 |
+
return '[{}{}] {}/{}'.format(
|
| 546 |
+
filled, rest,
|
| 547 |
+
self.progress, self.total,
|
| 548 |
+
)
|
| 549 |
+
|
| 550 |
+
def _repr_html_(self):
|
| 551 |
+
return "<progress style='width:{}' max='{}' value='{}'></progress>".format(
|
| 552 |
+
self.html_width, self.total, self.progress)
|
| 553 |
+
|
| 554 |
+
def display(self):
|
| 555 |
+
display_functions.display(self, display_id=self._display_id)
|
| 556 |
+
|
| 557 |
+
def update(self):
|
| 558 |
+
display_functions.display(self, display_id=self._display_id, update=True)
|
| 559 |
+
|
| 560 |
+
@property
|
| 561 |
+
def progress(self):
|
| 562 |
+
return self._progress
|
| 563 |
+
|
| 564 |
+
@progress.setter
|
| 565 |
+
def progress(self, value):
|
| 566 |
+
self._progress = value
|
| 567 |
+
self.update()
|
| 568 |
+
|
| 569 |
+
def __iter__(self):
|
| 570 |
+
self.display()
|
| 571 |
+
self._progress = -1 # First iteration is 0
|
| 572 |
+
return self
|
| 573 |
+
|
| 574 |
+
def __next__(self):
|
| 575 |
+
"""Returns current value and increments display by one."""
|
| 576 |
+
self.progress += 1
|
| 577 |
+
if self.progress < self.total:
|
| 578 |
+
return self.progress
|
| 579 |
+
else:
|
| 580 |
+
raise StopIteration()
|
| 581 |
+
|
| 582 |
+
class JSON(DisplayObject):
|
| 583 |
+
"""JSON expects a JSON-able dict or list
|
| 584 |
+
|
| 585 |
+
not an already-serialized JSON string.
|
| 586 |
+
|
| 587 |
+
Scalar types (None, number, string) are not allowed, only dict or list containers.
|
| 588 |
+
"""
|
| 589 |
+
# wrap data in a property, which warns about passing already-serialized JSON
|
| 590 |
+
_data = None
|
| 591 |
+
def __init__(self, data=None, url=None, filename=None, expanded=False, metadata=None, root='root', **kwargs):
|
| 592 |
+
"""Create a JSON display object given raw data.
|
| 593 |
+
|
| 594 |
+
Parameters
|
| 595 |
+
----------
|
| 596 |
+
data : dict or list
|
| 597 |
+
JSON data to display. Not an already-serialized JSON string.
|
| 598 |
+
Scalar types (None, number, string) are not allowed, only dict
|
| 599 |
+
or list containers.
|
| 600 |
+
url : unicode
|
| 601 |
+
A URL to download the data from.
|
| 602 |
+
filename : unicode
|
| 603 |
+
Path to a local file to load the data from.
|
| 604 |
+
expanded : boolean
|
| 605 |
+
Metadata to control whether a JSON display component is expanded.
|
| 606 |
+
metadata : dict
|
| 607 |
+
Specify extra metadata to attach to the json display object.
|
| 608 |
+
root : str
|
| 609 |
+
The name of the root element of the JSON tree
|
| 610 |
+
"""
|
| 611 |
+
self.metadata = {
|
| 612 |
+
'expanded': expanded,
|
| 613 |
+
'root': root,
|
| 614 |
+
}
|
| 615 |
+
if metadata:
|
| 616 |
+
self.metadata.update(metadata)
|
| 617 |
+
if kwargs:
|
| 618 |
+
self.metadata.update(kwargs)
|
| 619 |
+
super(JSON, self).__init__(data=data, url=url, filename=filename)
|
| 620 |
+
|
| 621 |
+
def _check_data(self):
|
| 622 |
+
if self.data is not None and not isinstance(self.data, (dict, list)):
|
| 623 |
+
raise TypeError("%s expects JSONable dict or list, not %r" % (self.__class__.__name__, self.data))
|
| 624 |
+
|
| 625 |
+
@property
|
| 626 |
+
def data(self):
|
| 627 |
+
return self._data
|
| 628 |
+
|
| 629 |
+
@data.setter
|
| 630 |
+
def data(self, data):
|
| 631 |
+
if isinstance(data, (Path, PurePath)):
|
| 632 |
+
data = str(data)
|
| 633 |
+
|
| 634 |
+
if isinstance(data, str):
|
| 635 |
+
if self.filename is None and self.url is None:
|
| 636 |
+
warnings.warn("JSON expects JSONable dict or list, not JSON strings")
|
| 637 |
+
data = json.loads(data)
|
| 638 |
+
self._data = data
|
| 639 |
+
|
| 640 |
+
def _data_and_metadata(self):
|
| 641 |
+
return self.data, self.metadata
|
| 642 |
+
|
| 643 |
+
def _repr_json_(self):
|
| 644 |
+
return self._data_and_metadata()
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
_css_t = """var link = document.createElement("link");
|
| 648 |
+
link.rel = "stylesheet";
|
| 649 |
+
link.type = "text/css";
|
| 650 |
+
link.href = "%s";
|
| 651 |
+
document.head.appendChild(link);
|
| 652 |
+
"""
|
| 653 |
+
|
| 654 |
+
_lib_t1 = """new Promise(function(resolve, reject) {
|
| 655 |
+
var script = document.createElement("script");
|
| 656 |
+
script.onload = resolve;
|
| 657 |
+
script.onerror = reject;
|
| 658 |
+
script.src = "%s";
|
| 659 |
+
document.head.appendChild(script);
|
| 660 |
+
}).then(() => {
|
| 661 |
+
"""
|
| 662 |
+
|
| 663 |
+
_lib_t2 = """
|
| 664 |
+
});"""
|
| 665 |
+
|
| 666 |
+
class GeoJSON(JSON):
|
| 667 |
+
"""GeoJSON expects JSON-able dict
|
| 668 |
+
|
| 669 |
+
not an already-serialized JSON string.
|
| 670 |
+
|
| 671 |
+
Scalar types (None, number, string) are not allowed, only dict containers.
|
| 672 |
+
"""
|
| 673 |
+
|
| 674 |
+
def __init__(self, *args, **kwargs):
|
| 675 |
+
"""Create a GeoJSON display object given raw data.
|
| 676 |
+
|
| 677 |
+
Parameters
|
| 678 |
+
----------
|
| 679 |
+
data : dict or list
|
| 680 |
+
VegaLite data. Not an already-serialized JSON string.
|
| 681 |
+
Scalar types (None, number, string) are not allowed, only dict
|
| 682 |
+
or list containers.
|
| 683 |
+
url_template : string
|
| 684 |
+
Leaflet TileLayer URL template: http://leafletjs.com/reference.html#url-template
|
| 685 |
+
layer_options : dict
|
| 686 |
+
Leaflet TileLayer options: http://leafletjs.com/reference.html#tilelayer-options
|
| 687 |
+
url : unicode
|
| 688 |
+
A URL to download the data from.
|
| 689 |
+
filename : unicode
|
| 690 |
+
Path to a local file to load the data from.
|
| 691 |
+
metadata : dict
|
| 692 |
+
Specify extra metadata to attach to the json display object.
|
| 693 |
+
|
| 694 |
+
Examples
|
| 695 |
+
--------
|
| 696 |
+
The following will display an interactive map of Mars with a point of
|
| 697 |
+
interest on frontend that do support GeoJSON display.
|
| 698 |
+
|
| 699 |
+
>>> from IPython.display import GeoJSON
|
| 700 |
+
|
| 701 |
+
>>> GeoJSON(data={
|
| 702 |
+
... "type": "Feature",
|
| 703 |
+
... "geometry": {
|
| 704 |
+
... "type": "Point",
|
| 705 |
+
... "coordinates": [-81.327, 296.038]
|
| 706 |
+
... }
|
| 707 |
+
... },
|
| 708 |
+
... url_template="http://s3-eu-west-1.amazonaws.com/whereonmars.cartodb.net/{basemap_id}/{z}/{x}/{y}.png",
|
| 709 |
+
... layer_options={
|
| 710 |
+
... "basemap_id": "celestia_mars-shaded-16k_global",
|
| 711 |
+
... "attribution" : "Celestia/praesepe",
|
| 712 |
+
... "minZoom" : 0,
|
| 713 |
+
... "maxZoom" : 18,
|
| 714 |
+
... })
|
| 715 |
+
<IPython.core.display.GeoJSON object>
|
| 716 |
+
|
| 717 |
+
In the terminal IPython, you will only see the text representation of
|
| 718 |
+
the GeoJSON object.
|
| 719 |
+
|
| 720 |
+
"""
|
| 721 |
+
|
| 722 |
+
super(GeoJSON, self).__init__(*args, **kwargs)
|
| 723 |
+
|
| 724 |
+
|
| 725 |
+
def _ipython_display_(self):
|
| 726 |
+
bundle = {
|
| 727 |
+
'application/geo+json': self.data,
|
| 728 |
+
'text/plain': '<IPython.display.GeoJSON object>'
|
| 729 |
+
}
|
| 730 |
+
metadata = {
|
| 731 |
+
'application/geo+json': self.metadata
|
| 732 |
+
}
|
| 733 |
+
display_functions.display(bundle, metadata=metadata, raw=True)
|
| 734 |
+
|
| 735 |
+
class Javascript(TextDisplayObject):
|
| 736 |
+
|
| 737 |
+
def __init__(self, data=None, url=None, filename=None, lib=None, css=None):
|
| 738 |
+
"""Create a Javascript display object given raw data.
|
| 739 |
+
|
| 740 |
+
When this object is returned by an expression or passed to the
|
| 741 |
+
display function, it will result in the data being displayed
|
| 742 |
+
in the frontend. If the data is a URL, the data will first be
|
| 743 |
+
downloaded and then displayed.
|
| 744 |
+
|
| 745 |
+
In the Notebook, the containing element will be available as `element`,
|
| 746 |
+
and jQuery will be available. Content appended to `element` will be
|
| 747 |
+
visible in the output area.
|
| 748 |
+
|
| 749 |
+
Parameters
|
| 750 |
+
----------
|
| 751 |
+
data : unicode, str or bytes
|
| 752 |
+
The Javascript source code or a URL to download it from.
|
| 753 |
+
url : unicode
|
| 754 |
+
A URL to download the data from.
|
| 755 |
+
filename : unicode
|
| 756 |
+
Path to a local file to load the data from.
|
| 757 |
+
lib : list or str
|
| 758 |
+
A sequence of Javascript library URLs to load asynchronously before
|
| 759 |
+
running the source code. The full URLs of the libraries should
|
| 760 |
+
be given. A single Javascript library URL can also be given as a
|
| 761 |
+
string.
|
| 762 |
+
css : list or str
|
| 763 |
+
A sequence of css files to load before running the source code.
|
| 764 |
+
The full URLs of the css files should be given. A single css URL
|
| 765 |
+
can also be given as a string.
|
| 766 |
+
"""
|
| 767 |
+
if isinstance(lib, str):
|
| 768 |
+
lib = [lib]
|
| 769 |
+
elif lib is None:
|
| 770 |
+
lib = []
|
| 771 |
+
if isinstance(css, str):
|
| 772 |
+
css = [css]
|
| 773 |
+
elif css is None:
|
| 774 |
+
css = []
|
| 775 |
+
if not isinstance(lib, (list,tuple)):
|
| 776 |
+
raise TypeError('expected sequence, got: %r' % lib)
|
| 777 |
+
if not isinstance(css, (list,tuple)):
|
| 778 |
+
raise TypeError('expected sequence, got: %r' % css)
|
| 779 |
+
self.lib = lib
|
| 780 |
+
self.css = css
|
| 781 |
+
super(Javascript, self).__init__(data=data, url=url, filename=filename)
|
| 782 |
+
|
| 783 |
+
def _repr_javascript_(self):
|
| 784 |
+
r = ''
|
| 785 |
+
for c in self.css:
|
| 786 |
+
r += _css_t % c
|
| 787 |
+
for l in self.lib:
|
| 788 |
+
r += _lib_t1 % l
|
| 789 |
+
r += self.data
|
| 790 |
+
r += _lib_t2*len(self.lib)
|
| 791 |
+
return r
|
| 792 |
+
|
| 793 |
+
|
| 794 |
+
# constants for identifying png/jpeg/gif/webp data
|
| 795 |
+
_PNG = b"\x89PNG\r\n\x1a\n"
|
| 796 |
+
_JPEG = b"\xff\xd8"
|
| 797 |
+
_GIF1 = b"GIF87a"
|
| 798 |
+
_GIF2 = b"GIF89a"
|
| 799 |
+
_WEBP = b"WEBP"
|
| 800 |
+
|
| 801 |
+
|
| 802 |
+
def _pngxy(data):
|
| 803 |
+
"""read the (width, height) from a PNG header"""
|
| 804 |
+
ihdr = data.index(b'IHDR')
|
| 805 |
+
# next 8 bytes are width/height
|
| 806 |
+
return struct.unpack('>ii', data[ihdr+4:ihdr+12])
|
| 807 |
+
|
| 808 |
+
|
| 809 |
+
def _jpegxy(data):
|
| 810 |
+
"""read the (width, height) from a JPEG header"""
|
| 811 |
+
# adapted from http://www.64lines.com/jpeg-width-height
|
| 812 |
+
|
| 813 |
+
idx = 4
|
| 814 |
+
while True:
|
| 815 |
+
block_size = struct.unpack('>H', data[idx:idx+2])[0]
|
| 816 |
+
idx = idx + block_size
|
| 817 |
+
if data[idx:idx+2] == b'\xFF\xC0':
|
| 818 |
+
# found Start of Frame
|
| 819 |
+
iSOF = idx
|
| 820 |
+
break
|
| 821 |
+
else:
|
| 822 |
+
# read another block
|
| 823 |
+
idx += 2
|
| 824 |
+
|
| 825 |
+
h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9])
|
| 826 |
+
return w, h
|
| 827 |
+
|
| 828 |
+
|
| 829 |
+
def _gifxy(data):
|
| 830 |
+
"""read the (width, height) from a GIF header"""
|
| 831 |
+
return struct.unpack('<HH', data[6:10])
|
| 832 |
+
|
| 833 |
+
|
| 834 |
+
def _webpxy(data):
|
| 835 |
+
"""read the (width, height) from a WEBP header"""
|
| 836 |
+
if data[12:16] == b"VP8 ":
|
| 837 |
+
width, height = struct.unpack("<HH", data[24:30])
|
| 838 |
+
width = width & 0x3FFF
|
| 839 |
+
height = height & 0x3FFF
|
| 840 |
+
return (width, height)
|
| 841 |
+
elif data[12:16] == b"VP8L":
|
| 842 |
+
size_info = struct.unpack("<I", data[21:25])[0]
|
| 843 |
+
width = 1 + ((size_info & 0x3F) << 8) | (size_info >> 24)
|
| 844 |
+
height = 1 + (
|
| 845 |
+
(((size_info >> 8) & 0xF) << 10)
|
| 846 |
+
| (((size_info >> 14) & 0x3FC) << 2)
|
| 847 |
+
| ((size_info >> 22) & 0x3)
|
| 848 |
+
)
|
| 849 |
+
return (width, height)
|
| 850 |
+
else:
|
| 851 |
+
raise ValueError("Not a valid WEBP header")
|
| 852 |
+
|
| 853 |
+
|
| 854 |
+
class Image(DisplayObject):
|
| 855 |
+
|
| 856 |
+
_read_flags = "rb"
|
| 857 |
+
_FMT_JPEG = "jpeg"
|
| 858 |
+
_FMT_PNG = "png"
|
| 859 |
+
_FMT_GIF = "gif"
|
| 860 |
+
_FMT_WEBP = "webp"
|
| 861 |
+
_ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG, _FMT_GIF, _FMT_WEBP]
|
| 862 |
+
_MIMETYPES = {
|
| 863 |
+
_FMT_PNG: "image/png",
|
| 864 |
+
_FMT_JPEG: "image/jpeg",
|
| 865 |
+
_FMT_GIF: "image/gif",
|
| 866 |
+
_FMT_WEBP: "image/webp",
|
| 867 |
+
}
|
| 868 |
+
|
| 869 |
+
def __init__(
|
| 870 |
+
self,
|
| 871 |
+
data=None,
|
| 872 |
+
url=None,
|
| 873 |
+
filename=None,
|
| 874 |
+
format=None,
|
| 875 |
+
embed=None,
|
| 876 |
+
width=None,
|
| 877 |
+
height=None,
|
| 878 |
+
retina=False,
|
| 879 |
+
unconfined=False,
|
| 880 |
+
metadata=None,
|
| 881 |
+
alt=None,
|
| 882 |
+
):
|
| 883 |
+
"""Create a PNG/JPEG/GIF/WEBP image object given raw data.
|
| 884 |
+
|
| 885 |
+
When this object is returned by an input cell or passed to the
|
| 886 |
+
display function, it will result in the image being displayed
|
| 887 |
+
in the frontend.
|
| 888 |
+
|
| 889 |
+
Parameters
|
| 890 |
+
----------
|
| 891 |
+
data : unicode, str or bytes
|
| 892 |
+
The raw image data or a URL or filename to load the data from.
|
| 893 |
+
This always results in embedded image data.
|
| 894 |
+
|
| 895 |
+
url : unicode
|
| 896 |
+
A URL to download the data from. If you specify `url=`,
|
| 897 |
+
the image data will not be embedded unless you also specify `embed=True`.
|
| 898 |
+
|
| 899 |
+
filename : unicode
|
| 900 |
+
Path to a local file to load the data from.
|
| 901 |
+
Images from a file are always embedded.
|
| 902 |
+
|
| 903 |
+
format : unicode
|
| 904 |
+
The format of the image data (png/jpeg/jpg/gif/webp). If a filename or URL is given
|
| 905 |
+
for format will be inferred from the filename extension.
|
| 906 |
+
|
| 907 |
+
embed : bool
|
| 908 |
+
Should the image data be embedded using a data URI (True) or be
|
| 909 |
+
loaded using an <img> tag. Set this to True if you want the image
|
| 910 |
+
to be viewable later with no internet connection in the notebook.
|
| 911 |
+
|
| 912 |
+
Default is `True`, unless the keyword argument `url` is set, then
|
| 913 |
+
default value is `False`.
|
| 914 |
+
|
| 915 |
+
Note that QtConsole is not able to display images if `embed` is set to `False`
|
| 916 |
+
|
| 917 |
+
width : int
|
| 918 |
+
Width in pixels to which to constrain the image in html
|
| 919 |
+
|
| 920 |
+
height : int
|
| 921 |
+
Height in pixels to which to constrain the image in html
|
| 922 |
+
|
| 923 |
+
retina : bool
|
| 924 |
+
Automatically set the width and height to half of the measured
|
| 925 |
+
width and height.
|
| 926 |
+
This only works for embedded images because it reads the width/height
|
| 927 |
+
from image data.
|
| 928 |
+
For non-embedded images, you can just set the desired display width
|
| 929 |
+
and height directly.
|
| 930 |
+
|
| 931 |
+
unconfined : bool
|
| 932 |
+
Set unconfined=True to disable max-width confinement of the image.
|
| 933 |
+
|
| 934 |
+
metadata : dict
|
| 935 |
+
Specify extra metadata to attach to the image.
|
| 936 |
+
|
| 937 |
+
alt : unicode
|
| 938 |
+
Alternative text for the image, for use by screen readers.
|
| 939 |
+
|
| 940 |
+
Examples
|
| 941 |
+
--------
|
| 942 |
+
embedded image data, works in qtconsole and notebook
|
| 943 |
+
when passed positionally, the first arg can be any of raw image data,
|
| 944 |
+
a URL, or a filename from which to load image data.
|
| 945 |
+
The result is always embedding image data for inline images.
|
| 946 |
+
|
| 947 |
+
>>> Image('https://www.google.fr/images/srpr/logo3w.png') # doctest: +SKIP
|
| 948 |
+
<IPython.core.display.Image object>
|
| 949 |
+
|
| 950 |
+
>>> Image('/path/to/image.jpg')
|
| 951 |
+
<IPython.core.display.Image object>
|
| 952 |
+
|
| 953 |
+
>>> Image(b'RAW_PNG_DATA...')
|
| 954 |
+
<IPython.core.display.Image object>
|
| 955 |
+
|
| 956 |
+
Specifying Image(url=...) does not embed the image data,
|
| 957 |
+
it only generates ``<img>`` tag with a link to the source.
|
| 958 |
+
This will not work in the qtconsole or offline.
|
| 959 |
+
|
| 960 |
+
>>> Image(url='https://www.google.fr/images/srpr/logo3w.png')
|
| 961 |
+
<IPython.core.display.Image object>
|
| 962 |
+
|
| 963 |
+
"""
|
| 964 |
+
if isinstance(data, (Path, PurePath)):
|
| 965 |
+
data = str(data)
|
| 966 |
+
|
| 967 |
+
if filename is not None:
|
| 968 |
+
ext = self._find_ext(filename)
|
| 969 |
+
elif url is not None:
|
| 970 |
+
ext = self._find_ext(url)
|
| 971 |
+
elif data is None:
|
| 972 |
+
raise ValueError("No image data found. Expecting filename, url, or data.")
|
| 973 |
+
elif isinstance(data, str) and (
|
| 974 |
+
data.startswith('http') or _safe_exists(data)
|
| 975 |
+
):
|
| 976 |
+
ext = self._find_ext(data)
|
| 977 |
+
else:
|
| 978 |
+
ext = None
|
| 979 |
+
|
| 980 |
+
if format is None:
|
| 981 |
+
if ext is not None:
|
| 982 |
+
if ext == u'jpg' or ext == u'jpeg':
|
| 983 |
+
format = self._FMT_JPEG
|
| 984 |
+
elif ext == u'png':
|
| 985 |
+
format = self._FMT_PNG
|
| 986 |
+
elif ext == u'gif':
|
| 987 |
+
format = self._FMT_GIF
|
| 988 |
+
elif ext == "webp":
|
| 989 |
+
format = self._FMT_WEBP
|
| 990 |
+
else:
|
| 991 |
+
format = ext.lower()
|
| 992 |
+
elif isinstance(data, bytes):
|
| 993 |
+
# infer image type from image data header,
|
| 994 |
+
# only if format has not been specified.
|
| 995 |
+
if data[:2] == _JPEG:
|
| 996 |
+
format = self._FMT_JPEG
|
| 997 |
+
elif data[:8] == _PNG:
|
| 998 |
+
format = self._FMT_PNG
|
| 999 |
+
elif data[8:12] == _WEBP:
|
| 1000 |
+
format = self._FMT_WEBP
|
| 1001 |
+
elif data[:6] == _GIF1 or data[:6] == _GIF2:
|
| 1002 |
+
format = self._FMT_GIF
|
| 1003 |
+
|
| 1004 |
+
# failed to detect format, default png
|
| 1005 |
+
if format is None:
|
| 1006 |
+
format = self._FMT_PNG
|
| 1007 |
+
|
| 1008 |
+
if format.lower() == 'jpg':
|
| 1009 |
+
# jpg->jpeg
|
| 1010 |
+
format = self._FMT_JPEG
|
| 1011 |
+
|
| 1012 |
+
self.format = format.lower()
|
| 1013 |
+
self.embed = embed if embed is not None else (url is None)
|
| 1014 |
+
|
| 1015 |
+
if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
|
| 1016 |
+
raise ValueError("Cannot embed the '%s' image format" % (self.format))
|
| 1017 |
+
if self.embed:
|
| 1018 |
+
self._mimetype = self._MIMETYPES.get(self.format)
|
| 1019 |
+
|
| 1020 |
+
self.width = width
|
| 1021 |
+
self.height = height
|
| 1022 |
+
self.retina = retina
|
| 1023 |
+
self.unconfined = unconfined
|
| 1024 |
+
self.alt = alt
|
| 1025 |
+
super(Image, self).__init__(data=data, url=url, filename=filename,
|
| 1026 |
+
metadata=metadata)
|
| 1027 |
+
|
| 1028 |
+
if self.width is None and self.metadata.get('width', {}):
|
| 1029 |
+
self.width = metadata['width']
|
| 1030 |
+
|
| 1031 |
+
if self.height is None and self.metadata.get('height', {}):
|
| 1032 |
+
self.height = metadata['height']
|
| 1033 |
+
|
| 1034 |
+
if self.alt is None and self.metadata.get("alt", {}):
|
| 1035 |
+
self.alt = metadata["alt"]
|
| 1036 |
+
|
| 1037 |
+
if retina:
|
| 1038 |
+
self._retina_shape()
|
| 1039 |
+
|
| 1040 |
+
|
| 1041 |
+
def _retina_shape(self):
|
| 1042 |
+
"""load pixel-doubled width and height from image data"""
|
| 1043 |
+
if not self.embed:
|
| 1044 |
+
return
|
| 1045 |
+
if self.format == self._FMT_PNG:
|
| 1046 |
+
w, h = _pngxy(self.data)
|
| 1047 |
+
elif self.format == self._FMT_JPEG:
|
| 1048 |
+
w, h = _jpegxy(self.data)
|
| 1049 |
+
elif self.format == self._FMT_GIF:
|
| 1050 |
+
w, h = _gifxy(self.data)
|
| 1051 |
+
else:
|
| 1052 |
+
# retina only supports png
|
| 1053 |
+
return
|
| 1054 |
+
self.width = w // 2
|
| 1055 |
+
self.height = h // 2
|
| 1056 |
+
|
| 1057 |
+
def reload(self):
|
| 1058 |
+
"""Reload the raw data from file or URL."""
|
| 1059 |
+
if self.embed:
|
| 1060 |
+
super(Image,self).reload()
|
| 1061 |
+
if self.retina:
|
| 1062 |
+
self._retina_shape()
|
| 1063 |
+
|
| 1064 |
+
def _repr_html_(self):
|
| 1065 |
+
if not self.embed:
|
| 1066 |
+
width = height = klass = alt = ""
|
| 1067 |
+
if self.width:
|
| 1068 |
+
width = ' width="%d"' % self.width
|
| 1069 |
+
if self.height:
|
| 1070 |
+
height = ' height="%d"' % self.height
|
| 1071 |
+
if self.unconfined:
|
| 1072 |
+
klass = ' class="unconfined"'
|
| 1073 |
+
if self.alt:
|
| 1074 |
+
alt = ' alt="%s"' % html.escape(self.alt)
|
| 1075 |
+
return '<img src="{url}"{width}{height}{klass}{alt}/>'.format(
|
| 1076 |
+
url=self.url,
|
| 1077 |
+
width=width,
|
| 1078 |
+
height=height,
|
| 1079 |
+
klass=klass,
|
| 1080 |
+
alt=alt,
|
| 1081 |
+
)
|
| 1082 |
+
|
| 1083 |
+
def _repr_mimebundle_(self, include=None, exclude=None):
|
| 1084 |
+
"""Return the image as a mimebundle
|
| 1085 |
+
|
| 1086 |
+
Any new mimetype support should be implemented here.
|
| 1087 |
+
"""
|
| 1088 |
+
if self.embed:
|
| 1089 |
+
mimetype = self._mimetype
|
| 1090 |
+
data, metadata = self._data_and_metadata(always_both=True)
|
| 1091 |
+
if metadata:
|
| 1092 |
+
metadata = {mimetype: metadata}
|
| 1093 |
+
return {mimetype: data}, metadata
|
| 1094 |
+
else:
|
| 1095 |
+
return {'text/html': self._repr_html_()}
|
| 1096 |
+
|
| 1097 |
+
def _data_and_metadata(self, always_both=False):
|
| 1098 |
+
"""shortcut for returning metadata with shape information, if defined"""
|
| 1099 |
+
try:
|
| 1100 |
+
b64_data = b2a_base64(self.data, newline=False).decode("ascii")
|
| 1101 |
+
except TypeError as e:
|
| 1102 |
+
raise FileNotFoundError(
|
| 1103 |
+
"No such file or directory: '%s'" % (self.data)) from e
|
| 1104 |
+
md = {}
|
| 1105 |
+
if self.metadata:
|
| 1106 |
+
md.update(self.metadata)
|
| 1107 |
+
if self.width:
|
| 1108 |
+
md['width'] = self.width
|
| 1109 |
+
if self.height:
|
| 1110 |
+
md['height'] = self.height
|
| 1111 |
+
if self.unconfined:
|
| 1112 |
+
md['unconfined'] = self.unconfined
|
| 1113 |
+
if self.alt:
|
| 1114 |
+
md["alt"] = self.alt
|
| 1115 |
+
if md or always_both:
|
| 1116 |
+
return b64_data, md
|
| 1117 |
+
else:
|
| 1118 |
+
return b64_data
|
| 1119 |
+
|
| 1120 |
+
def _repr_png_(self):
|
| 1121 |
+
if self.embed and self.format == self._FMT_PNG:
|
| 1122 |
+
return self._data_and_metadata()
|
| 1123 |
+
|
| 1124 |
+
def _repr_jpeg_(self):
|
| 1125 |
+
if self.embed and self.format == self._FMT_JPEG:
|
| 1126 |
+
return self._data_and_metadata()
|
| 1127 |
+
|
| 1128 |
+
def _find_ext(self, s):
|
| 1129 |
+
base, ext = splitext(s)
|
| 1130 |
+
|
| 1131 |
+
if not ext:
|
| 1132 |
+
return base
|
| 1133 |
+
|
| 1134 |
+
# `splitext` includes leading period, so we skip it
|
| 1135 |
+
return ext[1:].lower()
|
| 1136 |
+
|
| 1137 |
+
|
| 1138 |
+
class Video(DisplayObject):
|
| 1139 |
+
|
| 1140 |
+
def __init__(self, data=None, url=None, filename=None, embed=False,
|
| 1141 |
+
mimetype=None, width=None, height=None, html_attributes="controls"):
|
| 1142 |
+
"""Create a video object given raw data or an URL.
|
| 1143 |
+
|
| 1144 |
+
When this object is returned by an input cell or passed to the
|
| 1145 |
+
display function, it will result in the video being displayed
|
| 1146 |
+
in the frontend.
|
| 1147 |
+
|
| 1148 |
+
Parameters
|
| 1149 |
+
----------
|
| 1150 |
+
data : unicode, str or bytes
|
| 1151 |
+
The raw video data or a URL or filename to load the data from.
|
| 1152 |
+
Raw data will require passing ``embed=True``.
|
| 1153 |
+
|
| 1154 |
+
url : unicode
|
| 1155 |
+
A URL for the video. If you specify ``url=``,
|
| 1156 |
+
the image data will not be embedded.
|
| 1157 |
+
|
| 1158 |
+
filename : unicode
|
| 1159 |
+
Path to a local file containing the video.
|
| 1160 |
+
Will be interpreted as a local URL unless ``embed=True``.
|
| 1161 |
+
|
| 1162 |
+
embed : bool
|
| 1163 |
+
Should the video be embedded using a data URI (True) or be
|
| 1164 |
+
loaded using a <video> tag (False).
|
| 1165 |
+
|
| 1166 |
+
Since videos are large, embedding them should be avoided, if possible.
|
| 1167 |
+
You must confirm embedding as your intention by passing ``embed=True``.
|
| 1168 |
+
|
| 1169 |
+
Local files can be displayed with URLs without embedding the content, via::
|
| 1170 |
+
|
| 1171 |
+
Video('./video.mp4')
|
| 1172 |
+
|
| 1173 |
+
mimetype : unicode
|
| 1174 |
+
Specify the mimetype for embedded videos.
|
| 1175 |
+
Default will be guessed from file extension, if available.
|
| 1176 |
+
|
| 1177 |
+
width : int
|
| 1178 |
+
Width in pixels to which to constrain the video in HTML.
|
| 1179 |
+
If not supplied, defaults to the width of the video.
|
| 1180 |
+
|
| 1181 |
+
height : int
|
| 1182 |
+
Height in pixels to which to constrain the video in html.
|
| 1183 |
+
If not supplied, defaults to the height of the video.
|
| 1184 |
+
|
| 1185 |
+
html_attributes : str
|
| 1186 |
+
Attributes for the HTML ``<video>`` block.
|
| 1187 |
+
Default: ``"controls"`` to get video controls.
|
| 1188 |
+
Other examples: ``"controls muted"`` for muted video with controls,
|
| 1189 |
+
``"loop autoplay"`` for looping autoplaying video without controls.
|
| 1190 |
+
|
| 1191 |
+
Examples
|
| 1192 |
+
--------
|
| 1193 |
+
::
|
| 1194 |
+
|
| 1195 |
+
Video('https://archive.org/download/Sita_Sings_the_Blues/Sita_Sings_the_Blues_small.mp4')
|
| 1196 |
+
Video('path/to/video.mp4')
|
| 1197 |
+
Video('path/to/video.mp4', embed=True)
|
| 1198 |
+
Video('path/to/video.mp4', embed=True, html_attributes="controls muted autoplay")
|
| 1199 |
+
Video(b'raw-videodata', embed=True)
|
| 1200 |
+
"""
|
| 1201 |
+
if isinstance(data, (Path, PurePath)):
|
| 1202 |
+
data = str(data)
|
| 1203 |
+
|
| 1204 |
+
if url is None and isinstance(data, str) and data.startswith(('http:', 'https:')):
|
| 1205 |
+
url = data
|
| 1206 |
+
data = None
|
| 1207 |
+
elif data is not None and os.path.exists(data):
|
| 1208 |
+
filename = data
|
| 1209 |
+
data = None
|
| 1210 |
+
|
| 1211 |
+
if data and not embed:
|
| 1212 |
+
msg = ''.join([
|
| 1213 |
+
"To embed videos, you must pass embed=True ",
|
| 1214 |
+
"(this may make your notebook files huge)\n",
|
| 1215 |
+
"Consider passing Video(url='...')",
|
| 1216 |
+
])
|
| 1217 |
+
raise ValueError(msg)
|
| 1218 |
+
|
| 1219 |
+
self.mimetype = mimetype
|
| 1220 |
+
self.embed = embed
|
| 1221 |
+
self.width = width
|
| 1222 |
+
self.height = height
|
| 1223 |
+
self.html_attributes = html_attributes
|
| 1224 |
+
super(Video, self).__init__(data=data, url=url, filename=filename)
|
| 1225 |
+
|
| 1226 |
+
def _repr_html_(self):
|
| 1227 |
+
width = height = ''
|
| 1228 |
+
if self.width:
|
| 1229 |
+
width = ' width="%d"' % self.width
|
| 1230 |
+
if self.height:
|
| 1231 |
+
height = ' height="%d"' % self.height
|
| 1232 |
+
|
| 1233 |
+
# External URLs and potentially local files are not embedded into the
|
| 1234 |
+
# notebook output.
|
| 1235 |
+
if not self.embed:
|
| 1236 |
+
url = self.url if self.url is not None else self.filename
|
| 1237 |
+
output = """<video src="{0}" {1} {2} {3}>
|
| 1238 |
+
Your browser does not support the <code>video</code> element.
|
| 1239 |
+
</video>""".format(url, self.html_attributes, width, height)
|
| 1240 |
+
return output
|
| 1241 |
+
|
| 1242 |
+
# Embedded videos are base64-encoded.
|
| 1243 |
+
mimetype = self.mimetype
|
| 1244 |
+
if self.filename is not None:
|
| 1245 |
+
if not mimetype:
|
| 1246 |
+
mimetype, _ = mimetypes.guess_type(self.filename)
|
| 1247 |
+
|
| 1248 |
+
with open(self.filename, 'rb') as f:
|
| 1249 |
+
video = f.read()
|
| 1250 |
+
else:
|
| 1251 |
+
video = self.data
|
| 1252 |
+
if isinstance(video, str):
|
| 1253 |
+
# unicode input is already b64-encoded
|
| 1254 |
+
b64_video = video
|
| 1255 |
+
else:
|
| 1256 |
+
b64_video = b2a_base64(video, newline=False).decode("ascii").rstrip()
|
| 1257 |
+
|
| 1258 |
+
output = """<video {0} {1} {2}>
|
| 1259 |
+
<source src="data:{3};base64,{4}" type="{3}">
|
| 1260 |
+
Your browser does not support the video tag.
|
| 1261 |
+
</video>""".format(self.html_attributes, width, height, mimetype, b64_video)
|
| 1262 |
+
return output
|
| 1263 |
+
|
| 1264 |
+
def reload(self):
|
| 1265 |
+
# TODO
|
| 1266 |
+
pass
|
lib/python3.12/site-packages/IPython/core/display_functions.py
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Top-level display functions for displaying object in different formats."""
|
| 2 |
+
|
| 3 |
+
# Copyright (c) IPython Development Team.
|
| 4 |
+
# Distributed under the terms of the Modified BSD License.
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
from binascii import b2a_hex
|
| 8 |
+
import os
|
| 9 |
+
import sys
|
| 10 |
+
import warnings
|
| 11 |
+
|
| 12 |
+
__all__ = ['display', 'clear_output', 'publish_display_data', 'update_display', 'DisplayHandle']
|
| 13 |
+
|
| 14 |
+
#-----------------------------------------------------------------------------
|
| 15 |
+
# utility functions
|
| 16 |
+
#-----------------------------------------------------------------------------
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _merge(d1, d2):
|
| 20 |
+
"""Like update, but merges sub-dicts instead of clobbering at the top level.
|
| 21 |
+
|
| 22 |
+
Updates d1 in-place
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
if not isinstance(d2, dict) or not isinstance(d1, dict):
|
| 26 |
+
return d2
|
| 27 |
+
for key, value in d2.items():
|
| 28 |
+
d1[key] = _merge(d1.get(key), value)
|
| 29 |
+
return d1
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
#-----------------------------------------------------------------------------
|
| 33 |
+
# Main functions
|
| 34 |
+
#-----------------------------------------------------------------------------
|
| 35 |
+
|
| 36 |
+
# use * to indicate transient is keyword-only
|
| 37 |
+
def publish_display_data(data, metadata=None, *, transient=None, **kwargs):
|
| 38 |
+
"""Publish data and metadata to all frontends.
|
| 39 |
+
|
| 40 |
+
See the ``display_data`` message in the messaging documentation for
|
| 41 |
+
more details about this message type.
|
| 42 |
+
|
| 43 |
+
Keys of data and metadata can be any mime-type.
|
| 44 |
+
|
| 45 |
+
Parameters
|
| 46 |
+
----------
|
| 47 |
+
data : dict
|
| 48 |
+
A dictionary having keys that are valid MIME types (like
|
| 49 |
+
'text/plain' or 'image/svg+xml') and values that are the data for
|
| 50 |
+
that MIME type. The data itself must be a JSON'able data
|
| 51 |
+
structure. Minimally all data should have the 'text/plain' data,
|
| 52 |
+
which can be displayed by all frontends. If more than the plain
|
| 53 |
+
text is given, it is up to the frontend to decide which
|
| 54 |
+
representation to use.
|
| 55 |
+
metadata : dict
|
| 56 |
+
A dictionary for metadata related to the data. This can contain
|
| 57 |
+
arbitrary key, value pairs that frontends can use to interpret
|
| 58 |
+
the data. mime-type keys matching those in data can be used
|
| 59 |
+
to specify metadata about particular representations.
|
| 60 |
+
transient : dict, keyword-only
|
| 61 |
+
A dictionary of transient data, such as display_id.
|
| 62 |
+
"""
|
| 63 |
+
from IPython.core.interactiveshell import InteractiveShell
|
| 64 |
+
|
| 65 |
+
display_pub = InteractiveShell.instance().display_pub
|
| 66 |
+
|
| 67 |
+
# only pass transient if supplied,
|
| 68 |
+
# to avoid errors with older ipykernel.
|
| 69 |
+
# TODO: We could check for ipykernel version and provide a detailed upgrade message.
|
| 70 |
+
if transient:
|
| 71 |
+
kwargs['transient'] = transient
|
| 72 |
+
|
| 73 |
+
display_pub.publish(
|
| 74 |
+
data=data,
|
| 75 |
+
metadata=metadata,
|
| 76 |
+
**kwargs
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _new_id():
|
| 81 |
+
"""Generate a new random text id with urandom"""
|
| 82 |
+
return b2a_hex(os.urandom(16)).decode('ascii')
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def display(
|
| 86 |
+
*objs,
|
| 87 |
+
include=None,
|
| 88 |
+
exclude=None,
|
| 89 |
+
metadata=None,
|
| 90 |
+
transient=None,
|
| 91 |
+
display_id=None,
|
| 92 |
+
raw=False,
|
| 93 |
+
clear=False,
|
| 94 |
+
**kwargs,
|
| 95 |
+
):
|
| 96 |
+
"""Display a Python object in all frontends.
|
| 97 |
+
|
| 98 |
+
By default all representations will be computed and sent to the frontends.
|
| 99 |
+
Frontends can decide which representation is used and how.
|
| 100 |
+
|
| 101 |
+
In terminal IPython this will be similar to using :func:`print`, for use in richer
|
| 102 |
+
frontends see Jupyter notebook examples with rich display logic.
|
| 103 |
+
|
| 104 |
+
Parameters
|
| 105 |
+
----------
|
| 106 |
+
*objs : object
|
| 107 |
+
The Python objects to display.
|
| 108 |
+
raw : bool, optional
|
| 109 |
+
Are the objects to be displayed already mimetype-keyed dicts of raw display data,
|
| 110 |
+
or Python objects that need to be formatted before display? [default: False]
|
| 111 |
+
include : list, tuple or set, optional
|
| 112 |
+
A list of format type strings (MIME types) to include in the
|
| 113 |
+
format data dict. If this is set *only* the format types included
|
| 114 |
+
in this list will be computed.
|
| 115 |
+
exclude : list, tuple or set, optional
|
| 116 |
+
A list of format type strings (MIME types) to exclude in the format
|
| 117 |
+
data dict. If this is set all format types will be computed,
|
| 118 |
+
except for those included in this argument.
|
| 119 |
+
metadata : dict, optional
|
| 120 |
+
A dictionary of metadata to associate with the output.
|
| 121 |
+
mime-type keys in this dictionary will be associated with the individual
|
| 122 |
+
representation formats, if they exist.
|
| 123 |
+
transient : dict, optional
|
| 124 |
+
A dictionary of transient data to associate with the output.
|
| 125 |
+
Data in this dict should not be persisted to files (e.g. notebooks).
|
| 126 |
+
display_id : str, bool optional
|
| 127 |
+
Set an id for the display.
|
| 128 |
+
This id can be used for updating this display area later via update_display.
|
| 129 |
+
If given as `True`, generate a new `display_id`
|
| 130 |
+
clear : bool, optional
|
| 131 |
+
Should the output area be cleared before displaying anything? If True,
|
| 132 |
+
this will wait for additional output before clearing. [default: False]
|
| 133 |
+
**kwargs : additional keyword-args, optional
|
| 134 |
+
Additional keyword-arguments are passed through to the display publisher.
|
| 135 |
+
|
| 136 |
+
Returns
|
| 137 |
+
-------
|
| 138 |
+
handle: DisplayHandle
|
| 139 |
+
Returns a handle on updatable displays for use with :func:`update_display`,
|
| 140 |
+
if `display_id` is given. Returns :py:data:`None` if no `display_id` is given
|
| 141 |
+
(default).
|
| 142 |
+
|
| 143 |
+
Examples
|
| 144 |
+
--------
|
| 145 |
+
>>> class Json(object):
|
| 146 |
+
... def __init__(self, json):
|
| 147 |
+
... self.json = json
|
| 148 |
+
... def _repr_pretty_(self, pp, cycle):
|
| 149 |
+
... import json
|
| 150 |
+
... pp.text(json.dumps(self.json, indent=2))
|
| 151 |
+
... def __repr__(self):
|
| 152 |
+
... return str(self.json)
|
| 153 |
+
...
|
| 154 |
+
|
| 155 |
+
>>> d = Json({1:2, 3: {4:5}})
|
| 156 |
+
|
| 157 |
+
>>> print(d)
|
| 158 |
+
{1: 2, 3: {4: 5}}
|
| 159 |
+
|
| 160 |
+
>>> display(d)
|
| 161 |
+
{
|
| 162 |
+
"1": 2,
|
| 163 |
+
"3": {
|
| 164 |
+
"4": 5
|
| 165 |
+
}
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
>>> def int_formatter(integer, pp, cycle):
|
| 169 |
+
... pp.text('I'*integer)
|
| 170 |
+
|
| 171 |
+
>>> plain = get_ipython().display_formatter.formatters['text/plain']
|
| 172 |
+
>>> plain.for_type(int, int_formatter)
|
| 173 |
+
<function _repr_pprint at 0x...>
|
| 174 |
+
>>> display(7-5)
|
| 175 |
+
II
|
| 176 |
+
|
| 177 |
+
>>> del plain.type_printers[int]
|
| 178 |
+
>>> display(7-5)
|
| 179 |
+
2
|
| 180 |
+
|
| 181 |
+
See Also
|
| 182 |
+
--------
|
| 183 |
+
:func:`update_display`
|
| 184 |
+
|
| 185 |
+
Notes
|
| 186 |
+
-----
|
| 187 |
+
In Python, objects can declare their textual representation using the
|
| 188 |
+
`__repr__` method. IPython expands on this idea and allows objects to declare
|
| 189 |
+
other, rich representations including:
|
| 190 |
+
|
| 191 |
+
- HTML
|
| 192 |
+
- JSON
|
| 193 |
+
- PNG
|
| 194 |
+
- JPEG
|
| 195 |
+
- SVG
|
| 196 |
+
- LaTeX
|
| 197 |
+
|
| 198 |
+
A single object can declare some or all of these representations; all are
|
| 199 |
+
handled by IPython's display system.
|
| 200 |
+
|
| 201 |
+
The main idea of the first approach is that you have to implement special
|
| 202 |
+
display methods when you define your class, one for each representation you
|
| 203 |
+
want to use. Here is a list of the names of the special methods and the
|
| 204 |
+
values they must return:
|
| 205 |
+
|
| 206 |
+
- `_repr_html_`: return raw HTML as a string, or a tuple (see below).
|
| 207 |
+
- `_repr_json_`: return a JSONable dict, or a tuple (see below).
|
| 208 |
+
- `_repr_jpeg_`: return raw JPEG data, or a tuple (see below).
|
| 209 |
+
- `_repr_png_`: return raw PNG data, or a tuple (see below).
|
| 210 |
+
- `_repr_svg_`: return raw SVG data as a string, or a tuple (see below).
|
| 211 |
+
- `_repr_latex_`: return LaTeX commands in a string surrounded by "$",
|
| 212 |
+
or a tuple (see below).
|
| 213 |
+
- `_repr_mimebundle_`: return a full mimebundle containing the mapping
|
| 214 |
+
from all mimetypes to data.
|
| 215 |
+
Use this for any mime-type not listed above.
|
| 216 |
+
|
| 217 |
+
The above functions may also return the object's metadata alonside the
|
| 218 |
+
data. If the metadata is available, the functions will return a tuple
|
| 219 |
+
containing the data and metadata, in that order. If there is no metadata
|
| 220 |
+
available, then the functions will return the data only.
|
| 221 |
+
|
| 222 |
+
When you are directly writing your own classes, you can adapt them for
|
| 223 |
+
display in IPython by following the above approach. But in practice, you
|
| 224 |
+
often need to work with existing classes that you can't easily modify.
|
| 225 |
+
|
| 226 |
+
You can refer to the documentation on integrating with the display system in
|
| 227 |
+
order to register custom formatters for already existing types
|
| 228 |
+
(:ref:`integrating_rich_display`).
|
| 229 |
+
|
| 230 |
+
.. versionadded:: 5.4 display available without import
|
| 231 |
+
.. versionadded:: 6.1 display available without import
|
| 232 |
+
|
| 233 |
+
Since IPython 5.4 and 6.1 :func:`display` is automatically made available to
|
| 234 |
+
the user without import. If you are using display in a document that might
|
| 235 |
+
be used in a pure python context or with older version of IPython, use the
|
| 236 |
+
following import at the top of your file::
|
| 237 |
+
|
| 238 |
+
from IPython.display import display
|
| 239 |
+
|
| 240 |
+
"""
|
| 241 |
+
from IPython.core.interactiveshell import InteractiveShell
|
| 242 |
+
|
| 243 |
+
if not InteractiveShell.initialized():
|
| 244 |
+
# Directly print objects.
|
| 245 |
+
print(*objs)
|
| 246 |
+
return
|
| 247 |
+
|
| 248 |
+
if transient is None:
|
| 249 |
+
transient = {}
|
| 250 |
+
if metadata is None:
|
| 251 |
+
metadata={}
|
| 252 |
+
if display_id:
|
| 253 |
+
if display_id is True:
|
| 254 |
+
display_id = _new_id()
|
| 255 |
+
transient['display_id'] = display_id
|
| 256 |
+
if kwargs.get('update') and 'display_id' not in transient:
|
| 257 |
+
raise TypeError('display_id required for update_display')
|
| 258 |
+
if transient:
|
| 259 |
+
kwargs['transient'] = transient
|
| 260 |
+
|
| 261 |
+
if not objs and display_id:
|
| 262 |
+
# if given no objects, but still a request for a display_id,
|
| 263 |
+
# we assume the user wants to insert an empty output that
|
| 264 |
+
# can be updated later
|
| 265 |
+
objs = [{}]
|
| 266 |
+
raw = True
|
| 267 |
+
|
| 268 |
+
if not raw:
|
| 269 |
+
format = InteractiveShell.instance().display_formatter.format
|
| 270 |
+
|
| 271 |
+
if clear:
|
| 272 |
+
clear_output(wait=True)
|
| 273 |
+
|
| 274 |
+
for obj in objs:
|
| 275 |
+
if raw:
|
| 276 |
+
publish_display_data(data=obj, metadata=metadata, **kwargs)
|
| 277 |
+
else:
|
| 278 |
+
format_dict, md_dict = format(obj, include=include, exclude=exclude)
|
| 279 |
+
if not format_dict:
|
| 280 |
+
# nothing to display (e.g. _ipython_display_ took over)
|
| 281 |
+
continue
|
| 282 |
+
if metadata:
|
| 283 |
+
# kwarg-specified metadata gets precedence
|
| 284 |
+
_merge(md_dict, metadata)
|
| 285 |
+
publish_display_data(data=format_dict, metadata=md_dict, **kwargs)
|
| 286 |
+
if display_id:
|
| 287 |
+
return DisplayHandle(display_id)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
# use * for keyword-only display_id arg
|
| 291 |
+
def update_display(obj, *, display_id, **kwargs):
|
| 292 |
+
"""Update an existing display by id
|
| 293 |
+
|
| 294 |
+
Parameters
|
| 295 |
+
----------
|
| 296 |
+
obj
|
| 297 |
+
The object with which to update the display
|
| 298 |
+
display_id : keyword-only
|
| 299 |
+
The id of the display to update
|
| 300 |
+
|
| 301 |
+
See Also
|
| 302 |
+
--------
|
| 303 |
+
:func:`display`
|
| 304 |
+
"""
|
| 305 |
+
kwargs['update'] = True
|
| 306 |
+
display(obj, display_id=display_id, **kwargs)
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
class DisplayHandle:
|
| 310 |
+
"""A handle on an updatable display
|
| 311 |
+
|
| 312 |
+
Call `.update(obj)` to display a new object.
|
| 313 |
+
|
| 314 |
+
Call `.display(obj`) to add a new instance of this display,
|
| 315 |
+
and update existing instances.
|
| 316 |
+
|
| 317 |
+
See Also
|
| 318 |
+
--------
|
| 319 |
+
|
| 320 |
+
:func:`display`, :func:`update_display`
|
| 321 |
+
|
| 322 |
+
"""
|
| 323 |
+
|
| 324 |
+
def __init__(self, display_id=None):
|
| 325 |
+
if display_id is None:
|
| 326 |
+
display_id = _new_id()
|
| 327 |
+
self.display_id = display_id
|
| 328 |
+
|
| 329 |
+
def __repr__(self):
|
| 330 |
+
return "<%s display_id=%s>" % (self.__class__.__name__, self.display_id)
|
| 331 |
+
|
| 332 |
+
def display(self, obj, **kwargs):
|
| 333 |
+
"""Make a new display with my id, updating existing instances.
|
| 334 |
+
|
| 335 |
+
Parameters
|
| 336 |
+
----------
|
| 337 |
+
obj
|
| 338 |
+
object to display
|
| 339 |
+
**kwargs
|
| 340 |
+
additional keyword arguments passed to display
|
| 341 |
+
"""
|
| 342 |
+
display(obj, display_id=self.display_id, **kwargs)
|
| 343 |
+
|
| 344 |
+
def update(self, obj, **kwargs):
|
| 345 |
+
"""Update existing displays with my id
|
| 346 |
+
|
| 347 |
+
Parameters
|
| 348 |
+
----------
|
| 349 |
+
obj
|
| 350 |
+
object to display
|
| 351 |
+
**kwargs
|
| 352 |
+
additional keyword arguments passed to update_display
|
| 353 |
+
"""
|
| 354 |
+
update_display(obj, display_id=self.display_id, **kwargs)
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def clear_output(wait=False):
|
| 358 |
+
"""Clear the output of the current cell receiving output.
|
| 359 |
+
|
| 360 |
+
Parameters
|
| 361 |
+
----------
|
| 362 |
+
wait : bool [default: false]
|
| 363 |
+
Wait to clear the output until new output is available to replace it."""
|
| 364 |
+
from IPython.core.interactiveshell import InteractiveShell
|
| 365 |
+
if InteractiveShell.initialized():
|
| 366 |
+
InteractiveShell.instance().display_pub.clear_output(wait)
|
| 367 |
+
else:
|
| 368 |
+
print('\033[2K\r', end='')
|
| 369 |
+
sys.stdout.flush()
|
| 370 |
+
print('\033[2K\r', end='')
|
| 371 |
+
sys.stderr.flush()
|
lib/python3.12/site-packages/IPython/core/display_trap.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# encoding: utf-8
|
| 2 |
+
"""
|
| 3 |
+
A context manager for handling sys.displayhook.
|
| 4 |
+
|
| 5 |
+
Authors:
|
| 6 |
+
|
| 7 |
+
* Robert Kern
|
| 8 |
+
* Brian Granger
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
#-----------------------------------------------------------------------------
|
| 12 |
+
# Copyright (C) 2008-2011 The IPython Development Team
|
| 13 |
+
#
|
| 14 |
+
# Distributed under the terms of the BSD License. The full license is in
|
| 15 |
+
# the file COPYING, distributed as part of this software.
|
| 16 |
+
#-----------------------------------------------------------------------------
|
| 17 |
+
|
| 18 |
+
#-----------------------------------------------------------------------------
|
| 19 |
+
# Imports
|
| 20 |
+
#-----------------------------------------------------------------------------
|
| 21 |
+
|
| 22 |
+
import sys
|
| 23 |
+
|
| 24 |
+
from traitlets.config.configurable import Configurable
|
| 25 |
+
from traitlets import Any
|
| 26 |
+
|
| 27 |
+
#-----------------------------------------------------------------------------
|
| 28 |
+
# Classes and functions
|
| 29 |
+
#-----------------------------------------------------------------------------
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class DisplayTrap(Configurable):
|
| 33 |
+
"""Object to manage sys.displayhook.
|
| 34 |
+
|
| 35 |
+
This came from IPython.core.kernel.display_hook, but is simplified
|
| 36 |
+
(no callbacks or formatters) until more of the core is refactored.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
hook = Any()
|
| 40 |
+
|
| 41 |
+
def __init__(self, hook=None):
|
| 42 |
+
super(DisplayTrap, self).__init__(hook=hook, config=None)
|
| 43 |
+
self.old_hook = None
|
| 44 |
+
# We define this to track if a single BuiltinTrap is nested.
|
| 45 |
+
# Only turn off the trap when the outermost call to __exit__ is made.
|
| 46 |
+
self._nested_level = 0
|
| 47 |
+
|
| 48 |
+
def __enter__(self):
|
| 49 |
+
if self._nested_level == 0:
|
| 50 |
+
self.set()
|
| 51 |
+
self._nested_level += 1
|
| 52 |
+
return self
|
| 53 |
+
|
| 54 |
+
def __exit__(self, type, value, traceback):
|
| 55 |
+
if self._nested_level == 1:
|
| 56 |
+
self.unset()
|
| 57 |
+
self._nested_level -= 1
|
| 58 |
+
# Returning False will cause exceptions to propagate
|
| 59 |
+
return False
|
| 60 |
+
|
| 61 |
+
@property
|
| 62 |
+
def is_active(self) -> bool:
|
| 63 |
+
return self._nested_level != 0
|
| 64 |
+
|
| 65 |
+
def set(self):
|
| 66 |
+
"""Set the hook."""
|
| 67 |
+
if sys.displayhook is not self.hook:
|
| 68 |
+
self.old_hook = sys.displayhook
|
| 69 |
+
sys.displayhook = self.hook
|
| 70 |
+
|
| 71 |
+
def unset(self):
|
| 72 |
+
"""Unset the hook."""
|
| 73 |
+
sys.displayhook = self.old_hook
|
| 74 |
+
|
lib/python3.12/site-packages/IPython/core/displayhook.py
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
|
| 4 |
+
This defines a callable class that IPython uses for `sys.displayhook`.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
# Copyright (c) IPython Development Team.
|
| 8 |
+
# Distributed under the terms of the Modified BSD License.
|
| 9 |
+
|
| 10 |
+
import builtins as builtin_mod
|
| 11 |
+
import sys
|
| 12 |
+
import io as _io
|
| 13 |
+
import tokenize
|
| 14 |
+
|
| 15 |
+
from traitlets.config.configurable import Configurable
|
| 16 |
+
from traitlets import Instance, Float
|
| 17 |
+
from warnings import warn
|
| 18 |
+
|
| 19 |
+
from .history import HistoryOutput
|
| 20 |
+
|
| 21 |
+
# TODO: Move the various attributes (cache_size, [others now moved]). Some
|
| 22 |
+
# of these are also attributes of InteractiveShell. They should be on ONE object
|
| 23 |
+
# only and the other objects should ask that one object for their values.
|
| 24 |
+
|
| 25 |
+
class DisplayHook(Configurable):
|
| 26 |
+
"""The custom IPython displayhook to replace sys.displayhook.
|
| 27 |
+
|
| 28 |
+
This class does many things, but the basic idea is that it is a callable
|
| 29 |
+
that gets called anytime user code returns a value.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
|
| 33 |
+
allow_none=True)
|
| 34 |
+
exec_result = Instance('IPython.core.interactiveshell.ExecutionResult',
|
| 35 |
+
allow_none=True)
|
| 36 |
+
cull_fraction = Float(0.2)
|
| 37 |
+
|
| 38 |
+
def __init__(self, shell=None, cache_size=1000, **kwargs):
|
| 39 |
+
super(DisplayHook, self).__init__(shell=shell, **kwargs)
|
| 40 |
+
self._is_active = False
|
| 41 |
+
cache_size_min = 3
|
| 42 |
+
if cache_size <= 0:
|
| 43 |
+
self.do_full_cache = 0
|
| 44 |
+
cache_size = 0
|
| 45 |
+
elif cache_size < cache_size_min:
|
| 46 |
+
self.do_full_cache = 0
|
| 47 |
+
cache_size = 0
|
| 48 |
+
warn('caching was disabled (min value for cache size is %s).' %
|
| 49 |
+
cache_size_min,stacklevel=3)
|
| 50 |
+
else:
|
| 51 |
+
self.do_full_cache = 1
|
| 52 |
+
|
| 53 |
+
self.cache_size = cache_size
|
| 54 |
+
|
| 55 |
+
# we need a reference to the user-level namespace
|
| 56 |
+
self.shell = shell
|
| 57 |
+
|
| 58 |
+
self._,self.__,self.___ = '','',''
|
| 59 |
+
|
| 60 |
+
# these are deliberately global:
|
| 61 |
+
to_user_ns = {'_':self._,'__':self.__,'___':self.___}
|
| 62 |
+
self.shell.user_ns.update(to_user_ns)
|
| 63 |
+
|
| 64 |
+
@property
|
| 65 |
+
def prompt_count(self):
|
| 66 |
+
return self.shell.execution_count - 1
|
| 67 |
+
|
| 68 |
+
#-------------------------------------------------------------------------
|
| 69 |
+
# Methods used in __call__. Override these methods to modify the behavior
|
| 70 |
+
# of the displayhook.
|
| 71 |
+
#-------------------------------------------------------------------------
|
| 72 |
+
|
| 73 |
+
def check_for_underscore(self):
|
| 74 |
+
"""Check if the user has set the '_' variable by hand."""
|
| 75 |
+
# If something injected a '_' variable in __builtin__, delete
|
| 76 |
+
# ipython's automatic one so we don't clobber that. gettext() in
|
| 77 |
+
# particular uses _, so we need to stay away from it.
|
| 78 |
+
if '_' in builtin_mod.__dict__:
|
| 79 |
+
try:
|
| 80 |
+
user_value = self.shell.user_ns['_']
|
| 81 |
+
if user_value is not self._:
|
| 82 |
+
return
|
| 83 |
+
del self.shell.user_ns['_']
|
| 84 |
+
except KeyError:
|
| 85 |
+
pass
|
| 86 |
+
|
| 87 |
+
def quiet(self):
|
| 88 |
+
"""Should we silence the display hook because of ';'?"""
|
| 89 |
+
# do not print output if input ends in ';'
|
| 90 |
+
|
| 91 |
+
try:
|
| 92 |
+
cell = self.shell.history_manager.input_hist_parsed[-1]
|
| 93 |
+
except IndexError:
|
| 94 |
+
# some uses of ipshellembed may fail here
|
| 95 |
+
return False
|
| 96 |
+
|
| 97 |
+
return self.semicolon_at_end_of_expression(cell)
|
| 98 |
+
|
| 99 |
+
@staticmethod
|
| 100 |
+
def semicolon_at_end_of_expression(expression):
|
| 101 |
+
"""Parse Python expression and detects whether last token is ';'"""
|
| 102 |
+
|
| 103 |
+
sio = _io.StringIO(expression)
|
| 104 |
+
tokens = list(tokenize.generate_tokens(sio.readline))
|
| 105 |
+
|
| 106 |
+
for token in reversed(tokens):
|
| 107 |
+
if token[0] in (tokenize.ENDMARKER, tokenize.NL, tokenize.NEWLINE, tokenize.COMMENT):
|
| 108 |
+
continue
|
| 109 |
+
if (token[0] == tokenize.OP) and (token[1] == ';'):
|
| 110 |
+
return True
|
| 111 |
+
else:
|
| 112 |
+
return False
|
| 113 |
+
|
| 114 |
+
def start_displayhook(self):
|
| 115 |
+
"""Start the displayhook, initializing resources."""
|
| 116 |
+
self._is_active = True
|
| 117 |
+
|
| 118 |
+
@property
|
| 119 |
+
def is_active(self):
|
| 120 |
+
return self._is_active
|
| 121 |
+
|
| 122 |
+
def write_output_prompt(self):
|
| 123 |
+
"""Write the output prompt.
|
| 124 |
+
|
| 125 |
+
The default implementation simply writes the prompt to
|
| 126 |
+
``sys.stdout``.
|
| 127 |
+
"""
|
| 128 |
+
# Use write, not print which adds an extra space.
|
| 129 |
+
sys.stdout.write(self.shell.separate_out)
|
| 130 |
+
outprompt = 'Out[{}]: '.format(self.shell.execution_count - 1)
|
| 131 |
+
if self.do_full_cache:
|
| 132 |
+
sys.stdout.write(outprompt)
|
| 133 |
+
|
| 134 |
+
def compute_format_data(self, result):
|
| 135 |
+
"""Compute format data of the object to be displayed.
|
| 136 |
+
|
| 137 |
+
The format data is a generalization of the :func:`repr` of an object.
|
| 138 |
+
In the default implementation the format data is a :class:`dict` of
|
| 139 |
+
key value pair where the keys are valid MIME types and the values
|
| 140 |
+
are JSON'able data structure containing the raw data for that MIME
|
| 141 |
+
type. It is up to frontends to determine pick a MIME to to use and
|
| 142 |
+
display that data in an appropriate manner.
|
| 143 |
+
|
| 144 |
+
This method only computes the format data for the object and should
|
| 145 |
+
NOT actually print or write that to a stream.
|
| 146 |
+
|
| 147 |
+
Parameters
|
| 148 |
+
----------
|
| 149 |
+
result : object
|
| 150 |
+
The Python object passed to the display hook, whose format will be
|
| 151 |
+
computed.
|
| 152 |
+
|
| 153 |
+
Returns
|
| 154 |
+
-------
|
| 155 |
+
(format_dict, md_dict) : dict
|
| 156 |
+
format_dict is a :class:`dict` whose keys are valid MIME types and values are
|
| 157 |
+
JSON'able raw data for that MIME type. It is recommended that
|
| 158 |
+
all return values of this should always include the "text/plain"
|
| 159 |
+
MIME type representation of the object.
|
| 160 |
+
md_dict is a :class:`dict` with the same MIME type keys
|
| 161 |
+
of metadata associated with each output.
|
| 162 |
+
|
| 163 |
+
"""
|
| 164 |
+
return self.shell.display_formatter.format(result)
|
| 165 |
+
|
| 166 |
+
# This can be set to True by the write_output_prompt method in a subclass
|
| 167 |
+
prompt_end_newline = False
|
| 168 |
+
|
| 169 |
+
def write_format_data(self, format_dict, md_dict=None) -> None:
|
| 170 |
+
"""Write the format data dict to the frontend.
|
| 171 |
+
|
| 172 |
+
This default version of this method simply writes the plain text
|
| 173 |
+
representation of the object to ``sys.stdout``. Subclasses should
|
| 174 |
+
override this method to send the entire `format_dict` to the
|
| 175 |
+
frontends.
|
| 176 |
+
|
| 177 |
+
Parameters
|
| 178 |
+
----------
|
| 179 |
+
format_dict : dict
|
| 180 |
+
The format dict for the object passed to `sys.displayhook`.
|
| 181 |
+
md_dict : dict (optional)
|
| 182 |
+
The metadata dict to be associated with the display data.
|
| 183 |
+
"""
|
| 184 |
+
if 'text/plain' not in format_dict:
|
| 185 |
+
# nothing to do
|
| 186 |
+
return
|
| 187 |
+
# We want to print because we want to always make sure we have a
|
| 188 |
+
# newline, even if all the prompt separators are ''. This is the
|
| 189 |
+
# standard IPython behavior.
|
| 190 |
+
result_repr = format_dict['text/plain']
|
| 191 |
+
if '\n' in result_repr:
|
| 192 |
+
# So that multi-line strings line up with the left column of
|
| 193 |
+
# the screen, instead of having the output prompt mess up
|
| 194 |
+
# their first line.
|
| 195 |
+
# We use the prompt template instead of the expanded prompt
|
| 196 |
+
# because the expansion may add ANSI escapes that will interfere
|
| 197 |
+
# with our ability to determine whether or not we should add
|
| 198 |
+
# a newline.
|
| 199 |
+
if not self.prompt_end_newline:
|
| 200 |
+
# But avoid extraneous empty lines.
|
| 201 |
+
result_repr = '\n' + result_repr
|
| 202 |
+
|
| 203 |
+
try:
|
| 204 |
+
print(result_repr)
|
| 205 |
+
except UnicodeEncodeError:
|
| 206 |
+
# If a character is not supported by the terminal encoding replace
|
| 207 |
+
# it with its \u or \x representation
|
| 208 |
+
print(result_repr.encode(sys.stdout.encoding,'backslashreplace').decode(sys.stdout.encoding))
|
| 209 |
+
|
| 210 |
+
def update_user_ns(self, result):
|
| 211 |
+
"""Update user_ns with various things like _, __, _1, etc."""
|
| 212 |
+
|
| 213 |
+
# Avoid recursive reference when displaying _oh/Out
|
| 214 |
+
if self.cache_size and result is not self.shell.user_ns['_oh']:
|
| 215 |
+
if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
|
| 216 |
+
self.cull_cache()
|
| 217 |
+
|
| 218 |
+
# Don't overwrite '_' and friends if '_' is in __builtin__
|
| 219 |
+
# (otherwise we cause buggy behavior for things like gettext). and
|
| 220 |
+
# do not overwrite _, __ or ___ if one of these has been assigned
|
| 221 |
+
# by the user.
|
| 222 |
+
update_unders = True
|
| 223 |
+
for unders in ['_'*i for i in range(1,4)]:
|
| 224 |
+
if unders not in self.shell.user_ns:
|
| 225 |
+
continue
|
| 226 |
+
if getattr(self, unders) is not self.shell.user_ns.get(unders):
|
| 227 |
+
update_unders = False
|
| 228 |
+
|
| 229 |
+
self.___ = self.__
|
| 230 |
+
self.__ = self._
|
| 231 |
+
self._ = result
|
| 232 |
+
|
| 233 |
+
if ('_' not in builtin_mod.__dict__) and (update_unders):
|
| 234 |
+
self.shell.push({'_':self._,
|
| 235 |
+
'__':self.__,
|
| 236 |
+
'___':self.___}, interactive=False)
|
| 237 |
+
|
| 238 |
+
# hackish access to top-level namespace to create _1,_2... dynamically
|
| 239 |
+
to_main = {}
|
| 240 |
+
if self.do_full_cache:
|
| 241 |
+
new_result = '_%s' % self.prompt_count
|
| 242 |
+
to_main[new_result] = result
|
| 243 |
+
self.shell.push(to_main, interactive=False)
|
| 244 |
+
self.shell.user_ns['_oh'][self.prompt_count] = result
|
| 245 |
+
|
| 246 |
+
def fill_exec_result(self, result):
|
| 247 |
+
if self.exec_result is not None:
|
| 248 |
+
self.exec_result.result = result
|
| 249 |
+
|
| 250 |
+
def log_output(self, format_dict):
|
| 251 |
+
"""Log the output."""
|
| 252 |
+
self.shell.history_manager.outputs[self.prompt_count].append(
|
| 253 |
+
HistoryOutput(output_type="execute_result", bundle=format_dict)
|
| 254 |
+
)
|
| 255 |
+
if "text/plain" not in format_dict:
|
| 256 |
+
# nothing to do
|
| 257 |
+
return
|
| 258 |
+
if self.shell.logger.log_output:
|
| 259 |
+
self.shell.logger.log_write(format_dict['text/plain'], 'output')
|
| 260 |
+
self.shell.history_manager.output_hist_reprs[self.prompt_count] = \
|
| 261 |
+
format_dict['text/plain']
|
| 262 |
+
|
| 263 |
+
def finish_displayhook(self):
|
| 264 |
+
"""Finish up all displayhook activities."""
|
| 265 |
+
sys.stdout.write(self.shell.separate_out2)
|
| 266 |
+
sys.stdout.flush()
|
| 267 |
+
self._is_active = False
|
| 268 |
+
|
| 269 |
+
def __call__(self, result=None):
|
| 270 |
+
"""Printing with history cache management.
|
| 271 |
+
|
| 272 |
+
This is invoked every time the interpreter needs to print, and is
|
| 273 |
+
activated by setting the variable sys.displayhook to it.
|
| 274 |
+
"""
|
| 275 |
+
self.check_for_underscore()
|
| 276 |
+
if result is not None and not self.quiet():
|
| 277 |
+
self.start_displayhook()
|
| 278 |
+
self.write_output_prompt()
|
| 279 |
+
format_dict, md_dict = self.compute_format_data(result)
|
| 280 |
+
self.update_user_ns(result)
|
| 281 |
+
self.fill_exec_result(result)
|
| 282 |
+
if format_dict:
|
| 283 |
+
self.write_format_data(format_dict, md_dict)
|
| 284 |
+
self.log_output(format_dict)
|
| 285 |
+
self.finish_displayhook()
|
| 286 |
+
|
| 287 |
+
def cull_cache(self):
|
| 288 |
+
"""Output cache is full, cull the oldest entries"""
|
| 289 |
+
oh = self.shell.user_ns.get('_oh', {})
|
| 290 |
+
sz = len(oh)
|
| 291 |
+
cull_count = max(int(sz * self.cull_fraction), 2)
|
| 292 |
+
warn('Output cache limit (currently {sz} entries) hit.\n'
|
| 293 |
+
'Flushing oldest {cull_count} entries.'.format(sz=sz, cull_count=cull_count))
|
| 294 |
+
|
| 295 |
+
for i, n in enumerate(sorted(oh)):
|
| 296 |
+
if i >= cull_count:
|
| 297 |
+
break
|
| 298 |
+
self.shell.user_ns.pop('_%i' % n, None)
|
| 299 |
+
oh.pop(n, None)
|
| 300 |
+
|
| 301 |
+
def flush(self):
|
| 302 |
+
if not self.do_full_cache:
|
| 303 |
+
raise ValueError("You shouldn't have reached the cache flush "
|
| 304 |
+
"if full caching is not enabled!")
|
| 305 |
+
# delete auto-generated vars from global namespace
|
| 306 |
+
|
| 307 |
+
for n in range(1,self.prompt_count + 1):
|
| 308 |
+
key = '_'+repr(n)
|
| 309 |
+
try:
|
| 310 |
+
del self.shell.user_ns_hidden[key]
|
| 311 |
+
except KeyError:
|
| 312 |
+
pass
|
| 313 |
+
try:
|
| 314 |
+
del self.shell.user_ns[key]
|
| 315 |
+
except KeyError:
|
| 316 |
+
pass
|
| 317 |
+
# In some embedded circumstances, the user_ns doesn't have the
|
| 318 |
+
# '_oh' key set up.
|
| 319 |
+
oh = self.shell.user_ns.get('_oh', None)
|
| 320 |
+
if oh is not None:
|
| 321 |
+
oh.clear()
|
| 322 |
+
|
| 323 |
+
# Release our own references to objects:
|
| 324 |
+
self._, self.__, self.___ = '', '', ''
|
| 325 |
+
|
| 326 |
+
if '_' not in builtin_mod.__dict__:
|
| 327 |
+
self.shell.user_ns.update({'_':self._,'__':self.__,'___':self.___})
|
| 328 |
+
import gc
|
| 329 |
+
# TODO: Is this really needed?
|
| 330 |
+
# IronPython blocks here forever
|
| 331 |
+
if sys.platform != "cli":
|
| 332 |
+
gc.collect()
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
class CapturingDisplayHook:
|
| 336 |
+
def __init__(self, shell, outputs=None):
|
| 337 |
+
self.shell = shell
|
| 338 |
+
if outputs is None:
|
| 339 |
+
outputs = []
|
| 340 |
+
self.outputs = outputs
|
| 341 |
+
|
| 342 |
+
def __call__(self, result=None):
|
| 343 |
+
if result is None:
|
| 344 |
+
return
|
| 345 |
+
format_dict, md_dict = self.shell.display_formatter.format(result)
|
| 346 |
+
self.outputs.append({ 'data': format_dict, 'metadata': md_dict })
|
lib/python3.12/site-packages/IPython/core/doctb.py
ADDED
|
@@ -0,0 +1,445 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
| 1 |
+
import inspect
|
| 2 |
+
import linecache
|
| 3 |
+
import sys
|
| 4 |
+
from collections.abc import Sequence
|
| 5 |
+
from types import TracebackType
|
| 6 |
+
from typing import Any, Optional
|
| 7 |
+
from collections.abc import Callable
|
| 8 |
+
|
| 9 |
+
import stack_data
|
| 10 |
+
from pygments.formatters.terminal256 import Terminal256Formatter
|
| 11 |
+
from pygments.token import Token
|
| 12 |
+
|
| 13 |
+
from IPython.utils.PyColorize import Theme, TokenStream, theme_table
|
| 14 |
+
from IPython.utils.terminal import get_terminal_size
|
| 15 |
+
|
| 16 |
+
from .tbtools import (
|
| 17 |
+
FrameInfo,
|
| 18 |
+
TBTools,
|
| 19 |
+
_safe_string,
|
| 20 |
+
_tokens_filename,
|
| 21 |
+
eqrepr,
|
| 22 |
+
get_line_number_of_frame,
|
| 23 |
+
nullrepr,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
INDENT_SIZE = 8
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _format_traceback_lines(
|
| 30 |
+
lines: list[stack_data.Line],
|
| 31 |
+
theme: Theme,
|
| 32 |
+
has_colors: bool,
|
| 33 |
+
lvals_toks: list[TokenStream],
|
| 34 |
+
) -> TokenStream:
|
| 35 |
+
"""
|
| 36 |
+
Format tracebacks lines with pointing arrow, leading numbers,
|
| 37 |
+
this assumes the stack have been extracted using stackdata.
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
Parameters
|
| 41 |
+
----------
|
| 42 |
+
lines : list[Line]
|
| 43 |
+
"""
|
| 44 |
+
numbers_width = INDENT_SIZE - 1
|
| 45 |
+
tokens: TokenStream = [(Token, "\n")]
|
| 46 |
+
|
| 47 |
+
for stack_line in lines:
|
| 48 |
+
if stack_line is stack_data.LINE_GAP:
|
| 49 |
+
toks = [(Token.LinenoEm, " (...)")]
|
| 50 |
+
tokens.extend(toks)
|
| 51 |
+
continue
|
| 52 |
+
|
| 53 |
+
lineno = stack_line.lineno
|
| 54 |
+
line = stack_line.render(pygmented=has_colors).rstrip("\n") + "\n"
|
| 55 |
+
if stack_line.is_current:
|
| 56 |
+
# This is the line with the error
|
| 57 |
+
pad = numbers_width - len(str(lineno))
|
| 58 |
+
toks = [
|
| 59 |
+
(Token.Prompt, theme.make_arrow(3)),
|
| 60 |
+
(Token, " "),
|
| 61 |
+
(Token, line),
|
| 62 |
+
]
|
| 63 |
+
else:
|
| 64 |
+
# num = "%*s" % (numbers_width, lineno)
|
| 65 |
+
toks = [
|
| 66 |
+
# (Token.LinenoEm, str(num)),
|
| 67 |
+
(Token, "..."),
|
| 68 |
+
(Token, " "),
|
| 69 |
+
(Token, line),
|
| 70 |
+
]
|
| 71 |
+
|
| 72 |
+
tokens.extend(toks)
|
| 73 |
+
if lvals_toks and stack_line.is_current:
|
| 74 |
+
for lv in lvals_toks:
|
| 75 |
+
tokens.append((Token, " " * INDENT_SIZE))
|
| 76 |
+
tokens.extend(lv)
|
| 77 |
+
tokens.append((Token, "\n"))
|
| 78 |
+
# strip the last newline
|
| 79 |
+
tokens = tokens[:-1]
|
| 80 |
+
|
| 81 |
+
return tokens
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class DocTB(TBTools):
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
A stripped down version of Verbose TB, simplified to not have too much information when
|
| 88 |
+
running doctests
|
| 89 |
+
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
tb_highlight = ""
|
| 93 |
+
tb_highlight_style = "default"
|
| 94 |
+
tb_offset: int
|
| 95 |
+
long_header: bool
|
| 96 |
+
include_vars: bool
|
| 97 |
+
|
| 98 |
+
_mode: str
|
| 99 |
+
|
| 100 |
+
def __init__(
|
| 101 |
+
self,
|
| 102 |
+
# TODO: no default ?
|
| 103 |
+
theme_name: str = "linux",
|
| 104 |
+
call_pdb: bool = False,
|
| 105 |
+
ostream: Any = None,
|
| 106 |
+
tb_offset: int = 0,
|
| 107 |
+
long_header: bool = False,
|
| 108 |
+
include_vars: bool = True,
|
| 109 |
+
check_cache: Callable[[], None] | None = None,
|
| 110 |
+
debugger_cls: type | None = None,
|
| 111 |
+
):
|
| 112 |
+
"""Specify traceback offset, headers and color scheme.
|
| 113 |
+
|
| 114 |
+
Define how many frames to drop from the tracebacks. Calling it with
|
| 115 |
+
tb_offset=1 allows use of this handler in interpreters which will have
|
| 116 |
+
their own code at the top of the traceback (VerboseTB will first
|
| 117 |
+
remove that frame before printing the traceback info)."""
|
| 118 |
+
assert isinstance(theme_name, str)
|
| 119 |
+
super().__init__(
|
| 120 |
+
theme_name=theme_name,
|
| 121 |
+
call_pdb=call_pdb,
|
| 122 |
+
ostream=ostream,
|
| 123 |
+
debugger_cls=debugger_cls,
|
| 124 |
+
)
|
| 125 |
+
self.tb_offset = tb_offset
|
| 126 |
+
self.long_header = long_header
|
| 127 |
+
self.include_vars = include_vars
|
| 128 |
+
# By default we use linecache.checkcache, but the user can provide a
|
| 129 |
+
# different check_cache implementation. This was formerly used by the
|
| 130 |
+
# IPython kernel for interactive code, but is no longer necessary.
|
| 131 |
+
if check_cache is None:
|
| 132 |
+
check_cache = linecache.checkcache
|
| 133 |
+
self.check_cache = check_cache
|
| 134 |
+
|
| 135 |
+
self.skip_hidden = True
|
| 136 |
+
|
| 137 |
+
def format_record(self, frame_info: FrameInfo) -> str:
|
| 138 |
+
"""Format a single stack frame"""
|
| 139 |
+
assert isinstance(frame_info, FrameInfo)
|
| 140 |
+
|
| 141 |
+
if isinstance(frame_info._sd, stack_data.RepeatedFrames):
|
| 142 |
+
return theme_table[self._theme_name].format(
|
| 143 |
+
[
|
| 144 |
+
(Token, " "),
|
| 145 |
+
(
|
| 146 |
+
Token.ExcName,
|
| 147 |
+
"[... skipping similar frames: %s]" % frame_info.description,
|
| 148 |
+
),
|
| 149 |
+
(Token, "\n"),
|
| 150 |
+
]
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
indent: str = " " * INDENT_SIZE
|
| 154 |
+
|
| 155 |
+
assert isinstance(frame_info.lineno, int)
|
| 156 |
+
args, varargs, varkw, locals_ = inspect.getargvalues(frame_info.frame)
|
| 157 |
+
if frame_info.executing is not None:
|
| 158 |
+
func = frame_info.executing.code_qualname()
|
| 159 |
+
else:
|
| 160 |
+
func = "?"
|
| 161 |
+
if func == "<module>":
|
| 162 |
+
call = ""
|
| 163 |
+
else:
|
| 164 |
+
# Decide whether to include variable details or not
|
| 165 |
+
var_repr = eqrepr if self.include_vars else nullrepr
|
| 166 |
+
try:
|
| 167 |
+
scope = inspect.formatargvalues(
|
| 168 |
+
args, varargs, varkw, locals_, formatvalue=var_repr
|
| 169 |
+
)
|
| 170 |
+
assert isinstance(scope, str)
|
| 171 |
+
call = theme_table[self._theme_name].format(
|
| 172 |
+
[(Token, "in "), (Token.VName, func), (Token.ValEm, scope)]
|
| 173 |
+
)
|
| 174 |
+
except KeyError:
|
| 175 |
+
# This happens in situations like errors inside generator
|
| 176 |
+
# expressions, where local variables are listed in the
|
| 177 |
+
# line, but can't be extracted from the frame. I'm not
|
| 178 |
+
# 100% sure this isn't actually a bug in inspect itself,
|
| 179 |
+
# but since there's no info for us to compute with, the
|
| 180 |
+
# best we can do is report the failure and move on. Here
|
| 181 |
+
# we must *not* call any traceback construction again,
|
| 182 |
+
# because that would mess up use of %debug later on. So we
|
| 183 |
+
# simply report the failure and move on. The only
|
| 184 |
+
# limitation will be that this frame won't have locals
|
| 185 |
+
# listed in the call signature. Quite subtle problem...
|
| 186 |
+
# I can't think of a good way to validate this in a unit
|
| 187 |
+
# test, but running a script consisting of:
|
| 188 |
+
# dict( (k,v.strip()) for (k,v) in range(10) )
|
| 189 |
+
# will illustrate the error, if this exception catch is
|
| 190 |
+
# disabled.
|
| 191 |
+
call = theme_table[self._theme_name].format(
|
| 192 |
+
[
|
| 193 |
+
(Token, "in "),
|
| 194 |
+
(Token.VName, func),
|
| 195 |
+
(Token.ValEm, "(***failed resolving arguments***)"),
|
| 196 |
+
]
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
lvals_toks: list[TokenStream] = []
|
| 200 |
+
if self.include_vars:
|
| 201 |
+
try:
|
| 202 |
+
# we likely want to fix stackdata at some point, but
|
| 203 |
+
# still need a workaround.
|
| 204 |
+
fibp = frame_info.variables_in_executing_piece
|
| 205 |
+
for var in fibp:
|
| 206 |
+
lvals_toks.append(
|
| 207 |
+
[
|
| 208 |
+
(Token, var.name),
|
| 209 |
+
(Token, " "),
|
| 210 |
+
(Token.ValEm, "= "),
|
| 211 |
+
(Token.ValEm, repr(var.value)),
|
| 212 |
+
]
|
| 213 |
+
)
|
| 214 |
+
except Exception:
|
| 215 |
+
lvals_toks.append(
|
| 216 |
+
[
|
| 217 |
+
(
|
| 218 |
+
Token,
|
| 219 |
+
"Exception trying to inspect frame. No more locals available.",
|
| 220 |
+
),
|
| 221 |
+
]
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
assert frame_info._sd is not None
|
| 225 |
+
result = theme_table[self._theme_name].format(
|
| 226 |
+
_tokens_filename(True, frame_info.filename, lineno=frame_info.lineno)
|
| 227 |
+
)
|
| 228 |
+
result += ", " if call else ""
|
| 229 |
+
result += f"{call}\n"
|
| 230 |
+
result += theme_table[self._theme_name].format(
|
| 231 |
+
_format_traceback_lines(
|
| 232 |
+
frame_info.lines,
|
| 233 |
+
theme_table[self._theme_name],
|
| 234 |
+
self.has_colors,
|
| 235 |
+
lvals_toks,
|
| 236 |
+
)
|
| 237 |
+
)
|
| 238 |
+
return result
|
| 239 |
+
|
| 240 |
+
def prepare_header(self, etype: str) -> str:
|
| 241 |
+
width = min(75, get_terminal_size()[0])
|
| 242 |
+
head = theme_table[self._theme_name].format(
|
| 243 |
+
[
|
| 244 |
+
(
|
| 245 |
+
Token,
|
| 246 |
+
"Traceback (most recent call last):",
|
| 247 |
+
),
|
| 248 |
+
(Token, " "),
|
| 249 |
+
]
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
return head
|
| 253 |
+
|
| 254 |
+
def format_exception(self, etype: Any, evalue: Any) -> Any:
|
| 255 |
+
# Get (safely) a string form of the exception info
|
| 256 |
+
try:
|
| 257 |
+
etype_str, evalue_str = map(str, (etype, evalue))
|
| 258 |
+
except:
|
| 259 |
+
# User exception is improperly defined.
|
| 260 |
+
etype, evalue = str, sys.exc_info()[:2]
|
| 261 |
+
etype_str, evalue_str = map(str, (etype, evalue))
|
| 262 |
+
|
| 263 |
+
# PEP-678 notes
|
| 264 |
+
notes = getattr(evalue, "__notes__", [])
|
| 265 |
+
if not isinstance(notes, Sequence) or isinstance(notes, (str, bytes)):
|
| 266 |
+
notes = [_safe_string(notes, "__notes__", func=repr)]
|
| 267 |
+
|
| 268 |
+
# ... and format it
|
| 269 |
+
return [
|
| 270 |
+
theme_table[self._theme_name].format(
|
| 271 |
+
[(Token.ExcName, etype_str), (Token, ": "), (Token, evalue_str)]
|
| 272 |
+
),
|
| 273 |
+
*(
|
| 274 |
+
theme_table[self._theme_name].format([(Token, _safe_string(n, "note"))])
|
| 275 |
+
for n in notes
|
| 276 |
+
),
|
| 277 |
+
]
|
| 278 |
+
|
| 279 |
+
def format_exception_as_a_whole(
|
| 280 |
+
self,
|
| 281 |
+
etype: type,
|
| 282 |
+
evalue: Optional[BaseException],
|
| 283 |
+
etb: Optional[TracebackType],
|
| 284 |
+
context: int,
|
| 285 |
+
tb_offset: Optional[int],
|
| 286 |
+
) -> list[list[str]]:
|
| 287 |
+
"""Formats the header, traceback and exception message for a single exception.
|
| 288 |
+
|
| 289 |
+
This may be called multiple times by Python 3 exception chaining
|
| 290 |
+
(PEP 3134).
|
| 291 |
+
"""
|
| 292 |
+
# some locals
|
| 293 |
+
orig_etype = etype
|
| 294 |
+
try:
|
| 295 |
+
etype = etype.__name__ # type: ignore[assignment]
|
| 296 |
+
except AttributeError:
|
| 297 |
+
pass
|
| 298 |
+
|
| 299 |
+
tb_offset = self.tb_offset if tb_offset is None else tb_offset
|
| 300 |
+
assert isinstance(tb_offset, int)
|
| 301 |
+
head = self.prepare_header(str(etype))
|
| 302 |
+
assert context == 1, context
|
| 303 |
+
records = self.get_records(etb, context, tb_offset) if etb else []
|
| 304 |
+
|
| 305 |
+
frames = []
|
| 306 |
+
skipped = 0
|
| 307 |
+
nskipped = len(records) - 1
|
| 308 |
+
frames.append(self.format_record(records[0]))
|
| 309 |
+
if nskipped:
|
| 310 |
+
frames.append(
|
| 311 |
+
theme_table[self._theme_name].format(
|
| 312 |
+
[
|
| 313 |
+
(Token, "\n"),
|
| 314 |
+
(Token, " "),
|
| 315 |
+
(Token, "[... %s skipped frames]" % nskipped),
|
| 316 |
+
(Token, "\n"),
|
| 317 |
+
(Token, "\n"),
|
| 318 |
+
]
|
| 319 |
+
)
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
formatted_exception = self.format_exception(etype, evalue)
|
| 323 |
+
return [[head] + frames + formatted_exception]
|
| 324 |
+
|
| 325 |
+
def get_records(self, etb: TracebackType, context: int, tb_offset: int) -> Any:
|
| 326 |
+
assert context == 1, context
|
| 327 |
+
assert etb is not None
|
| 328 |
+
context = context - 1
|
| 329 |
+
after = context // 2
|
| 330 |
+
before = context - after
|
| 331 |
+
if self.has_colors:
|
| 332 |
+
base_style = theme_table[self._theme_name].as_pygments_style()
|
| 333 |
+
style = stack_data.style_with_executing_node(base_style, self.tb_highlight)
|
| 334 |
+
formatter = Terminal256Formatter(style=style)
|
| 335 |
+
else:
|
| 336 |
+
formatter = None
|
| 337 |
+
options = stack_data.Options(
|
| 338 |
+
before=before,
|
| 339 |
+
after=after,
|
| 340 |
+
pygments_formatter=formatter,
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
# Let's estimate the amount of code we will have to parse/highlight.
|
| 344 |
+
cf: Optional[TracebackType] = etb
|
| 345 |
+
max_len = 0
|
| 346 |
+
tbs = []
|
| 347 |
+
while cf is not None:
|
| 348 |
+
try:
|
| 349 |
+
mod = inspect.getmodule(cf.tb_frame)
|
| 350 |
+
if mod is not None:
|
| 351 |
+
mod_name = mod.__name__
|
| 352 |
+
root_name, *_ = mod_name.split(".")
|
| 353 |
+
if root_name == "IPython":
|
| 354 |
+
cf = cf.tb_next
|
| 355 |
+
continue
|
| 356 |
+
max_len = get_line_number_of_frame(cf.tb_frame)
|
| 357 |
+
|
| 358 |
+
except OSError:
|
| 359 |
+
max_len = 0
|
| 360 |
+
max_len = max(max_len, max_len)
|
| 361 |
+
tbs.append(cf)
|
| 362 |
+
cf = getattr(cf, "tb_next", None)
|
| 363 |
+
|
| 364 |
+
res = list(stack_data.FrameInfo.stack_data(etb, options=options))[tb_offset:]
|
| 365 |
+
res2 = [FrameInfo._from_stack_data_FrameInfo(r) for r in res]
|
| 366 |
+
return res2
|
| 367 |
+
|
| 368 |
+
def structured_traceback(
|
| 369 |
+
self,
|
| 370 |
+
etype: type,
|
| 371 |
+
evalue: Optional[BaseException],
|
| 372 |
+
etb: Optional[TracebackType] = None,
|
| 373 |
+
tb_offset: Optional[int] = None,
|
| 374 |
+
context: int = 1,
|
| 375 |
+
) -> list[str]:
|
| 376 |
+
"""Return a nice text document describing the traceback."""
|
| 377 |
+
assert context > 0
|
| 378 |
+
assert context == 1, context
|
| 379 |
+
formatted_exceptions: list[list[str]] = self.format_exception_as_a_whole(
|
| 380 |
+
etype, evalue, etb, context, tb_offset
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
termsize = min(75, get_terminal_size()[0])
|
| 384 |
+
theme = theme_table[self._theme_name]
|
| 385 |
+
structured_traceback_parts: list[str] = []
|
| 386 |
+
chained_exceptions_tb_offset = 0
|
| 387 |
+
lines_of_context = 3
|
| 388 |
+
exception = self.get_parts_of_chained_exception(evalue)
|
| 389 |
+
if exception:
|
| 390 |
+
assert evalue is not None
|
| 391 |
+
formatted_exceptions += self.prepare_chained_exception_message(
|
| 392 |
+
evalue.__cause__
|
| 393 |
+
)
|
| 394 |
+
etype, evalue, etb = exception
|
| 395 |
+
else:
|
| 396 |
+
evalue = None
|
| 397 |
+
chained_exc_ids = set()
|
| 398 |
+
while evalue:
|
| 399 |
+
formatted_exceptions += self.format_exception_as_a_whole(
|
| 400 |
+
etype, evalue, etb, lines_of_context, chained_exceptions_tb_offset
|
| 401 |
+
)
|
| 402 |
+
exception = self.get_parts_of_chained_exception(evalue)
|
| 403 |
+
|
| 404 |
+
if exception and id(exception[1]) not in chained_exc_ids:
|
| 405 |
+
chained_exc_ids.add(
|
| 406 |
+
id(exception[1])
|
| 407 |
+
) # trace exception to avoid infinite 'cause' loop
|
| 408 |
+
formatted_exceptions += self.prepare_chained_exception_message(
|
| 409 |
+
evalue.__cause__
|
| 410 |
+
)
|
| 411 |
+
etype, evalue, etb = exception
|
| 412 |
+
else:
|
| 413 |
+
evalue = None
|
| 414 |
+
|
| 415 |
+
# we want to see exceptions in a reversed order:
|
| 416 |
+
# the first exception should be on top
|
| 417 |
+
for fx in reversed(formatted_exceptions):
|
| 418 |
+
structured_traceback_parts += fx
|
| 419 |
+
|
| 420 |
+
return structured_traceback_parts
|
| 421 |
+
|
| 422 |
+
def debugger(self, force: bool = False) -> None:
|
| 423 |
+
raise RuntimeError("canot rundebugger in Docs mode")
|
| 424 |
+
|
| 425 |
+
def handler(self, info: tuple[Any, Any, Any] | None = None) -> None:
|
| 426 |
+
(etype, evalue, etb) = info or sys.exc_info()
|
| 427 |
+
self.tb = etb
|
| 428 |
+
ostream = self.ostream
|
| 429 |
+
ostream.flush()
|
| 430 |
+
ostream.write(self.text(etype, evalue, etb)) # type:ignore[arg-type]
|
| 431 |
+
ostream.write("\n")
|
| 432 |
+
ostream.flush()
|
| 433 |
+
|
| 434 |
+
# Changed so an instance can just be called as VerboseTB_inst() and print
|
| 435 |
+
# out the right info on its own.
|
| 436 |
+
def __call__(self, etype: Any = None, evalue: Any = None, etb: Any = None) -> None:
|
| 437 |
+
"""This hook can replace sys.excepthook (for Python 2.1 or higher)."""
|
| 438 |
+
if etb is None:
|
| 439 |
+
self.handler()
|
| 440 |
+
else:
|
| 441 |
+
self.handler((etype, evalue, etb))
|
| 442 |
+
try:
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Infrastructure for registering and firing callbacks on application events.
|
| 2 |
+
|
| 3 |
+
Unlike :mod:`IPython.core.hooks`, which lets end users set single functions to
|
| 4 |
+
be called at specific times, or a collection of alternative methods to try,
|
| 5 |
+
callbacks are designed to be used by extension authors. A number of callbacks
|
| 6 |
+
can be registered for the same event without needing to be aware of one another.
|
| 7 |
+
|
| 8 |
+
The functions defined in this module are no-ops indicating the names of available
|
| 9 |
+
events and the arguments which will be passed to them.
|
| 10 |
+
|
| 11 |
+
.. note::
|
| 12 |
+
|
| 13 |
+
This API is experimental in IPython 2.0, and may be revised in future versions.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
from typing import TYPE_CHECKING, Any, Callable, Iterable
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from IPython.core.interactiveshell import InteractiveShell
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class EventManager:
|
| 25 |
+
"""Manage a collection of events and a sequence of callbacks for each.
|
| 26 |
+
|
| 27 |
+
This is attached to :class:`~IPython.core.interactiveshell.InteractiveShell`
|
| 28 |
+
instances as an ``events`` attribute.
|
| 29 |
+
|
| 30 |
+
.. note::
|
| 31 |
+
|
| 32 |
+
This API is experimental in IPython 2.0, and may be revised in future versions.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
def __init__(
|
| 36 |
+
self,
|
| 37 |
+
shell: InteractiveShell,
|
| 38 |
+
available_events: Iterable[str],
|
| 39 |
+
print_on_error: bool = True,
|
| 40 |
+
) -> None:
|
| 41 |
+
"""Initialise the :class:`CallbackManager`.
|
| 42 |
+
|
| 43 |
+
Parameters
|
| 44 |
+
----------
|
| 45 |
+
shell
|
| 46 |
+
The :class:`~IPython.core.interactiveshell.InteractiveShell` instance
|
| 47 |
+
available_events
|
| 48 |
+
An iterable of names for callback events.
|
| 49 |
+
print_on_error:
|
| 50 |
+
A boolean flag to set whether the EventManager will print a warning which a event errors.
|
| 51 |
+
"""
|
| 52 |
+
self.shell = shell
|
| 53 |
+
self.callbacks: dict[str, list[Callable[..., Any]]] = {
|
| 54 |
+
n: [] for n in available_events
|
| 55 |
+
}
|
| 56 |
+
self.print_on_error = print_on_error
|
| 57 |
+
|
| 58 |
+
def register(self, event: str, function: Callable[..., Any]) -> None:
|
| 59 |
+
"""Register a new event callback.
|
| 60 |
+
|
| 61 |
+
Parameters
|
| 62 |
+
----------
|
| 63 |
+
event : str
|
| 64 |
+
The event for which to register this callback.
|
| 65 |
+
function : callable
|
| 66 |
+
A function to be called on the given event. It should take the same
|
| 67 |
+
parameters as the appropriate callback prototype.
|
| 68 |
+
|
| 69 |
+
Raises
|
| 70 |
+
------
|
| 71 |
+
TypeError
|
| 72 |
+
If ``function`` is not callable.
|
| 73 |
+
KeyError
|
| 74 |
+
If ``event`` is not one of the known events.
|
| 75 |
+
"""
|
| 76 |
+
if not callable(function):
|
| 77 |
+
raise TypeError('Need a callable, got %r' % function)
|
| 78 |
+
if function not in self.callbacks[event]:
|
| 79 |
+
self.callbacks[event].append(function)
|
| 80 |
+
|
| 81 |
+
def unregister(self, event: str, function: Callable[..., Any]) -> None:
|
| 82 |
+
"""Remove a callback from the given event."""
|
| 83 |
+
if function in self.callbacks[event]:
|
| 84 |
+
return self.callbacks[event].remove(function)
|
| 85 |
+
|
| 86 |
+
raise ValueError('Function {!r} is not registered as a {} callback'.format(function, event))
|
| 87 |
+
|
| 88 |
+
def trigger(self, event: str, *args: Any, **kwargs: Any) -> None:
|
| 89 |
+
"""Call callbacks for ``event``.
|
| 90 |
+
|
| 91 |
+
Any additional arguments are passed to all callbacks registered for this
|
| 92 |
+
event. Exceptions raised by callbacks are caught, and a message printed.
|
| 93 |
+
"""
|
| 94 |
+
for func in self.callbacks[event][:]:
|
| 95 |
+
try:
|
| 96 |
+
func(*args, **kwargs)
|
| 97 |
+
except (Exception, KeyboardInterrupt):
|
| 98 |
+
if self.print_on_error:
|
| 99 |
+
print(
|
| 100 |
+
"Error in callback {} (for {}), with arguments args {},kwargs {}:".format(
|
| 101 |
+
func, event, args, kwargs
|
| 102 |
+
)
|
| 103 |
+
)
|
| 104 |
+
self.shell.showtraceback()
|
| 105 |
+
|
| 106 |
+
# event_name -> prototype mapping
|
| 107 |
+
available_events: dict[str, Callable[..., Any]] = {}
|
| 108 |
+
|
| 109 |
+
def _define_event(callback_function: Callable[..., Any]) -> Callable[..., Any]:
|
| 110 |
+
available_events[callback_function.__name__] = callback_function
|
| 111 |
+
return callback_function
|
| 112 |
+
|
| 113 |
+
# ------------------------------------------------------------------------------
|
| 114 |
+
# Callback prototypes
|
| 115 |
+
#
|
| 116 |
+
# No-op functions which describe the names of available events and the
|
| 117 |
+
# signatures of callbacks for those events.
|
| 118 |
+
# ------------------------------------------------------------------------------
|
| 119 |
+
|
| 120 |
+
@_define_event
|
| 121 |
+
def pre_execute() -> None:
|
| 122 |
+
"""Fires before code is executed in response to user/frontend action.
|
| 123 |
+
|
| 124 |
+
This includes comm and widget messages and silent execution, as well as user
|
| 125 |
+
code cells.
|
| 126 |
+
"""
|
| 127 |
+
pass
|
| 128 |
+
|
| 129 |
+
@_define_event
|
| 130 |
+
def pre_run_cell(info: Any) -> None:
|
| 131 |
+
"""Fires before user-entered code runs.
|
| 132 |
+
|
| 133 |
+
Parameters
|
| 134 |
+
----------
|
| 135 |
+
info : :class:`~IPython.core.interactiveshell.ExecutionInfo`
|
| 136 |
+
An object containing information used for the code execution.
|
| 137 |
+
"""
|
| 138 |
+
pass
|
| 139 |
+
|
| 140 |
+
@_define_event
|
| 141 |
+
def post_execute() -> None:
|
| 142 |
+
"""Fires after code is executed in response to user/frontend action.
|
| 143 |
+
|
| 144 |
+
This includes comm and widget messages and silent execution, as well as user
|
| 145 |
+
code cells.
|
| 146 |
+
"""
|
| 147 |
+
pass
|
| 148 |
+
|
| 149 |
+
@_define_event
|
| 150 |
+
def post_run_cell(result: Any) -> None:
|
| 151 |
+
"""Fires after user-entered code runs.
|
| 152 |
+
|
| 153 |
+
Parameters
|
| 154 |
+
----------
|
| 155 |
+
result : :class:`~IPython.core.interactiveshell.ExecutionResult`
|
| 156 |
+
The object which will be returned as the execution result.
|
| 157 |
+
"""
|
| 158 |
+
pass
|
| 159 |
+
|
| 160 |
+
@_define_event
|
| 161 |
+
def shell_initialized(ip: InteractiveShell) -> None:
|
| 162 |
+
"""Fires after initialisation of :class:`~IPython.core.interactiveshell.InteractiveShell`.
|
| 163 |
+
|
| 164 |
+
This is before extensions and startup scripts are loaded, so it can only be
|
| 165 |
+
set by subclassing.
|
| 166 |
+
|
| 167 |
+
Parameters
|
| 168 |
+
----------
|
| 169 |
+
ip : :class:`~IPython.core.interactiveshell.InteractiveShell`
|
| 170 |
+
The newly initialised shell.
|
| 171 |
+
"""
|
| 172 |
+
pass
|
lib/python3.12/site-packages/IPython/core/formatters.py
ADDED
|
@@ -0,0 +1,1090 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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utf-8 -*-
|
| 2 |
+
"""Display formatters.
|
| 3 |
+
|
| 4 |
+
This module defines the base instances in order to implement custom
|
| 5 |
+
formatters/mimetypes
|
| 6 |
+
got objects:
|
| 7 |
+
|
| 8 |
+
As we want to see internal IPython working we are going to use the following
|
| 9 |
+
function to diaply objects instead of the normal print or display method:
|
| 10 |
+
|
| 11 |
+
>>> ip = get_ipython()
|
| 12 |
+
>>> ip.display_formatter.format(...)
|
| 13 |
+
({'text/plain': 'Ellipsis'}, {})
|
| 14 |
+
|
| 15 |
+
This return a tuple with the mimebumdle for the current object, and the
|
| 16 |
+
associated metadata.
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
We can now define our own formatter and register it:
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
>>> from IPython.core.formatters import BaseFormatter, FormatterABC
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
>>> class LLMFormatter(BaseFormatter):
|
| 26 |
+
...
|
| 27 |
+
... format_type = 'x-vendor/llm'
|
| 28 |
+
... print_method = '_repr_llm_'
|
| 29 |
+
... _return_type = (dict, str)
|
| 30 |
+
|
| 31 |
+
>>> llm_formatter = LLMFormatter(parent=ip.display_formatter)
|
| 32 |
+
|
| 33 |
+
>>> ip.display_formatter.formatters[LLMFormatter.format_type] = llm_formatter
|
| 34 |
+
|
| 35 |
+
Now any class that define `_repr_llm_` will return a x-vendor/llm as part of
|
| 36 |
+
it's display data:
|
| 37 |
+
|
| 38 |
+
>>> class A:
|
| 39 |
+
...
|
| 40 |
+
... def _repr_llm_(self, *kwargs):
|
| 41 |
+
... return 'This a A'
|
| 42 |
+
...
|
| 43 |
+
|
| 44 |
+
>>> ip.display_formatter.format(A())
|
| 45 |
+
({'text/plain': '<IPython.core.formatters.A at ...>', 'x-vendor/llm': 'This a A'}, {})
|
| 46 |
+
|
| 47 |
+
As usual, you can register methods for third party types (see
|
| 48 |
+
:ref:`third_party_formatting`)
|
| 49 |
+
|
| 50 |
+
>>> def llm_int(obj):
|
| 51 |
+
... return 'This is the integer %s, in between %s and %s'%(obj, obj-1, obj+1)
|
| 52 |
+
|
| 53 |
+
>>> llm_formatter.for_type(int, llm_int)
|
| 54 |
+
|
| 55 |
+
>>> ip.display_formatter.format(42)
|
| 56 |
+
({'text/plain': '42', 'x-vendor/llm': 'This is the integer 42, in between 41 and 43'}, {})
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
Inheritance diagram:
|
| 60 |
+
|
| 61 |
+
.. inheritance-diagram:: IPython.core.formatters
|
| 62 |
+
:parts: 3
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
# Copyright (c) IPython Development Team.
|
| 66 |
+
# Distributed under the terms of the Modified BSD License.
|
| 67 |
+
|
| 68 |
+
import abc
|
| 69 |
+
import sys
|
| 70 |
+
import traceback
|
| 71 |
+
import warnings
|
| 72 |
+
from io import StringIO
|
| 73 |
+
|
| 74 |
+
from decorator import decorator
|
| 75 |
+
|
| 76 |
+
from traitlets.config.configurable import Configurable
|
| 77 |
+
from .getipython import get_ipython
|
| 78 |
+
from ..utils.sentinel import Sentinel
|
| 79 |
+
from ..utils.dir2 import get_real_method
|
| 80 |
+
from ..lib import pretty
|
| 81 |
+
from traitlets import (
|
| 82 |
+
Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
|
| 83 |
+
ForwardDeclaredInstance,
|
| 84 |
+
default, observe,
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
from typing import Any
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class DisplayFormatter(Configurable):
|
| 91 |
+
|
| 92 |
+
active_types = List(Unicode(),
|
| 93 |
+
help="""List of currently active mime-types to display.
|
| 94 |
+
You can use this to set a white-list for formats to display.
|
| 95 |
+
|
| 96 |
+
Most users will not need to change this value.
|
| 97 |
+
""",
|
| 98 |
+
).tag(config=True)
|
| 99 |
+
|
| 100 |
+
@default('active_types')
|
| 101 |
+
def _active_types_default(self):
|
| 102 |
+
return self.format_types
|
| 103 |
+
|
| 104 |
+
@observe('active_types')
|
| 105 |
+
def _active_types_changed(self, change):
|
| 106 |
+
for key, formatter in self.formatters.items():
|
| 107 |
+
if key in change['new']:
|
| 108 |
+
formatter.enabled = True
|
| 109 |
+
else:
|
| 110 |
+
formatter.enabled = False
|
| 111 |
+
|
| 112 |
+
ipython_display_formatter = ForwardDeclaredInstance("FormatterABC") # type: ignore
|
| 113 |
+
|
| 114 |
+
@default("ipython_display_formatter")
|
| 115 |
+
def _default_formatter(self):
|
| 116 |
+
return IPythonDisplayFormatter(parent=self)
|
| 117 |
+
|
| 118 |
+
mimebundle_formatter = ForwardDeclaredInstance("FormatterABC") # type: ignore
|
| 119 |
+
|
| 120 |
+
@default("mimebundle_formatter")
|
| 121 |
+
def _default_mime_formatter(self):
|
| 122 |
+
return MimeBundleFormatter(parent=self)
|
| 123 |
+
|
| 124 |
+
# A dict of formatter whose keys are format types (MIME types) and whose
|
| 125 |
+
# values are subclasses of BaseFormatter.
|
| 126 |
+
formatters = Dict()
|
| 127 |
+
|
| 128 |
+
@default("formatters")
|
| 129 |
+
def _formatters_default(self):
|
| 130 |
+
"""Activate the default formatters."""
|
| 131 |
+
formatter_classes = [
|
| 132 |
+
PlainTextFormatter,
|
| 133 |
+
HTMLFormatter,
|
| 134 |
+
MarkdownFormatter,
|
| 135 |
+
SVGFormatter,
|
| 136 |
+
PNGFormatter,
|
| 137 |
+
PDFFormatter,
|
| 138 |
+
JPEGFormatter,
|
| 139 |
+
LatexFormatter,
|
| 140 |
+
JSONFormatter,
|
| 141 |
+
JavascriptFormatter
|
| 142 |
+
]
|
| 143 |
+
d = {}
|
| 144 |
+
for cls in formatter_classes:
|
| 145 |
+
f = cls(parent=self)
|
| 146 |
+
d[f.format_type] = f
|
| 147 |
+
return d
|
| 148 |
+
|
| 149 |
+
def format(self, obj, include=None, exclude=None):
|
| 150 |
+
"""Return a format data dict for an object.
|
| 151 |
+
|
| 152 |
+
By default all format types will be computed.
|
| 153 |
+
|
| 154 |
+
The following MIME types are usually implemented:
|
| 155 |
+
|
| 156 |
+
* text/plain
|
| 157 |
+
* text/html
|
| 158 |
+
* text/markdown
|
| 159 |
+
* text/latex
|
| 160 |
+
* application/json
|
| 161 |
+
* application/javascript
|
| 162 |
+
* application/pdf
|
| 163 |
+
* image/png
|
| 164 |
+
* image/jpeg
|
| 165 |
+
* image/svg+xml
|
| 166 |
+
|
| 167 |
+
Parameters
|
| 168 |
+
----------
|
| 169 |
+
obj : object
|
| 170 |
+
The Python object whose format data will be computed.
|
| 171 |
+
include : list, tuple or set; optional
|
| 172 |
+
A list of format type strings (MIME types) to include in the
|
| 173 |
+
format data dict. If this is set *only* the format types included
|
| 174 |
+
in this list will be computed.
|
| 175 |
+
exclude : list, tuple or set; optional
|
| 176 |
+
A list of format type string (MIME types) to exclude in the format
|
| 177 |
+
data dict. If this is set all format types will be computed,
|
| 178 |
+
except for those included in this argument.
|
| 179 |
+
Mimetypes present in exclude will take precedence over the ones in include
|
| 180 |
+
|
| 181 |
+
Returns
|
| 182 |
+
-------
|
| 183 |
+
(format_dict, metadata_dict) : tuple of two dicts
|
| 184 |
+
format_dict is a dictionary of key/value pairs, one of each format that was
|
| 185 |
+
generated for the object. The keys are the format types, which
|
| 186 |
+
will usually be MIME type strings and the values and JSON'able
|
| 187 |
+
data structure containing the raw data for the representation in
|
| 188 |
+
that format.
|
| 189 |
+
|
| 190 |
+
metadata_dict is a dictionary of metadata about each mime-type output.
|
| 191 |
+
Its keys will be a strict subset of the keys in format_dict.
|
| 192 |
+
|
| 193 |
+
Notes
|
| 194 |
+
-----
|
| 195 |
+
If an object implement `_repr_mimebundle_` as well as various
|
| 196 |
+
`_repr_*_`, the data returned by `_repr_mimebundle_` will take
|
| 197 |
+
precedence and the corresponding `_repr_*_` for this mimetype will
|
| 198 |
+
not be called.
|
| 199 |
+
|
| 200 |
+
"""
|
| 201 |
+
format_dict = {}
|
| 202 |
+
md_dict = {}
|
| 203 |
+
|
| 204 |
+
if self.ipython_display_formatter(obj):
|
| 205 |
+
# object handled itself, don't proceed
|
| 206 |
+
return {}, {}
|
| 207 |
+
|
| 208 |
+
format_dict, md_dict = self.mimebundle_formatter(obj, include=include, exclude=exclude)
|
| 209 |
+
|
| 210 |
+
if format_dict or md_dict:
|
| 211 |
+
if include:
|
| 212 |
+
format_dict = {k:v for k,v in format_dict.items() if k in include}
|
| 213 |
+
md_dict = {k:v for k,v in md_dict.items() if k in include}
|
| 214 |
+
if exclude:
|
| 215 |
+
format_dict = {k:v for k,v in format_dict.items() if k not in exclude}
|
| 216 |
+
md_dict = {k:v for k,v in md_dict.items() if k not in exclude}
|
| 217 |
+
|
| 218 |
+
for format_type, formatter in self.formatters.items():
|
| 219 |
+
if format_type in format_dict:
|
| 220 |
+
# already got it from mimebundle, maybe don't render again.
|
| 221 |
+
# exception: manually registered per-mime renderer
|
| 222 |
+
# check priority:
|
| 223 |
+
# 1. user-registered per-mime formatter
|
| 224 |
+
# 2. mime-bundle (user-registered or repr method)
|
| 225 |
+
# 3. default per-mime formatter (e.g. repr method)
|
| 226 |
+
try:
|
| 227 |
+
formatter.lookup(obj)
|
| 228 |
+
except KeyError:
|
| 229 |
+
# no special formatter, use mime-bundle-provided value
|
| 230 |
+
continue
|
| 231 |
+
if include and format_type not in include:
|
| 232 |
+
continue
|
| 233 |
+
if exclude and format_type in exclude:
|
| 234 |
+
continue
|
| 235 |
+
|
| 236 |
+
md = None
|
| 237 |
+
try:
|
| 238 |
+
data = formatter(obj)
|
| 239 |
+
except:
|
| 240 |
+
# FIXME: log the exception
|
| 241 |
+
raise
|
| 242 |
+
|
| 243 |
+
# formatters can return raw data or (data, metadata)
|
| 244 |
+
if isinstance(data, tuple) and len(data) == 2:
|
| 245 |
+
data, md = data
|
| 246 |
+
|
| 247 |
+
if data is not None:
|
| 248 |
+
format_dict[format_type] = data
|
| 249 |
+
if md is not None:
|
| 250 |
+
md_dict[format_type] = md
|
| 251 |
+
return format_dict, md_dict
|
| 252 |
+
|
| 253 |
+
@property
|
| 254 |
+
def format_types(self):
|
| 255 |
+
"""Return the format types (MIME types) of the active formatters."""
|
| 256 |
+
return list(self.formatters.keys())
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
#-----------------------------------------------------------------------------
|
| 260 |
+
# Formatters for specific format types (text, html, svg, etc.)
|
| 261 |
+
#-----------------------------------------------------------------------------
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def _safe_repr(obj):
|
| 265 |
+
"""Try to return a repr of an object
|
| 266 |
+
|
| 267 |
+
always returns a string, at least.
|
| 268 |
+
"""
|
| 269 |
+
try:
|
| 270 |
+
return repr(obj)
|
| 271 |
+
except Exception as e:
|
| 272 |
+
return "un-repr-able object (%r)" % e
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
class FormatterWarning(UserWarning):
|
| 276 |
+
"""Warning class for errors in formatters"""
|
| 277 |
+
|
| 278 |
+
@decorator
|
| 279 |
+
def catch_format_error(method, self, *args, **kwargs):
|
| 280 |
+
"""show traceback on failed format call"""
|
| 281 |
+
try:
|
| 282 |
+
r = method(self, *args, **kwargs)
|
| 283 |
+
except NotImplementedError:
|
| 284 |
+
# don't warn on NotImplementedErrors
|
| 285 |
+
return self._check_return(None, args[0])
|
| 286 |
+
except Exception:
|
| 287 |
+
exc_info = sys.exc_info()
|
| 288 |
+
ip = get_ipython()
|
| 289 |
+
if ip is not None:
|
| 290 |
+
ip.showtraceback(exc_info)
|
| 291 |
+
else:
|
| 292 |
+
traceback.print_exception(*exc_info)
|
| 293 |
+
return self._check_return(None, args[0])
|
| 294 |
+
return self._check_return(r, args[0])
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
class FormatterABC(metaclass=abc.ABCMeta):
|
| 298 |
+
""" Abstract base class for Formatters.
|
| 299 |
+
|
| 300 |
+
A formatter is a callable class that is responsible for computing the
|
| 301 |
+
raw format data for a particular format type (MIME type). For example,
|
| 302 |
+
an HTML formatter would have a format type of `text/html` and would return
|
| 303 |
+
the HTML representation of the object when called.
|
| 304 |
+
"""
|
| 305 |
+
|
| 306 |
+
# The format type of the data returned, usually a MIME type.
|
| 307 |
+
format_type = 'text/plain'
|
| 308 |
+
|
| 309 |
+
# Is the formatter enabled...
|
| 310 |
+
enabled = True
|
| 311 |
+
|
| 312 |
+
@abc.abstractmethod
|
| 313 |
+
def __call__(self, obj):
|
| 314 |
+
"""Return a JSON'able representation of the object.
|
| 315 |
+
|
| 316 |
+
If the object cannot be formatted by this formatter,
|
| 317 |
+
warn and return None.
|
| 318 |
+
"""
|
| 319 |
+
return repr(obj)
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def _mod_name_key(typ):
|
| 323 |
+
"""Return a (__module__, __name__) tuple for a type.
|
| 324 |
+
|
| 325 |
+
Used as key in Formatter.deferred_printers.
|
| 326 |
+
"""
|
| 327 |
+
module = getattr(typ, '__module__', None)
|
| 328 |
+
name = getattr(typ, '__name__', None)
|
| 329 |
+
return (module, name)
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def _get_type(obj):
|
| 333 |
+
"""Return the type of an instance (old and new-style)"""
|
| 334 |
+
return getattr(obj, '__class__', None) or type(obj)
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
_raise_key_error = Sentinel(
|
| 338 |
+
"_raise_key_error",
|
| 339 |
+
__name__,
|
| 340 |
+
"""
|
| 341 |
+
Special value to raise a KeyError
|
| 342 |
+
|
| 343 |
+
Raise KeyError in `BaseFormatter.pop` if passed as the default value to `pop`
|
| 344 |
+
""",
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
class BaseFormatter(Configurable):
|
| 349 |
+
"""A base formatter class that is configurable.
|
| 350 |
+
|
| 351 |
+
This formatter should usually be used as the base class of all formatters.
|
| 352 |
+
It is a traited :class:`Configurable` class and includes an extensible
|
| 353 |
+
API for users to determine how their objects are formatted. The following
|
| 354 |
+
logic is used to find a function to format an given object.
|
| 355 |
+
|
| 356 |
+
1. The object is introspected to see if it has a method with the name
|
| 357 |
+
:attr:`print_method`. If is does, that object is passed to that method
|
| 358 |
+
for formatting.
|
| 359 |
+
2. If no print method is found, three internal dictionaries are consulted
|
| 360 |
+
to find print method: :attr:`singleton_printers`, :attr:`type_printers`
|
| 361 |
+
and :attr:`deferred_printers`.
|
| 362 |
+
|
| 363 |
+
Users should use these dictionaries to register functions that will be
|
| 364 |
+
used to compute the format data for their objects (if those objects don't
|
| 365 |
+
have the special print methods). The easiest way of using these
|
| 366 |
+
dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
|
| 367 |
+
methods.
|
| 368 |
+
|
| 369 |
+
If no function/callable is found to compute the format data, :py:data:`None` is
|
| 370 |
+
returned and this format type is not used.
|
| 371 |
+
"""
|
| 372 |
+
|
| 373 |
+
format_type = Unicode("text/plain")
|
| 374 |
+
_return_type: Any = str
|
| 375 |
+
|
| 376 |
+
enabled = Bool(True).tag(config=True)
|
| 377 |
+
|
| 378 |
+
print_method = ObjectName('__repr__')
|
| 379 |
+
|
| 380 |
+
# The singleton printers.
|
| 381 |
+
# Maps the IDs of the builtin singleton objects to the format functions.
|
| 382 |
+
singleton_printers = Dict().tag(config=True)
|
| 383 |
+
|
| 384 |
+
# The type-specific printers.
|
| 385 |
+
# Map type objects to the format functions.
|
| 386 |
+
type_printers = Dict().tag(config=True)
|
| 387 |
+
|
| 388 |
+
# The deferred-import type-specific printers.
|
| 389 |
+
# Map (modulename, classname) pairs to the format functions.
|
| 390 |
+
deferred_printers = Dict().tag(config=True)
|
| 391 |
+
|
| 392 |
+
@catch_format_error
|
| 393 |
+
def __call__(self, obj):
|
| 394 |
+
"""Compute the format for an object."""
|
| 395 |
+
if self.enabled:
|
| 396 |
+
# lookup registered printer
|
| 397 |
+
try:
|
| 398 |
+
printer = self.lookup(obj)
|
| 399 |
+
except KeyError:
|
| 400 |
+
pass
|
| 401 |
+
else:
|
| 402 |
+
return printer(obj)
|
| 403 |
+
# Finally look for special method names
|
| 404 |
+
method = get_real_method(obj, self.print_method)
|
| 405 |
+
if method is not None:
|
| 406 |
+
return method()
|
| 407 |
+
return None
|
| 408 |
+
else:
|
| 409 |
+
return None
|
| 410 |
+
|
| 411 |
+
def __contains__(self, typ):
|
| 412 |
+
"""map in to lookup_by_type"""
|
| 413 |
+
try:
|
| 414 |
+
self.lookup_by_type(typ)
|
| 415 |
+
except KeyError:
|
| 416 |
+
return False
|
| 417 |
+
else:
|
| 418 |
+
return True
|
| 419 |
+
|
| 420 |
+
def _check_return(self, r, obj):
|
| 421 |
+
"""Check that a return value is appropriate
|
| 422 |
+
|
| 423 |
+
Return the value if so, None otherwise, warning if invalid.
|
| 424 |
+
"""
|
| 425 |
+
if r is None or isinstance(r, self._return_type) or \
|
| 426 |
+
(isinstance(r, tuple) and r and isinstance(r[0], self._return_type)):
|
| 427 |
+
return r
|
| 428 |
+
else:
|
| 429 |
+
warnings.warn(
|
| 430 |
+
"%s formatter returned invalid type %s (expected %s) for object: %s" % \
|
| 431 |
+
(self.format_type, type(r), self._return_type, _safe_repr(obj)),
|
| 432 |
+
FormatterWarning
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
def lookup(self, obj):
|
| 436 |
+
"""Look up the formatter for a given instance.
|
| 437 |
+
|
| 438 |
+
Parameters
|
| 439 |
+
----------
|
| 440 |
+
obj : object instance
|
| 441 |
+
|
| 442 |
+
Returns
|
| 443 |
+
-------
|
| 444 |
+
f : callable
|
| 445 |
+
The registered formatting callable for the type.
|
| 446 |
+
|
| 447 |
+
Raises
|
| 448 |
+
------
|
| 449 |
+
KeyError if the type has not been registered.
|
| 450 |
+
"""
|
| 451 |
+
# look for singleton first
|
| 452 |
+
obj_id = id(obj)
|
| 453 |
+
if obj_id in self.singleton_printers:
|
| 454 |
+
return self.singleton_printers[obj_id]
|
| 455 |
+
# then lookup by type
|
| 456 |
+
return self.lookup_by_type(_get_type(obj))
|
| 457 |
+
|
| 458 |
+
def lookup_by_type(self, typ):
|
| 459 |
+
"""Look up the registered formatter for a type.
|
| 460 |
+
|
| 461 |
+
Parameters
|
| 462 |
+
----------
|
| 463 |
+
typ : type or '__module__.__name__' string for a type
|
| 464 |
+
|
| 465 |
+
Returns
|
| 466 |
+
-------
|
| 467 |
+
f : callable
|
| 468 |
+
The registered formatting callable for the type.
|
| 469 |
+
|
| 470 |
+
Raises
|
| 471 |
+
------
|
| 472 |
+
KeyError if the type has not been registered.
|
| 473 |
+
"""
|
| 474 |
+
if isinstance(typ, str):
|
| 475 |
+
typ_key = tuple(typ.rsplit('.',1))
|
| 476 |
+
if typ_key not in self.deferred_printers:
|
| 477 |
+
# We may have it cached in the type map. We will have to
|
| 478 |
+
# iterate over all of the types to check.
|
| 479 |
+
for cls in self.type_printers:
|
| 480 |
+
if _mod_name_key(cls) == typ_key:
|
| 481 |
+
return self.type_printers[cls]
|
| 482 |
+
else:
|
| 483 |
+
return self.deferred_printers[typ_key]
|
| 484 |
+
else:
|
| 485 |
+
for cls in pretty._get_mro(typ):
|
| 486 |
+
if cls in self.type_printers or self._in_deferred_types(cls):
|
| 487 |
+
return self.type_printers[cls]
|
| 488 |
+
|
| 489 |
+
# If we have reached here, the lookup failed.
|
| 490 |
+
raise KeyError("No registered printer for {0!r}".format(typ))
|
| 491 |
+
|
| 492 |
+
def for_type(self, typ, func=None):
|
| 493 |
+
"""Add a format function for a given type.
|
| 494 |
+
|
| 495 |
+
Parameters
|
| 496 |
+
----------
|
| 497 |
+
typ : type or '__module__.__name__' string for a type
|
| 498 |
+
The class of the object that will be formatted using `func`.
|
| 499 |
+
|
| 500 |
+
func : callable
|
| 501 |
+
A callable for computing the format data.
|
| 502 |
+
`func` will be called with the object to be formatted,
|
| 503 |
+
and will return the raw data in this formatter's format.
|
| 504 |
+
Subclasses may use a different call signature for the
|
| 505 |
+
`func` argument.
|
| 506 |
+
|
| 507 |
+
If `func` is None or not specified, there will be no change,
|
| 508 |
+
only returning the current value.
|
| 509 |
+
|
| 510 |
+
Returns
|
| 511 |
+
-------
|
| 512 |
+
oldfunc : callable
|
| 513 |
+
The currently registered callable.
|
| 514 |
+
If you are registering a new formatter,
|
| 515 |
+
this will be the previous value (to enable restoring later).
|
| 516 |
+
"""
|
| 517 |
+
# if string given, interpret as 'pkg.module.class_name'
|
| 518 |
+
if isinstance(typ, str):
|
| 519 |
+
type_module, type_name = typ.rsplit('.', 1)
|
| 520 |
+
return self.for_type_by_name(type_module, type_name, func)
|
| 521 |
+
|
| 522 |
+
try:
|
| 523 |
+
oldfunc = self.lookup_by_type(typ)
|
| 524 |
+
except KeyError:
|
| 525 |
+
oldfunc = None
|
| 526 |
+
|
| 527 |
+
if func is not None:
|
| 528 |
+
self.type_printers[typ] = func
|
| 529 |
+
|
| 530 |
+
return oldfunc
|
| 531 |
+
|
| 532 |
+
def for_type_by_name(self, type_module, type_name, func=None):
|
| 533 |
+
"""Add a format function for a type specified by the full dotted
|
| 534 |
+
module and name of the type, rather than the type of the object.
|
| 535 |
+
|
| 536 |
+
Parameters
|
| 537 |
+
----------
|
| 538 |
+
type_module : str
|
| 539 |
+
The full dotted name of the module the type is defined in, like
|
| 540 |
+
``numpy``.
|
| 541 |
+
|
| 542 |
+
type_name : str
|
| 543 |
+
The name of the type (the class name), like ``dtype``
|
| 544 |
+
|
| 545 |
+
func : callable
|
| 546 |
+
A callable for computing the format data.
|
| 547 |
+
`func` will be called with the object to be formatted,
|
| 548 |
+
and will return the raw data in this formatter's format.
|
| 549 |
+
Subclasses may use a different call signature for the
|
| 550 |
+
`func` argument.
|
| 551 |
+
|
| 552 |
+
If `func` is None or unspecified, there will be no change,
|
| 553 |
+
only returning the current value.
|
| 554 |
+
|
| 555 |
+
Returns
|
| 556 |
+
-------
|
| 557 |
+
oldfunc : callable
|
| 558 |
+
The currently registered callable.
|
| 559 |
+
If you are registering a new formatter,
|
| 560 |
+
this will be the previous value (to enable restoring later).
|
| 561 |
+
"""
|
| 562 |
+
key = (type_module, type_name)
|
| 563 |
+
|
| 564 |
+
try:
|
| 565 |
+
oldfunc = self.lookup_by_type("%s.%s" % key)
|
| 566 |
+
except KeyError:
|
| 567 |
+
oldfunc = None
|
| 568 |
+
|
| 569 |
+
if func is not None:
|
| 570 |
+
self.deferred_printers[key] = func
|
| 571 |
+
return oldfunc
|
| 572 |
+
|
| 573 |
+
def pop(self, typ, default=_raise_key_error):
|
| 574 |
+
"""Pop a formatter for the given type.
|
| 575 |
+
|
| 576 |
+
Parameters
|
| 577 |
+
----------
|
| 578 |
+
typ : type or '__module__.__name__' string for a type
|
| 579 |
+
default : object
|
| 580 |
+
value to be returned if no formatter is registered for typ.
|
| 581 |
+
|
| 582 |
+
Returns
|
| 583 |
+
-------
|
| 584 |
+
obj : object
|
| 585 |
+
The last registered object for the type.
|
| 586 |
+
|
| 587 |
+
Raises
|
| 588 |
+
------
|
| 589 |
+
KeyError if the type is not registered and default is not specified.
|
| 590 |
+
"""
|
| 591 |
+
|
| 592 |
+
if isinstance(typ, str):
|
| 593 |
+
typ_key = tuple(typ.rsplit('.',1))
|
| 594 |
+
if typ_key not in self.deferred_printers:
|
| 595 |
+
# We may have it cached in the type map. We will have to
|
| 596 |
+
# iterate over all of the types to check.
|
| 597 |
+
for cls in self.type_printers:
|
| 598 |
+
if _mod_name_key(cls) == typ_key:
|
| 599 |
+
old = self.type_printers.pop(cls)
|
| 600 |
+
break
|
| 601 |
+
else:
|
| 602 |
+
old = default
|
| 603 |
+
else:
|
| 604 |
+
old = self.deferred_printers.pop(typ_key)
|
| 605 |
+
else:
|
| 606 |
+
if typ in self.type_printers:
|
| 607 |
+
old = self.type_printers.pop(typ)
|
| 608 |
+
else:
|
| 609 |
+
old = self.deferred_printers.pop(_mod_name_key(typ), default)
|
| 610 |
+
if old is _raise_key_error:
|
| 611 |
+
raise KeyError("No registered value for {0!r}".format(typ))
|
| 612 |
+
return old
|
| 613 |
+
|
| 614 |
+
def _in_deferred_types(self, cls):
|
| 615 |
+
"""
|
| 616 |
+
Check if the given class is specified in the deferred type registry.
|
| 617 |
+
|
| 618 |
+
Successful matches will be moved to the regular type registry for future use.
|
| 619 |
+
"""
|
| 620 |
+
mod = getattr(cls, '__module__', None)
|
| 621 |
+
name = getattr(cls, '__name__', None)
|
| 622 |
+
key = (mod, name)
|
| 623 |
+
if key in self.deferred_printers:
|
| 624 |
+
# Move the printer over to the regular registry.
|
| 625 |
+
printer = self.deferred_printers.pop(key)
|
| 626 |
+
self.type_printers[cls] = printer
|
| 627 |
+
return True
|
| 628 |
+
return False
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
class PlainTextFormatter(BaseFormatter):
|
| 632 |
+
"""The default pretty-printer.
|
| 633 |
+
|
| 634 |
+
This uses :mod:`IPython.lib.pretty` to compute the format data of
|
| 635 |
+
the object. If the object cannot be pretty printed, :func:`repr` is used.
|
| 636 |
+
See the documentation of :mod:`IPython.lib.pretty` for details on
|
| 637 |
+
how to write pretty printers. Here is a simple example::
|
| 638 |
+
|
| 639 |
+
def dtype_pprinter(obj, p, cycle):
|
| 640 |
+
if cycle:
|
| 641 |
+
return p.text('dtype(...)')
|
| 642 |
+
if hasattr(obj, 'fields'):
|
| 643 |
+
if obj.fields is None:
|
| 644 |
+
p.text(repr(obj))
|
| 645 |
+
else:
|
| 646 |
+
p.begin_group(7, 'dtype([')
|
| 647 |
+
for i, field in enumerate(obj.descr):
|
| 648 |
+
if i > 0:
|
| 649 |
+
p.text(',')
|
| 650 |
+
p.breakable()
|
| 651 |
+
p.pretty(field)
|
| 652 |
+
p.end_group(7, '])')
|
| 653 |
+
"""
|
| 654 |
+
|
| 655 |
+
# The format type of data returned.
|
| 656 |
+
format_type = Unicode('text/plain')
|
| 657 |
+
|
| 658 |
+
# This subclass ignores this attribute as it always need to return
|
| 659 |
+
# something.
|
| 660 |
+
enabled = Bool(True).tag(config=False)
|
| 661 |
+
|
| 662 |
+
max_seq_length = Integer(pretty.MAX_SEQ_LENGTH,
|
| 663 |
+
help="""Truncate large collections (lists, dicts, tuples, sets) to this size.
|
| 664 |
+
|
| 665 |
+
Set to 0 to disable truncation.
|
| 666 |
+
""",
|
| 667 |
+
).tag(config=True)
|
| 668 |
+
|
| 669 |
+
# Look for a _repr_pretty_ methods to use for pretty printing.
|
| 670 |
+
print_method = ObjectName('_repr_pretty_')
|
| 671 |
+
|
| 672 |
+
# Whether to pretty-print or not.
|
| 673 |
+
pprint = Bool(True).tag(config=True)
|
| 674 |
+
|
| 675 |
+
# Whether to be verbose or not.
|
| 676 |
+
verbose = Bool(False).tag(config=True)
|
| 677 |
+
|
| 678 |
+
# The maximum width.
|
| 679 |
+
max_width = Integer(79).tag(config=True)
|
| 680 |
+
|
| 681 |
+
# The newline character.
|
| 682 |
+
newline = Unicode('\n').tag(config=True)
|
| 683 |
+
|
| 684 |
+
# format-string for pprinting floats
|
| 685 |
+
float_format = Unicode('%r')
|
| 686 |
+
# setter for float precision, either int or direct format-string
|
| 687 |
+
float_precision = CUnicode('').tag(config=True)
|
| 688 |
+
|
| 689 |
+
@observe('float_precision')
|
| 690 |
+
def _float_precision_changed(self, change):
|
| 691 |
+
"""float_precision changed, set float_format accordingly.
|
| 692 |
+
|
| 693 |
+
float_precision can be set by int or str.
|
| 694 |
+
This will set float_format, after interpreting input.
|
| 695 |
+
If numpy has been imported, numpy print precision will also be set.
|
| 696 |
+
|
| 697 |
+
integer `n` sets format to '%.nf', otherwise, format set directly.
|
| 698 |
+
|
| 699 |
+
An empty string returns to defaults (repr for float, 8 for numpy).
|
| 700 |
+
|
| 701 |
+
This parameter can be set via the '%precision' magic.
|
| 702 |
+
"""
|
| 703 |
+
new = change['new']
|
| 704 |
+
if '%' in new:
|
| 705 |
+
# got explicit format string
|
| 706 |
+
fmt = new
|
| 707 |
+
try:
|
| 708 |
+
fmt%3.14159
|
| 709 |
+
except Exception as e:
|
| 710 |
+
raise ValueError("Precision must be int or format string, not %r"%new) from e
|
| 711 |
+
elif new:
|
| 712 |
+
# otherwise, should be an int
|
| 713 |
+
try:
|
| 714 |
+
i = int(new)
|
| 715 |
+
assert i >= 0
|
| 716 |
+
except ValueError as e:
|
| 717 |
+
raise ValueError("Precision must be int or format string, not %r"%new) from e
|
| 718 |
+
except AssertionError as e:
|
| 719 |
+
raise ValueError("int precision must be non-negative, not %r"%i) from e
|
| 720 |
+
|
| 721 |
+
fmt = '%%.%if'%i
|
| 722 |
+
if 'numpy' in sys.modules:
|
| 723 |
+
# set numpy precision if it has been imported
|
| 724 |
+
import numpy
|
| 725 |
+
numpy.set_printoptions(precision=i)
|
| 726 |
+
else:
|
| 727 |
+
# default back to repr
|
| 728 |
+
fmt = '%r'
|
| 729 |
+
if 'numpy' in sys.modules:
|
| 730 |
+
import numpy
|
| 731 |
+
# numpy default is 8
|
| 732 |
+
numpy.set_printoptions(precision=8)
|
| 733 |
+
self.float_format = fmt
|
| 734 |
+
|
| 735 |
+
# Use the default pretty printers from IPython.lib.pretty.
|
| 736 |
+
@default('singleton_printers')
|
| 737 |
+
def _singleton_printers_default(self):
|
| 738 |
+
return pretty._singleton_pprinters.copy()
|
| 739 |
+
|
| 740 |
+
@default('type_printers')
|
| 741 |
+
def _type_printers_default(self):
|
| 742 |
+
d = pretty._type_pprinters.copy()
|
| 743 |
+
d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
|
| 744 |
+
# if NumPy is used, set precision for its float64 type
|
| 745 |
+
if "numpy" in sys.modules:
|
| 746 |
+
import numpy
|
| 747 |
+
|
| 748 |
+
d[numpy.float64] = lambda obj, p, cycle: p.text(self.float_format % obj)
|
| 749 |
+
return d
|
| 750 |
+
|
| 751 |
+
@default('deferred_printers')
|
| 752 |
+
def _deferred_printers_default(self):
|
| 753 |
+
return pretty._deferred_type_pprinters.copy()
|
| 754 |
+
|
| 755 |
+
#### FormatterABC interface ####
|
| 756 |
+
|
| 757 |
+
@catch_format_error
|
| 758 |
+
def __call__(self, obj):
|
| 759 |
+
"""Compute the pretty representation of the object."""
|
| 760 |
+
if not self.pprint:
|
| 761 |
+
return repr(obj)
|
| 762 |
+
else:
|
| 763 |
+
stream = StringIO()
|
| 764 |
+
printer = pretty.RepresentationPrinter(stream, self.verbose,
|
| 765 |
+
self.max_width, self.newline,
|
| 766 |
+
max_seq_length=self.max_seq_length,
|
| 767 |
+
singleton_pprinters=self.singleton_printers,
|
| 768 |
+
type_pprinters=self.type_printers,
|
| 769 |
+
deferred_pprinters=self.deferred_printers)
|
| 770 |
+
printer.pretty(obj)
|
| 771 |
+
printer.flush()
|
| 772 |
+
return stream.getvalue()
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
class HTMLFormatter(BaseFormatter):
|
| 776 |
+
"""An HTML formatter.
|
| 777 |
+
|
| 778 |
+
To define the callables that compute the HTML representation of your
|
| 779 |
+
objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
|
| 780 |
+
or :meth:`for_type_by_name` methods to register functions that handle
|
| 781 |
+
this.
|
| 782 |
+
|
| 783 |
+
The return value of this formatter should be a valid HTML snippet that
|
| 784 |
+
could be injected into an existing DOM. It should *not* include the
|
| 785 |
+
```<html>`` or ```<body>`` tags.
|
| 786 |
+
"""
|
| 787 |
+
format_type = Unicode('text/html')
|
| 788 |
+
|
| 789 |
+
print_method = ObjectName('_repr_html_')
|
| 790 |
+
|
| 791 |
+
|
| 792 |
+
class MarkdownFormatter(BaseFormatter):
|
| 793 |
+
"""A Markdown formatter.
|
| 794 |
+
|
| 795 |
+
To define the callables that compute the Markdown representation of your
|
| 796 |
+
objects, define a :meth:`_repr_markdown_` method or use the :meth:`for_type`
|
| 797 |
+
or :meth:`for_type_by_name` methods to register functions that handle
|
| 798 |
+
this.
|
| 799 |
+
|
| 800 |
+
The return value of this formatter should be a valid Markdown.
|
| 801 |
+
"""
|
| 802 |
+
format_type = Unicode('text/markdown')
|
| 803 |
+
|
| 804 |
+
print_method = ObjectName('_repr_markdown_')
|
| 805 |
+
|
| 806 |
+
class SVGFormatter(BaseFormatter):
|
| 807 |
+
"""An SVG formatter.
|
| 808 |
+
|
| 809 |
+
To define the callables that compute the SVG representation of your
|
| 810 |
+
objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
|
| 811 |
+
or :meth:`for_type_by_name` methods to register functions that handle
|
| 812 |
+
this.
|
| 813 |
+
|
| 814 |
+
The return value of this formatter should be valid SVG enclosed in
|
| 815 |
+
```<svg>``` tags, that could be injected into an existing DOM. It should
|
| 816 |
+
*not* include the ```<html>`` or ```<body>`` tags.
|
| 817 |
+
"""
|
| 818 |
+
format_type = Unicode('image/svg+xml')
|
| 819 |
+
|
| 820 |
+
print_method = ObjectName('_repr_svg_')
|
| 821 |
+
|
| 822 |
+
|
| 823 |
+
class PNGFormatter(BaseFormatter):
|
| 824 |
+
"""A PNG formatter.
|
| 825 |
+
|
| 826 |
+
To define the callables that compute the PNG representation of your
|
| 827 |
+
objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
|
| 828 |
+
or :meth:`for_type_by_name` methods to register functions that handle
|
| 829 |
+
this.
|
| 830 |
+
|
| 831 |
+
The return value of this formatter should be raw PNG data, *not*
|
| 832 |
+
base64 encoded.
|
| 833 |
+
"""
|
| 834 |
+
format_type = Unicode('image/png')
|
| 835 |
+
|
| 836 |
+
print_method = ObjectName('_repr_png_')
|
| 837 |
+
|
| 838 |
+
_return_type = (bytes, str)
|
| 839 |
+
|
| 840 |
+
|
| 841 |
+
class JPEGFormatter(BaseFormatter):
|
| 842 |
+
"""A JPEG formatter.
|
| 843 |
+
|
| 844 |
+
To define the callables that compute the JPEG representation of your
|
| 845 |
+
objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type`
|
| 846 |
+
or :meth:`for_type_by_name` methods to register functions that handle
|
| 847 |
+
this.
|
| 848 |
+
|
| 849 |
+
The return value of this formatter should be raw JPEG data, *not*
|
| 850 |
+
base64 encoded.
|
| 851 |
+
"""
|
| 852 |
+
format_type = Unicode('image/jpeg')
|
| 853 |
+
|
| 854 |
+
print_method = ObjectName('_repr_jpeg_')
|
| 855 |
+
|
| 856 |
+
_return_type = (bytes, str)
|
| 857 |
+
|
| 858 |
+
|
| 859 |
+
class LatexFormatter(BaseFormatter):
|
| 860 |
+
"""A LaTeX formatter.
|
| 861 |
+
|
| 862 |
+
To define the callables that compute the LaTeX representation of your
|
| 863 |
+
objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
|
| 864 |
+
or :meth:`for_type_by_name` methods to register functions that handle
|
| 865 |
+
this.
|
| 866 |
+
|
| 867 |
+
The return value of this formatter should be a valid LaTeX equation,
|
| 868 |
+
enclosed in either ```$```, ```$$``` or another LaTeX equation
|
| 869 |
+
environment.
|
| 870 |
+
"""
|
| 871 |
+
format_type = Unicode('text/latex')
|
| 872 |
+
|
| 873 |
+
print_method = ObjectName('_repr_latex_')
|
| 874 |
+
|
| 875 |
+
|
| 876 |
+
class JSONFormatter(BaseFormatter):
|
| 877 |
+
"""A JSON string formatter.
|
| 878 |
+
|
| 879 |
+
To define the callables that compute the JSONable representation of
|
| 880 |
+
your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
|
| 881 |
+
or :meth:`for_type_by_name` methods to register functions that handle
|
| 882 |
+
this.
|
| 883 |
+
|
| 884 |
+
The return value of this formatter should be a JSONable list or dict.
|
| 885 |
+
JSON scalars (None, number, string) are not allowed, only dict or list containers.
|
| 886 |
+
"""
|
| 887 |
+
format_type = Unicode('application/json')
|
| 888 |
+
_return_type = (list, dict)
|
| 889 |
+
|
| 890 |
+
print_method = ObjectName('_repr_json_')
|
| 891 |
+
|
| 892 |
+
def _check_return(self, r, obj):
|
| 893 |
+
"""Check that a return value is appropriate
|
| 894 |
+
|
| 895 |
+
Return the value if so, None otherwise, warning if invalid.
|
| 896 |
+
"""
|
| 897 |
+
if r is None:
|
| 898 |
+
return
|
| 899 |
+
md = None
|
| 900 |
+
if isinstance(r, tuple):
|
| 901 |
+
# unpack data, metadata tuple for type checking on first element
|
| 902 |
+
r, md = r
|
| 903 |
+
|
| 904 |
+
assert not isinstance(
|
| 905 |
+
r, str
|
| 906 |
+
), "JSON-as-string has been deprecated since IPython < 3"
|
| 907 |
+
|
| 908 |
+
if md is not None:
|
| 909 |
+
# put the tuple back together
|
| 910 |
+
r = (r, md)
|
| 911 |
+
return super(JSONFormatter, self)._check_return(r, obj)
|
| 912 |
+
|
| 913 |
+
|
| 914 |
+
class JavascriptFormatter(BaseFormatter):
|
| 915 |
+
"""A Javascript formatter.
|
| 916 |
+
|
| 917 |
+
To define the callables that compute the Javascript representation of
|
| 918 |
+
your objects, define a :meth:`_repr_javascript_` method or use the
|
| 919 |
+
:meth:`for_type` or :meth:`for_type_by_name` methods to register functions
|
| 920 |
+
that handle this.
|
| 921 |
+
|
| 922 |
+
The return value of this formatter should be valid Javascript code and
|
| 923 |
+
should *not* be enclosed in ```<script>``` tags.
|
| 924 |
+
"""
|
| 925 |
+
format_type = Unicode('application/javascript')
|
| 926 |
+
|
| 927 |
+
print_method = ObjectName('_repr_javascript_')
|
| 928 |
+
|
| 929 |
+
|
| 930 |
+
class PDFFormatter(BaseFormatter):
|
| 931 |
+
"""A PDF formatter.
|
| 932 |
+
|
| 933 |
+
To define the callables that compute the PDF representation of your
|
| 934 |
+
objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type`
|
| 935 |
+
or :meth:`for_type_by_name` methods to register functions that handle
|
| 936 |
+
this.
|
| 937 |
+
|
| 938 |
+
The return value of this formatter should be raw PDF data, *not*
|
| 939 |
+
base64 encoded.
|
| 940 |
+
"""
|
| 941 |
+
format_type = Unicode('application/pdf')
|
| 942 |
+
|
| 943 |
+
print_method = ObjectName('_repr_pdf_')
|
| 944 |
+
|
| 945 |
+
_return_type = (bytes, str)
|
| 946 |
+
|
| 947 |
+
class IPythonDisplayFormatter(BaseFormatter):
|
| 948 |
+
"""An escape-hatch Formatter for objects that know how to display themselves.
|
| 949 |
+
|
| 950 |
+
To define the callables that compute the representation of your
|
| 951 |
+
objects, define a :meth:`_ipython_display_` method or use the :meth:`for_type`
|
| 952 |
+
or :meth:`for_type_by_name` methods to register functions that handle
|
| 953 |
+
this. Unlike mime-type displays, this method should not return anything,
|
| 954 |
+
instead calling any appropriate display methods itself.
|
| 955 |
+
|
| 956 |
+
This display formatter has highest priority.
|
| 957 |
+
If it fires, no other display formatter will be called.
|
| 958 |
+
|
| 959 |
+
Prior to IPython 6.1, `_ipython_display_` was the only way to display custom mime-types
|
| 960 |
+
without registering a new Formatter.
|
| 961 |
+
|
| 962 |
+
IPython 6.1 introduces `_repr_mimebundle_` for displaying custom mime-types,
|
| 963 |
+
so `_ipython_display_` should only be used for objects that require unusual
|
| 964 |
+
display patterns, such as multiple display calls.
|
| 965 |
+
"""
|
| 966 |
+
print_method = ObjectName('_ipython_display_')
|
| 967 |
+
_return_type = (type(None), bool)
|
| 968 |
+
|
| 969 |
+
@catch_format_error
|
| 970 |
+
def __call__(self, obj):
|
| 971 |
+
"""Compute the format for an object."""
|
| 972 |
+
if self.enabled:
|
| 973 |
+
# lookup registered printer
|
| 974 |
+
try:
|
| 975 |
+
printer = self.lookup(obj)
|
| 976 |
+
except KeyError:
|
| 977 |
+
pass
|
| 978 |
+
else:
|
| 979 |
+
printer(obj)
|
| 980 |
+
return True
|
| 981 |
+
# Finally look for special method names
|
| 982 |
+
method = get_real_method(obj, self.print_method)
|
| 983 |
+
if method is not None:
|
| 984 |
+
method()
|
| 985 |
+
return True
|
| 986 |
+
|
| 987 |
+
|
| 988 |
+
class MimeBundleFormatter(BaseFormatter):
|
| 989 |
+
"""A Formatter for arbitrary mime-types.
|
| 990 |
+
|
| 991 |
+
Unlike other `_repr_<mimetype>_` methods,
|
| 992 |
+
`_repr_mimebundle_` should return mime-bundle data,
|
| 993 |
+
either the mime-keyed `data` dictionary or the tuple `(data, metadata)`.
|
| 994 |
+
Any mime-type is valid.
|
| 995 |
+
|
| 996 |
+
To define the callables that compute the mime-bundle representation of your
|
| 997 |
+
objects, define a :meth:`_repr_mimebundle_` method or use the :meth:`for_type`
|
| 998 |
+
or :meth:`for_type_by_name` methods to register functions that handle
|
| 999 |
+
this.
|
| 1000 |
+
|
| 1001 |
+
.. versionadded:: 6.1
|
| 1002 |
+
"""
|
| 1003 |
+
print_method = ObjectName('_repr_mimebundle_')
|
| 1004 |
+
_return_type = dict
|
| 1005 |
+
|
| 1006 |
+
def _check_return(self, r, obj):
|
| 1007 |
+
r = super(MimeBundleFormatter, self)._check_return(r, obj)
|
| 1008 |
+
# always return (data, metadata):
|
| 1009 |
+
if r is None:
|
| 1010 |
+
return {}, {}
|
| 1011 |
+
if not isinstance(r, tuple):
|
| 1012 |
+
return r, {}
|
| 1013 |
+
return r
|
| 1014 |
+
|
| 1015 |
+
@catch_format_error
|
| 1016 |
+
def __call__(self, obj, include=None, exclude=None):
|
| 1017 |
+
"""Compute the format for an object.
|
| 1018 |
+
|
| 1019 |
+
Identical to parent's method but we pass extra parameters to the method.
|
| 1020 |
+
|
| 1021 |
+
Unlike other _repr_*_ `_repr_mimebundle_` should allow extra kwargs, in
|
| 1022 |
+
particular `include` and `exclude`.
|
| 1023 |
+
"""
|
| 1024 |
+
if self.enabled:
|
| 1025 |
+
# lookup registered printer
|
| 1026 |
+
try:
|
| 1027 |
+
printer = self.lookup(obj)
|
| 1028 |
+
except KeyError:
|
| 1029 |
+
pass
|
| 1030 |
+
else:
|
| 1031 |
+
return printer(obj)
|
| 1032 |
+
# Finally look for special method names
|
| 1033 |
+
method = get_real_method(obj, self.print_method)
|
| 1034 |
+
|
| 1035 |
+
if method is not None:
|
| 1036 |
+
return method(include=include, exclude=exclude)
|
| 1037 |
+
return None
|
| 1038 |
+
else:
|
| 1039 |
+
return None
|
| 1040 |
+
|
| 1041 |
+
|
| 1042 |
+
FormatterABC.register(BaseFormatter)
|
| 1043 |
+
FormatterABC.register(PlainTextFormatter)
|
| 1044 |
+
FormatterABC.register(HTMLFormatter)
|
| 1045 |
+
FormatterABC.register(MarkdownFormatter)
|
| 1046 |
+
FormatterABC.register(SVGFormatter)
|
| 1047 |
+
FormatterABC.register(PNGFormatter)
|
| 1048 |
+
FormatterABC.register(PDFFormatter)
|
| 1049 |
+
FormatterABC.register(JPEGFormatter)
|
| 1050 |
+
FormatterABC.register(LatexFormatter)
|
| 1051 |
+
FormatterABC.register(JSONFormatter)
|
| 1052 |
+
FormatterABC.register(JavascriptFormatter)
|
| 1053 |
+
FormatterABC.register(IPythonDisplayFormatter)
|
| 1054 |
+
FormatterABC.register(MimeBundleFormatter)
|
| 1055 |
+
|
| 1056 |
+
|
| 1057 |
+
def format_display_data(obj, include=None, exclude=None):
|
| 1058 |
+
"""Return a format data dict for an object.
|
| 1059 |
+
|
| 1060 |
+
By default all format types will be computed.
|
| 1061 |
+
|
| 1062 |
+
Parameters
|
| 1063 |
+
----------
|
| 1064 |
+
obj : object
|
| 1065 |
+
The Python object whose format data will be computed.
|
| 1066 |
+
|
| 1067 |
+
Returns
|
| 1068 |
+
-------
|
| 1069 |
+
format_dict : dict
|
| 1070 |
+
A dictionary of key/value pairs, one or each format that was
|
| 1071 |
+
generated for the object. The keys are the format types, which
|
| 1072 |
+
will usually be MIME type strings and the values and JSON'able
|
| 1073 |
+
data structure containing the raw data for the representation in
|
| 1074 |
+
that format.
|
| 1075 |
+
include : list or tuple, optional
|
| 1076 |
+
A list of format type strings (MIME types) to include in the
|
| 1077 |
+
format data dict. If this is set *only* the format types included
|
| 1078 |
+
in this list will be computed.
|
| 1079 |
+
exclude : list or tuple, optional
|
| 1080 |
+
A list of format type string (MIME types) to exclude in the format
|
| 1081 |
+
data dict. If this is set all format types will be computed,
|
| 1082 |
+
except for those included in this argument.
|
| 1083 |
+
"""
|
| 1084 |
+
from .interactiveshell import InteractiveShell
|
| 1085 |
+
|
| 1086 |
+
return InteractiveShell.instance().display_formatter.format(
|
| 1087 |
+
obj,
|
| 1088 |
+
include,
|
| 1089 |
+
exclude
|
| 1090 |
+
)
|
lib/python3.12/site-packages/IPython/core/historyapp.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# encoding: utf-8
|
| 2 |
+
"""
|
| 3 |
+
An application for managing IPython history.
|
| 4 |
+
|
| 5 |
+
To be invoked as the `ipython history` subcommand.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import sqlite3
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
from traitlets.config.application import Application
|
| 12 |
+
from .application import BaseIPythonApplication
|
| 13 |
+
from traitlets import Bool, Int, Dict
|
| 14 |
+
from ..utils.io import ask_yes_no
|
| 15 |
+
|
| 16 |
+
trim_hist_help = """Trim the IPython history database to the last 1000 entries.
|
| 17 |
+
|
| 18 |
+
This actually copies the last 1000 entries to a new database, and then replaces
|
| 19 |
+
the old file with the new. Use the `--keep=` argument to specify a number
|
| 20 |
+
other than 1000.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
clear_hist_help = """Clear the IPython history database, deleting all entries.
|
| 24 |
+
|
| 25 |
+
Because this is a destructive operation, IPython will prompt the user if they
|
| 26 |
+
really want to do this. Passing a `-f` flag will force clearing without a
|
| 27 |
+
prompt.
|
| 28 |
+
|
| 29 |
+
This is an handy alias to `ipython history trim --keep=0`
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class HistoryTrim(BaseIPythonApplication):
|
| 34 |
+
description = trim_hist_help
|
| 35 |
+
|
| 36 |
+
backup = Bool(False, help="Keep the old history file as history.sqlite.<N>").tag(
|
| 37 |
+
config=True
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
keep = Int(1000, help="Number of recent lines to keep in the database.").tag(
|
| 41 |
+
config=True
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
flags = Dict( # type: ignore
|
| 45 |
+
dict(backup=({"HistoryTrim": {"backup": True}}, backup.help))
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
aliases = Dict(dict(keep="HistoryTrim.keep")) # type: ignore
|
| 49 |
+
|
| 50 |
+
def start(self):
|
| 51 |
+
profile_dir = Path(self.profile_dir.location)
|
| 52 |
+
hist_file = profile_dir / "history.sqlite"
|
| 53 |
+
con = sqlite3.connect(hist_file)
|
| 54 |
+
|
| 55 |
+
# Grab the recent history from the current database.
|
| 56 |
+
inputs = list(con.execute('SELECT session, line, source, source_raw FROM '
|
| 57 |
+
'history ORDER BY session DESC, line DESC LIMIT ?', (self.keep+1,)))
|
| 58 |
+
if len(inputs) <= self.keep:
|
| 59 |
+
print("There are already at most %d entries in the history database." % self.keep)
|
| 60 |
+
print("Not doing anything. Use --keep= argument to keep fewer entries")
|
| 61 |
+
return
|
| 62 |
+
|
| 63 |
+
print("Trimming history to the most recent %d entries." % self.keep)
|
| 64 |
+
|
| 65 |
+
inputs.pop() # Remove the extra element we got to check the length.
|
| 66 |
+
inputs.reverse()
|
| 67 |
+
if inputs:
|
| 68 |
+
first_session = inputs[0][0]
|
| 69 |
+
outputs = list(con.execute('SELECT session, line, output FROM '
|
| 70 |
+
'output_history WHERE session >= ?', (first_session,)))
|
| 71 |
+
sessions = list(con.execute('SELECT session, start, end, num_cmds, remark FROM '
|
| 72 |
+
'sessions WHERE session >= ?', (first_session,)))
|
| 73 |
+
con.close()
|
| 74 |
+
|
| 75 |
+
# Create the new history database.
|
| 76 |
+
new_hist_file = profile_dir / "history.sqlite.new"
|
| 77 |
+
i = 0
|
| 78 |
+
while new_hist_file.exists():
|
| 79 |
+
# Make sure we don't interfere with an existing file.
|
| 80 |
+
i += 1
|
| 81 |
+
new_hist_file = profile_dir / ("history.sqlite.new" + str(i))
|
| 82 |
+
new_db = sqlite3.connect(new_hist_file)
|
| 83 |
+
new_db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
|
| 84 |
+
primary key autoincrement, start timestamp,
|
| 85 |
+
end timestamp, num_cmds integer, remark text)""")
|
| 86 |
+
new_db.execute("""CREATE TABLE IF NOT EXISTS history
|
| 87 |
+
(session integer, line integer, source text, source_raw text,
|
| 88 |
+
PRIMARY KEY (session, line))""")
|
| 89 |
+
new_db.execute("""CREATE TABLE IF NOT EXISTS output_history
|
| 90 |
+
(session integer, line integer, output text,
|
| 91 |
+
PRIMARY KEY (session, line))""")
|
| 92 |
+
new_db.commit()
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
if inputs:
|
| 96 |
+
with new_db:
|
| 97 |
+
# Add the recent history into the new database.
|
| 98 |
+
new_db.executemany('insert into sessions values (?,?,?,?,?)', sessions)
|
| 99 |
+
new_db.executemany('insert into history values (?,?,?,?)', inputs)
|
| 100 |
+
new_db.executemany('insert into output_history values (?,?,?)', outputs)
|
| 101 |
+
new_db.close()
|
| 102 |
+
|
| 103 |
+
if self.backup:
|
| 104 |
+
i = 1
|
| 105 |
+
backup_hist_file = profile_dir / ("history.sqlite.old.%d" % i)
|
| 106 |
+
while backup_hist_file.exists():
|
| 107 |
+
i += 1
|
| 108 |
+
backup_hist_file = profile_dir / ("history.sqlite.old.%d" % i)
|
| 109 |
+
hist_file.rename(backup_hist_file)
|
| 110 |
+
print("Backed up longer history file to", backup_hist_file)
|
| 111 |
+
else:
|
| 112 |
+
hist_file.unlink()
|
| 113 |
+
|
| 114 |
+
new_hist_file.rename(hist_file)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class HistoryClear(HistoryTrim):
|
| 118 |
+
description = clear_hist_help
|
| 119 |
+
keep = Int(0, help="Number of recent lines to keep in the database.")
|
| 120 |
+
|
| 121 |
+
force = Bool(False, help="Don't prompt user for confirmation").tag(config=True)
|
| 122 |
+
|
| 123 |
+
flags = Dict( # type: ignore
|
| 124 |
+
dict(
|
| 125 |
+
force=({"HistoryClear": {"force": True}}, force.help),
|
| 126 |
+
f=({"HistoryTrim": {"force": True}}, force.help),
|
| 127 |
+
)
|
| 128 |
+
)
|
| 129 |
+
aliases = Dict() # type: ignore
|
| 130 |
+
|
| 131 |
+
def start(self):
|
| 132 |
+
if self.force or ask_yes_no(
|
| 133 |
+
"Really delete all ipython history? ", default="no", interrupt="no"
|
| 134 |
+
):
|
| 135 |
+
HistoryTrim.start(self)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class HistoryApp(Application):
|
| 139 |
+
name = "ipython-history"
|
| 140 |
+
description = "Manage the IPython history database."
|
| 141 |
+
|
| 142 |
+
subcommands = Dict(dict(
|
| 143 |
+
trim = (HistoryTrim, HistoryTrim.description.splitlines()[0]),
|
| 144 |
+
clear = (HistoryClear, HistoryClear.description.splitlines()[0]),
|
| 145 |
+
))
|
| 146 |
+
|
| 147 |
+
def start(self):
|
| 148 |
+
if self.subapp is None:
|
| 149 |
+
print(
|
| 150 |
+
"No subcommand specified. Must specify one of: "
|
| 151 |
+
+ ", ".join(map(repr, self.subcommands))
|
| 152 |
+
+ ".\n"
|
| 153 |
+
)
|
| 154 |
+
self.print_description()
|
| 155 |
+
self.print_subcommands()
|
| 156 |
+
self.exit(1)
|
| 157 |
+
else:
|
| 158 |
+
return self.subapp.start()
|
lib/python3.12/site-packages/IPython/core/inputtransformer2.py
ADDED
|
@@ -0,0 +1,898 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Input transformer machinery to support IPython special syntax.
|
| 2 |
+
|
| 3 |
+
This includes the machinery to recognise and transform ``%magic`` commands,
|
| 4 |
+
``!system`` commands, ``help?`` querying, prompt stripping, and so forth.
|
| 5 |
+
|
| 6 |
+
Added: IPython 7.0. Replaces inputsplitter and inputtransformer which were
|
| 7 |
+
deprecated in 7.0 and removed in 9.0
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
# Copyright (c) IPython Development Team.
|
| 11 |
+
# Distributed under the terms of the Modified BSD License.
|
| 12 |
+
|
| 13 |
+
import ast
|
| 14 |
+
from codeop import CommandCompiler, Compile
|
| 15 |
+
import re
|
| 16 |
+
import sys
|
| 17 |
+
import tokenize
|
| 18 |
+
from typing import List, Tuple, Optional, Any
|
| 19 |
+
import warnings
|
| 20 |
+
from textwrap import dedent
|
| 21 |
+
|
| 22 |
+
from IPython.utils import tokenutil
|
| 23 |
+
|
| 24 |
+
_indent_re = re.compile(r'^[ \t]+')
|
| 25 |
+
|
| 26 |
+
def leading_empty_lines(lines):
|
| 27 |
+
"""Remove leading empty lines
|
| 28 |
+
|
| 29 |
+
If the leading lines are empty or contain only whitespace, they will be
|
| 30 |
+
removed.
|
| 31 |
+
"""
|
| 32 |
+
if not lines:
|
| 33 |
+
return lines
|
| 34 |
+
for i, line in enumerate(lines):
|
| 35 |
+
if line and not line.isspace():
|
| 36 |
+
return lines[i:]
|
| 37 |
+
return lines
|
| 38 |
+
|
| 39 |
+
def leading_indent(lines):
|
| 40 |
+
"""Remove leading indentation.
|
| 41 |
+
|
| 42 |
+
Removes the minimum common leading indentation from all lines.
|
| 43 |
+
"""
|
| 44 |
+
if not lines:
|
| 45 |
+
return lines
|
| 46 |
+
return dedent("".join(lines)).splitlines(keepends=True)
|
| 47 |
+
|
| 48 |
+
class PromptStripper:
|
| 49 |
+
"""Remove matching input prompts from a block of input.
|
| 50 |
+
|
| 51 |
+
Parameters
|
| 52 |
+
----------
|
| 53 |
+
prompt_re : regular expression
|
| 54 |
+
A regular expression matching any input prompt (including continuation,
|
| 55 |
+
e.g. ``...``)
|
| 56 |
+
initial_re : regular expression, optional
|
| 57 |
+
A regular expression matching only the initial prompt, but not continuation.
|
| 58 |
+
If no initial expression is given, prompt_re will be used everywhere.
|
| 59 |
+
Used mainly for plain Python prompts (``>>>``), where the continuation prompt
|
| 60 |
+
``...`` is a valid Python expression in Python 3, so shouldn't be stripped.
|
| 61 |
+
|
| 62 |
+
Notes
|
| 63 |
+
-----
|
| 64 |
+
|
| 65 |
+
If initial_re and prompt_re differ,
|
| 66 |
+
only initial_re will be tested against the first line.
|
| 67 |
+
If any prompt is found on the first two lines,
|
| 68 |
+
prompts will be stripped from the rest of the block.
|
| 69 |
+
"""
|
| 70 |
+
def __init__(self, prompt_re, initial_re=None, *, doctest=False):
|
| 71 |
+
self.prompt_re = prompt_re
|
| 72 |
+
self.initial_re = initial_re or prompt_re
|
| 73 |
+
self.doctest = doctest
|
| 74 |
+
if doctest:
|
| 75 |
+
# Doctest/xdoctest prompts may be indented (e.g. " >>>").
|
| 76 |
+
# We only treat "..." as a continuation prompt when the same pasted
|
| 77 |
+
# block contains at least one ">>>" line, to avoid ambiguity with the
|
| 78 |
+
# Python Ellipsis literal.
|
| 79 |
+
self._doctest_initial_re = re.compile(r'^\s*>>>')
|
| 80 |
+
self._doctest_ps1_re = re.compile(r'^\s*>>>\s?')
|
| 81 |
+
self._doctest_ps2_re = re.compile(r'^\s*\.\.\.\s?')
|
| 82 |
+
|
| 83 |
+
# Very small state machine to detect triple-quoted strings in the
|
| 84 |
+
# *same* input block (e.g. user typed """ then pasted doctest).
|
| 85 |
+
# We preserve literal >>> / ... inside triple-quoted strings.
|
| 86 |
+
self._triple_quote_re = re.compile(r"(?<!\\)(\"\"\"|''')")
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _triple_quote_mask(self, lines: List[str]) -> List[bool]:
|
| 90 |
+
"""
|
| 91 |
+
Return a boolean mask: True if the corresponding line is considered
|
| 92 |
+
inside a triple-quoted string literal.
|
| 93 |
+
|
| 94 |
+
This is intentionally heuristic (fast + good enough for paste handling).
|
| 95 |
+
"""
|
| 96 |
+
mask: List[bool] = []
|
| 97 |
+
in_triple: str | None = None # either ''' or """
|
| 98 |
+
for line in lines:
|
| 99 |
+
mask.append(in_triple is not None)
|
| 100 |
+
# Toggle state for each occurrence of """ or ''' in the line.
|
| 101 |
+
for m in self._triple_quote_re.finditer(line):
|
| 102 |
+
q = m.group(1)
|
| 103 |
+
if in_triple is None:
|
| 104 |
+
in_triple = q
|
| 105 |
+
mask[-1] = True # current line is inside triple quotes
|
| 106 |
+
elif in_triple == q:
|
| 107 |
+
in_triple = None
|
| 108 |
+
# else: ignore mismatched triple quote while inside
|
| 109 |
+
return mask
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def _strip(self, lines):
|
| 113 |
+
return [self.prompt_re.sub('', l, count=1) for l in lines]
|
| 114 |
+
|
| 115 |
+
def __call__(self, lines):
|
| 116 |
+
if not lines:
|
| 117 |
+
return lines
|
| 118 |
+
|
| 119 |
+
if self.doctest:
|
| 120 |
+
triple_mask = self._triple_quote_mask(lines)
|
| 121 |
+
|
| 122 |
+
# Detect doctest prompts only outside triple-quoted strings.
|
| 123 |
+
has_doctest_outside = any(
|
| 124 |
+
(not in_triple) and self._doctest_initial_re.match(l)
|
| 125 |
+
for l, in_triple in zip(lines, triple_mask)
|
| 126 |
+
)
|
| 127 |
+
if not has_doctest_outside:
|
| 128 |
+
return lines
|
| 129 |
+
|
| 130 |
+
out_lines: List[str] = []
|
| 131 |
+
stripped_mask: List[bool] = []
|
| 132 |
+
|
| 133 |
+
for l, in_triple in zip(lines, triple_mask):
|
| 134 |
+
if in_triple:
|
| 135 |
+
out_lines.append(l)
|
| 136 |
+
stripped_mask.append(False)
|
| 137 |
+
continue
|
| 138 |
+
|
| 139 |
+
if self._doctest_ps1_re.match(l):
|
| 140 |
+
new_l = self._doctest_ps1_re.sub('', l, count=1)
|
| 141 |
+
elif self._doctest_ps2_re.match(l):
|
| 142 |
+
new_l = self._doctest_ps2_re.sub('', l, count=1)
|
| 143 |
+
else:
|
| 144 |
+
new_l = l
|
| 145 |
+
out_lines.append(new_l)
|
| 146 |
+
stripped_mask.append(new_l != l)
|
| 147 |
+
|
| 148 |
+
# Dedent only the non-triple-quoted segments where stripping occurred.
|
| 149 |
+
dedented: List[str] = []
|
| 150 |
+
i = 0
|
| 151 |
+
while i < len(out_lines):
|
| 152 |
+
j = i
|
| 153 |
+
in_triple = triple_mask[i]
|
| 154 |
+
while j < len(out_lines) and triple_mask[j] == in_triple:
|
| 155 |
+
j += 1
|
| 156 |
+
|
| 157 |
+
segment = out_lines[i:j]
|
| 158 |
+
seg_stripped = any(stripped_mask[i:j])
|
| 159 |
+
|
| 160 |
+
if (not in_triple) and seg_stripped:
|
| 161 |
+
dedented.extend(dedent(''.join(segment)).splitlines(keepends=True))
|
| 162 |
+
else:
|
| 163 |
+
dedented.extend(segment)
|
| 164 |
+
|
| 165 |
+
i = j
|
| 166 |
+
|
| 167 |
+
return dedented
|
| 168 |
+
|
| 169 |
+
if self.initial_re.match(lines[0]) or \
|
| 170 |
+
(len(lines) > 1 and self.prompt_re.match(lines[1])):
|
| 171 |
+
return self._strip(lines)
|
| 172 |
+
return lines
|
| 173 |
+
|
| 174 |
+
classic_prompt = PromptStripper(
|
| 175 |
+
prompt_re=re.compile(r'^(>>>|\.\.\.)( |$)'),
|
| 176 |
+
initial_re=re.compile(r'^>>>( |$)'),
|
| 177 |
+
doctest=True,
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
ipython_prompt = PromptStripper(
|
| 181 |
+
re.compile(
|
| 182 |
+
r"""
|
| 183 |
+
^( # Match from the beginning of a line, either:
|
| 184 |
+
|
| 185 |
+
# 1. First-line prompt:
|
| 186 |
+
((\[nav\]|\[ins\])?\ )? # Vi editing mode prompt, if it's there
|
| 187 |
+
In\ # The 'In' of the prompt, with a space
|
| 188 |
+
\[\d+\]: # Command index, as displayed in the prompt
|
| 189 |
+
\ # With a mandatory trailing space
|
| 190 |
+
|
| 191 |
+
| # ... or ...
|
| 192 |
+
|
| 193 |
+
# 2. The three dots of the multiline prompt
|
| 194 |
+
\s* # All leading whitespace characters
|
| 195 |
+
\.{3,}: # The three (or more) dots
|
| 196 |
+
\ ? # With an optional trailing space
|
| 197 |
+
|
| 198 |
+
)
|
| 199 |
+
""",
|
| 200 |
+
re.VERBOSE,
|
| 201 |
+
)
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def cell_magic(lines):
|
| 206 |
+
if not lines or not lines[0].startswith('%%'):
|
| 207 |
+
return lines
|
| 208 |
+
if re.match(r'%%\w+\?', lines[0]):
|
| 209 |
+
# This case will be handled by help_end
|
| 210 |
+
return lines
|
| 211 |
+
magic_name, _, first_line = lines[0][2:].rstrip().partition(' ')
|
| 212 |
+
body = ''.join(lines[1:])
|
| 213 |
+
return ['get_ipython().run_cell_magic(%r, %r, %r)\n'
|
| 214 |
+
% (magic_name, first_line, body)]
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def _find_assign_op(token_line) -> Optional[int]:
|
| 218 |
+
"""Get the index of the first assignment in the line ('=' not inside brackets)
|
| 219 |
+
|
| 220 |
+
Note: We don't try to support multiple special assignment (a = b = %foo)
|
| 221 |
+
"""
|
| 222 |
+
paren_level = 0
|
| 223 |
+
for i, ti in enumerate(token_line):
|
| 224 |
+
s = ti.string
|
| 225 |
+
if s == '=' and paren_level == 0:
|
| 226 |
+
return i
|
| 227 |
+
if s in {'(','[','{'}:
|
| 228 |
+
paren_level += 1
|
| 229 |
+
elif s in {')', ']', '}'}:
|
| 230 |
+
if paren_level > 0:
|
| 231 |
+
paren_level -= 1
|
| 232 |
+
return None
|
| 233 |
+
|
| 234 |
+
def find_end_of_continued_line(lines, start_line: int):
|
| 235 |
+
"""Find the last line of a line explicitly extended using backslashes.
|
| 236 |
+
|
| 237 |
+
Uses 0-indexed line numbers.
|
| 238 |
+
"""
|
| 239 |
+
end_line = start_line
|
| 240 |
+
while lines[end_line].endswith('\\\n'):
|
| 241 |
+
end_line += 1
|
| 242 |
+
if end_line >= len(lines):
|
| 243 |
+
break
|
| 244 |
+
return end_line
|
| 245 |
+
|
| 246 |
+
def assemble_continued_line(lines, start: Tuple[int, int], end_line: int):
|
| 247 |
+
r"""Assemble a single line from multiple continued line pieces
|
| 248 |
+
|
| 249 |
+
Continued lines are lines ending in ``\``, and the line following the last
|
| 250 |
+
``\`` in the block.
|
| 251 |
+
|
| 252 |
+
For example, this code continues over multiple lines::
|
| 253 |
+
|
| 254 |
+
if (assign_ix is not None) \
|
| 255 |
+
and (len(line) >= assign_ix + 2) \
|
| 256 |
+
and (line[assign_ix+1].string == '%') \
|
| 257 |
+
and (line[assign_ix+2].type == tokenize.NAME):
|
| 258 |
+
|
| 259 |
+
This statement contains four continued line pieces.
|
| 260 |
+
Assembling these pieces into a single line would give::
|
| 261 |
+
|
| 262 |
+
if (assign_ix is not None) and (len(line) >= assign_ix + 2) and (line[...
|
| 263 |
+
|
| 264 |
+
This uses 0-indexed line numbers. *start* is (lineno, colno).
|
| 265 |
+
|
| 266 |
+
Used to allow ``%magic`` and ``!system`` commands to be continued over
|
| 267 |
+
multiple lines.
|
| 268 |
+
"""
|
| 269 |
+
parts = [lines[start[0]][start[1]:]] + lines[start[0]+1:end_line+1]
|
| 270 |
+
return ' '.join([p.rstrip()[:-1] for p in parts[:-1]] # Strip backslash+newline
|
| 271 |
+
+ [parts[-1].rstrip()]) # Strip newline from last line
|
| 272 |
+
|
| 273 |
+
class TokenTransformBase:
|
| 274 |
+
"""Base class for transformations which examine tokens.
|
| 275 |
+
|
| 276 |
+
Special syntax should not be transformed when it occurs inside strings or
|
| 277 |
+
comments. This is hard to reliably avoid with regexes. The solution is to
|
| 278 |
+
tokenise the code as Python, and recognise the special syntax in the tokens.
|
| 279 |
+
|
| 280 |
+
IPython's special syntax is not valid Python syntax, so tokenising may go
|
| 281 |
+
wrong after the special syntax starts. These classes therefore find and
|
| 282 |
+
transform *one* instance of special syntax at a time into regular Python
|
| 283 |
+
syntax. After each transformation, tokens are regenerated to find the next
|
| 284 |
+
piece of special syntax.
|
| 285 |
+
|
| 286 |
+
Subclasses need to implement one class method (find)
|
| 287 |
+
and one regular method (transform).
|
| 288 |
+
|
| 289 |
+
The priority attribute can select which transformation to apply if multiple
|
| 290 |
+
transformers match in the same place. Lower numbers have higher priority.
|
| 291 |
+
This allows "%magic?" to be turned into a help call rather than a magic call.
|
| 292 |
+
"""
|
| 293 |
+
# Lower numbers -> higher priority (for matches in the same location)
|
| 294 |
+
priority = 10
|
| 295 |
+
|
| 296 |
+
def sortby(self):
|
| 297 |
+
return self.start_line, self.start_col, self.priority
|
| 298 |
+
|
| 299 |
+
def __init__(self, start):
|
| 300 |
+
self.start_line = start[0] - 1 # Shift from 1-index to 0-index
|
| 301 |
+
self.start_col = start[1]
|
| 302 |
+
|
| 303 |
+
@classmethod
|
| 304 |
+
def find(cls, tokens_by_line):
|
| 305 |
+
"""Find one instance of special syntax in the provided tokens.
|
| 306 |
+
|
| 307 |
+
Tokens are grouped into logical lines for convenience,
|
| 308 |
+
so it is easy to e.g. look at the first token of each line.
|
| 309 |
+
*tokens_by_line* is a list of lists of tokenize.TokenInfo objects.
|
| 310 |
+
|
| 311 |
+
This should return an instance of its class, pointing to the start
|
| 312 |
+
position it has found, or None if it found no match.
|
| 313 |
+
"""
|
| 314 |
+
raise NotImplementedError
|
| 315 |
+
|
| 316 |
+
def transform(self, lines: List[str]):
|
| 317 |
+
"""Transform one instance of special syntax found by ``find()``
|
| 318 |
+
|
| 319 |
+
Takes a list of strings representing physical lines,
|
| 320 |
+
returns a similar list of transformed lines.
|
| 321 |
+
"""
|
| 322 |
+
raise NotImplementedError
|
| 323 |
+
|
| 324 |
+
class MagicAssign(TokenTransformBase):
|
| 325 |
+
"""Transformer for assignments from magics (a = %foo)"""
|
| 326 |
+
@classmethod
|
| 327 |
+
def find(cls, tokens_by_line):
|
| 328 |
+
"""Find the first magic assignment (a = %foo) in the cell.
|
| 329 |
+
"""
|
| 330 |
+
for line in tokens_by_line:
|
| 331 |
+
assign_ix = _find_assign_op(line)
|
| 332 |
+
if (assign_ix is not None) \
|
| 333 |
+
and (len(line) >= assign_ix + 2) \
|
| 334 |
+
and (line[assign_ix+1].string == '%') \
|
| 335 |
+
and (line[assign_ix+2].type == tokenize.NAME):
|
| 336 |
+
return cls(line[assign_ix+1].start)
|
| 337 |
+
|
| 338 |
+
def transform(self, lines: List[str]):
|
| 339 |
+
"""Transform a magic assignment found by the ``find()`` classmethod.
|
| 340 |
+
"""
|
| 341 |
+
start_line, start_col = self.start_line, self.start_col
|
| 342 |
+
lhs = lines[start_line][:start_col]
|
| 343 |
+
end_line = find_end_of_continued_line(lines, start_line)
|
| 344 |
+
rhs = assemble_continued_line(lines, (start_line, start_col), end_line)
|
| 345 |
+
assert rhs.startswith('%'), rhs
|
| 346 |
+
magic_name, _, args = rhs[1:].partition(' ')
|
| 347 |
+
|
| 348 |
+
lines_before = lines[:start_line]
|
| 349 |
+
call = "get_ipython().run_line_magic({!r}, {!r})".format(magic_name, args)
|
| 350 |
+
new_line = lhs + call + '\n'
|
| 351 |
+
lines_after = lines[end_line+1:]
|
| 352 |
+
|
| 353 |
+
return lines_before + [new_line] + lines_after
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
class SystemAssign(TokenTransformBase):
|
| 357 |
+
"""Transformer for assignments from system commands (a = !foo)"""
|
| 358 |
+
@classmethod
|
| 359 |
+
def find_pre_312(cls, tokens_by_line):
|
| 360 |
+
for line in tokens_by_line:
|
| 361 |
+
assign_ix = _find_assign_op(line)
|
| 362 |
+
if (assign_ix is not None) \
|
| 363 |
+
and not line[assign_ix].line.strip().startswith('=') \
|
| 364 |
+
and (len(line) >= assign_ix + 2) \
|
| 365 |
+
and (line[assign_ix + 1].type == tokenize.ERRORTOKEN):
|
| 366 |
+
ix = assign_ix + 1
|
| 367 |
+
|
| 368 |
+
while ix < len(line) and line[ix].type == tokenize.ERRORTOKEN:
|
| 369 |
+
if line[ix].string == '!':
|
| 370 |
+
return cls(line[ix].start)
|
| 371 |
+
elif not line[ix].string.isspace():
|
| 372 |
+
break
|
| 373 |
+
ix += 1
|
| 374 |
+
|
| 375 |
+
@classmethod
|
| 376 |
+
def find_post_312(cls, tokens_by_line):
|
| 377 |
+
for line in tokens_by_line:
|
| 378 |
+
assign_ix = _find_assign_op(line)
|
| 379 |
+
if (
|
| 380 |
+
(assign_ix is not None)
|
| 381 |
+
and not line[assign_ix].line.strip().startswith("=")
|
| 382 |
+
and (len(line) >= assign_ix + 2)
|
| 383 |
+
and (line[assign_ix + 1].type == tokenize.OP)
|
| 384 |
+
and (line[assign_ix + 1].string == "!")
|
| 385 |
+
):
|
| 386 |
+
return cls(line[assign_ix + 1].start)
|
| 387 |
+
|
| 388 |
+
@classmethod
|
| 389 |
+
def find(cls, tokens_by_line):
|
| 390 |
+
"""Find the first system assignment (a = !foo) in the cell."""
|
| 391 |
+
if sys.version_info < (3, 12):
|
| 392 |
+
return cls.find_pre_312(tokens_by_line)
|
| 393 |
+
return cls.find_post_312(tokens_by_line)
|
| 394 |
+
|
| 395 |
+
def transform(self, lines: List[str]):
|
| 396 |
+
"""Transform a system assignment found by the ``find()`` classmethod.
|
| 397 |
+
"""
|
| 398 |
+
start_line, start_col = self.start_line, self.start_col
|
| 399 |
+
|
| 400 |
+
lhs = lines[start_line][:start_col]
|
| 401 |
+
end_line = find_end_of_continued_line(lines, start_line)
|
| 402 |
+
rhs = assemble_continued_line(lines, (start_line, start_col), end_line)
|
| 403 |
+
assert rhs.startswith('!'), rhs
|
| 404 |
+
cmd = rhs[1:]
|
| 405 |
+
|
| 406 |
+
lines_before = lines[:start_line]
|
| 407 |
+
call = "get_ipython().getoutput({!r})".format(cmd)
|
| 408 |
+
new_line = lhs + call + '\n'
|
| 409 |
+
lines_after = lines[end_line + 1:]
|
| 410 |
+
|
| 411 |
+
return lines_before + [new_line] + lines_after
|
| 412 |
+
|
| 413 |
+
# The escape sequences that define the syntax transformations IPython will
|
| 414 |
+
# apply to user input. These can NOT be just changed here: many regular
|
| 415 |
+
# expressions and other parts of the code may use their hardcoded values, and
|
| 416 |
+
# for all intents and purposes they constitute the 'IPython syntax', so they
|
| 417 |
+
# should be considered fixed.
|
| 418 |
+
|
| 419 |
+
ESC_SHELL = '!' # Send line to underlying system shell
|
| 420 |
+
ESC_SH_CAP = '!!' # Send line to system shell and capture output
|
| 421 |
+
ESC_HELP = '?' # Find information about object
|
| 422 |
+
ESC_HELP2 = '??' # Find extra-detailed information about object
|
| 423 |
+
ESC_MAGIC = '%' # Call magic function
|
| 424 |
+
ESC_MAGIC2 = '%%' # Call cell-magic function
|
| 425 |
+
ESC_QUOTE = ',' # Split args on whitespace, quote each as string and call
|
| 426 |
+
ESC_QUOTE2 = ';' # Quote all args as a single string, call
|
| 427 |
+
ESC_PAREN = '/' # Call first argument with rest of line as arguments
|
| 428 |
+
|
| 429 |
+
ESCAPE_SINGLES = {'!', '?', '%', ',', ';', '/'}
|
| 430 |
+
ESCAPE_DOUBLES = {'!!', '??'} # %% (cell magic) is handled separately
|
| 431 |
+
|
| 432 |
+
def _make_help_call(target, esc):
|
| 433 |
+
"""Prepares a pinfo(2)/psearch call from a target name and the escape
|
| 434 |
+
(i.e. ? or ??)"""
|
| 435 |
+
method = 'pinfo2' if esc == '??' \
|
| 436 |
+
else 'psearch' if '*' in target \
|
| 437 |
+
else 'pinfo'
|
| 438 |
+
arg = " ".join([method, target])
|
| 439 |
+
#Prepare arguments for get_ipython().run_line_magic(magic_name, magic_args)
|
| 440 |
+
t_magic_name, _, t_magic_arg_s = arg.partition(' ')
|
| 441 |
+
t_magic_name = t_magic_name.lstrip(ESC_MAGIC)
|
| 442 |
+
return "get_ipython().run_line_magic(%r, %r)" % (t_magic_name, t_magic_arg_s)
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def _tr_help(content):
|
| 446 |
+
"""Translate lines escaped with: ?
|
| 447 |
+
|
| 448 |
+
A naked help line should fire the intro help screen (shell.show_usage())
|
| 449 |
+
"""
|
| 450 |
+
if not content:
|
| 451 |
+
return 'get_ipython().show_usage()'
|
| 452 |
+
|
| 453 |
+
return _make_help_call(content, '?')
|
| 454 |
+
|
| 455 |
+
def _tr_help2(content):
|
| 456 |
+
"""Translate lines escaped with: ??
|
| 457 |
+
|
| 458 |
+
A naked help line should fire the intro help screen (shell.show_usage())
|
| 459 |
+
"""
|
| 460 |
+
if not content:
|
| 461 |
+
return 'get_ipython().show_usage()'
|
| 462 |
+
|
| 463 |
+
return _make_help_call(content, '??')
|
| 464 |
+
|
| 465 |
+
def _tr_magic(content):
|
| 466 |
+
"Translate lines escaped with a percent sign: %"
|
| 467 |
+
name, _, args = content.partition(' ')
|
| 468 |
+
return 'get_ipython().run_line_magic(%r, %r)' % (name, args)
|
| 469 |
+
|
| 470 |
+
def _tr_quote(content):
|
| 471 |
+
"Translate lines escaped with a comma: ,"
|
| 472 |
+
name, _, args = content.partition(' ')
|
| 473 |
+
return '%s("%s")' % (name, '", "'.join(args.split()) )
|
| 474 |
+
|
| 475 |
+
def _tr_quote2(content):
|
| 476 |
+
"Translate lines escaped with a semicolon: ;"
|
| 477 |
+
name, _, args = content.partition(' ')
|
| 478 |
+
return '%s("%s")' % (name, args)
|
| 479 |
+
|
| 480 |
+
def _tr_paren(content):
|
| 481 |
+
"Translate lines escaped with a slash: /"
|
| 482 |
+
name, _, args = content.partition(" ")
|
| 483 |
+
if name == "":
|
| 484 |
+
raise SyntaxError(f'"{ESC_SHELL}" must be followed by a callable name')
|
| 485 |
+
|
| 486 |
+
return '%s(%s)' % (name, ", ".join(args.split()))
|
| 487 |
+
|
| 488 |
+
tr = { ESC_SHELL : 'get_ipython().system({!r})'.format,
|
| 489 |
+
ESC_SH_CAP : 'get_ipython().getoutput({!r})'.format,
|
| 490 |
+
ESC_HELP : _tr_help,
|
| 491 |
+
ESC_HELP2 : _tr_help2,
|
| 492 |
+
ESC_MAGIC : _tr_magic,
|
| 493 |
+
ESC_QUOTE : _tr_quote,
|
| 494 |
+
ESC_QUOTE2 : _tr_quote2,
|
| 495 |
+
ESC_PAREN : _tr_paren }
|
| 496 |
+
|
| 497 |
+
class EscapedCommand(TokenTransformBase):
|
| 498 |
+
"""Transformer for escaped commands like %foo, !foo, or /foo"""
|
| 499 |
+
@classmethod
|
| 500 |
+
def find(cls, tokens_by_line):
|
| 501 |
+
"""Find the first escaped command (%foo, !foo, etc.) in the cell.
|
| 502 |
+
"""
|
| 503 |
+
for line in tokens_by_line:
|
| 504 |
+
if not line:
|
| 505 |
+
continue
|
| 506 |
+
ix = 0
|
| 507 |
+
ll = len(line)
|
| 508 |
+
while ll > ix and line[ix].type in {tokenize.INDENT, tokenize.DEDENT}:
|
| 509 |
+
ix += 1
|
| 510 |
+
if ix >= ll:
|
| 511 |
+
continue
|
| 512 |
+
if line[ix].string in ESCAPE_SINGLES:
|
| 513 |
+
return cls(line[ix].start)
|
| 514 |
+
|
| 515 |
+
def transform(self, lines):
|
| 516 |
+
"""Transform an escaped line found by the ``find()`` classmethod.
|
| 517 |
+
"""
|
| 518 |
+
start_line, start_col = self.start_line, self.start_col
|
| 519 |
+
|
| 520 |
+
indent = lines[start_line][:start_col]
|
| 521 |
+
end_line = find_end_of_continued_line(lines, start_line)
|
| 522 |
+
line = assemble_continued_line(lines, (start_line, start_col), end_line)
|
| 523 |
+
|
| 524 |
+
if len(line) > 1 and line[:2] in ESCAPE_DOUBLES:
|
| 525 |
+
escape, content = line[:2], line[2:]
|
| 526 |
+
else:
|
| 527 |
+
escape, content = line[:1], line[1:]
|
| 528 |
+
|
| 529 |
+
if escape in tr:
|
| 530 |
+
call = tr[escape](content)
|
| 531 |
+
else:
|
| 532 |
+
call = ''
|
| 533 |
+
|
| 534 |
+
lines_before = lines[:start_line]
|
| 535 |
+
new_line = indent + call + '\n'
|
| 536 |
+
lines_after = lines[end_line + 1:]
|
| 537 |
+
|
| 538 |
+
return lines_before + [new_line] + lines_after
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
_help_end_re = re.compile(
|
| 542 |
+
r"""(%{0,2}
|
| 543 |
+
(?!\d)[\w*]+ # Variable name
|
| 544 |
+
(\.(?!\d)[\w*]+|\[-?[0-9]+\])* # .etc.etc or [0], we only support literal integers.
|
| 545 |
+
)
|
| 546 |
+
(\?\??)$ # ? or ??
|
| 547 |
+
""",
|
| 548 |
+
re.VERBOSE,
|
| 549 |
+
)
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
class HelpEnd(TokenTransformBase):
|
| 553 |
+
"""Transformer for help syntax: obj? and obj??"""
|
| 554 |
+
# This needs to be higher priority (lower number) than EscapedCommand so
|
| 555 |
+
# that inspecting magics (%foo?) works.
|
| 556 |
+
priority = 5
|
| 557 |
+
|
| 558 |
+
def __init__(self, start, q_locn):
|
| 559 |
+
super().__init__(start)
|
| 560 |
+
self.q_line = q_locn[0] - 1 # Shift from 1-indexed to 0-indexed
|
| 561 |
+
self.q_col = q_locn[1]
|
| 562 |
+
|
| 563 |
+
@classmethod
|
| 564 |
+
def find(cls, tokens_by_line):
|
| 565 |
+
"""Find the first help command (foo?) in the cell.
|
| 566 |
+
"""
|
| 567 |
+
for line in tokens_by_line:
|
| 568 |
+
# Last token is NEWLINE; look at last but one
|
| 569 |
+
if len(line) > 2 and line[-2].string == '?':
|
| 570 |
+
# Find the first token that's not INDENT/DEDENT
|
| 571 |
+
ix = 0
|
| 572 |
+
while line[ix].type in {tokenize.INDENT, tokenize.DEDENT}:
|
| 573 |
+
ix += 1
|
| 574 |
+
return cls(line[ix].start, line[-2].start)
|
| 575 |
+
|
| 576 |
+
def transform(self, lines):
|
| 577 |
+
"""Transform a help command found by the ``find()`` classmethod.
|
| 578 |
+
"""
|
| 579 |
+
|
| 580 |
+
piece = "".join(lines[self.start_line : self.q_line + 1])
|
| 581 |
+
indent, content = piece[: self.start_col], piece[self.start_col :]
|
| 582 |
+
lines_before = lines[: self.start_line]
|
| 583 |
+
lines_after = lines[self.q_line + 1 :]
|
| 584 |
+
|
| 585 |
+
m = _help_end_re.search(content)
|
| 586 |
+
if not m:
|
| 587 |
+
raise SyntaxError(content)
|
| 588 |
+
assert m is not None, content
|
| 589 |
+
target = m.group(1)
|
| 590 |
+
esc = m.group(3)
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
call = _make_help_call(target, esc)
|
| 594 |
+
new_line = indent + call + '\n'
|
| 595 |
+
|
| 596 |
+
return lines_before + [new_line] + lines_after
|
| 597 |
+
|
| 598 |
+
def make_tokens_by_line(lines:List[str]):
|
| 599 |
+
"""Tokenize a series of lines and group tokens by line.
|
| 600 |
+
|
| 601 |
+
The tokens for a multiline Python string or expression are grouped as one
|
| 602 |
+
line. All lines except the last lines should keep their line ending ('\\n',
|
| 603 |
+
'\\r\\n') for this to properly work. Use `.splitlines(keeplineending=True)`
|
| 604 |
+
for example when passing block of text to this function.
|
| 605 |
+
|
| 606 |
+
"""
|
| 607 |
+
# NL tokens are used inside multiline expressions, but also after blank
|
| 608 |
+
# lines or comments. This is intentional - see https://bugs.python.org/issue17061
|
| 609 |
+
# We want to group the former case together but split the latter, so we
|
| 610 |
+
# track parentheses level, similar to the internals of tokenize.
|
| 611 |
+
|
| 612 |
+
# reexported from token on 3.7+
|
| 613 |
+
NEWLINE, NL = tokenize.NEWLINE, tokenize.NL # type: ignore
|
| 614 |
+
tokens_by_line: List[List[Any]] = [[]]
|
| 615 |
+
if len(lines) > 1 and not lines[0].endswith(("\n", "\r", "\r\n", "\x0b", "\x0c")):
|
| 616 |
+
warnings.warn(
|
| 617 |
+
"`make_tokens_by_line` received a list of lines which do not have lineending markers ('\\n', '\\r', '\\r\\n', '\\x0b', '\\x0c'), behavior will be unspecified",
|
| 618 |
+
stacklevel=2,
|
| 619 |
+
)
|
| 620 |
+
parenlev = 0
|
| 621 |
+
try:
|
| 622 |
+
for token in tokenutil.generate_tokens_catch_errors(
|
| 623 |
+
iter(lines).__next__, extra_errors_to_catch=["expected EOF"]
|
| 624 |
+
):
|
| 625 |
+
tokens_by_line[-1].append(token)
|
| 626 |
+
if (token.type == NEWLINE) \
|
| 627 |
+
or ((token.type == NL) and (parenlev <= 0)):
|
| 628 |
+
tokens_by_line.append([])
|
| 629 |
+
elif token.string in {'(', '[', '{'}:
|
| 630 |
+
parenlev += 1
|
| 631 |
+
elif token.string in {')', ']', '}'}:
|
| 632 |
+
if parenlev > 0:
|
| 633 |
+
parenlev -= 1
|
| 634 |
+
except tokenize.TokenError:
|
| 635 |
+
# Input ended in a multiline string or expression. That's OK for us.
|
| 636 |
+
pass
|
| 637 |
+
|
| 638 |
+
|
| 639 |
+
if not tokens_by_line[-1]:
|
| 640 |
+
tokens_by_line.pop()
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
return tokens_by_line
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
def has_sunken_brackets(tokens: List[tokenize.TokenInfo]):
|
| 647 |
+
"""Check if the depth of brackets in the list of tokens drops below 0"""
|
| 648 |
+
parenlev = 0
|
| 649 |
+
for token in tokens:
|
| 650 |
+
if token.string in {"(", "[", "{"}:
|
| 651 |
+
parenlev += 1
|
| 652 |
+
elif token.string in {")", "]", "}"}:
|
| 653 |
+
parenlev -= 1
|
| 654 |
+
if parenlev < 0:
|
| 655 |
+
return True
|
| 656 |
+
return False
|
| 657 |
+
|
| 658 |
+
# Arbitrary limit to prevent getting stuck in infinite loops
|
| 659 |
+
TRANSFORM_LOOP_LIMIT = 500
|
| 660 |
+
|
| 661 |
+
class TransformerManager:
|
| 662 |
+
"""Applies various transformations to a cell or code block.
|
| 663 |
+
|
| 664 |
+
The key methods for external use are ``transform_cell()``
|
| 665 |
+
and ``check_complete()``.
|
| 666 |
+
"""
|
| 667 |
+
def __init__(self):
|
| 668 |
+
self.cleanup_transforms = [
|
| 669 |
+
leading_empty_lines,
|
| 670 |
+
leading_indent,
|
| 671 |
+
classic_prompt,
|
| 672 |
+
ipython_prompt,
|
| 673 |
+
]
|
| 674 |
+
self.line_transforms = [
|
| 675 |
+
cell_magic,
|
| 676 |
+
]
|
| 677 |
+
self.token_transformers = [
|
| 678 |
+
MagicAssign,
|
| 679 |
+
SystemAssign,
|
| 680 |
+
EscapedCommand,
|
| 681 |
+
HelpEnd,
|
| 682 |
+
]
|
| 683 |
+
|
| 684 |
+
def do_one_token_transform(self, lines):
|
| 685 |
+
"""Find and run the transform earliest in the code.
|
| 686 |
+
|
| 687 |
+
Returns (changed, lines).
|
| 688 |
+
|
| 689 |
+
This method is called repeatedly until changed is False, indicating
|
| 690 |
+
that all available transformations are complete.
|
| 691 |
+
|
| 692 |
+
The tokens following IPython special syntax might not be valid, so
|
| 693 |
+
the transformed code is retokenised every time to identify the next
|
| 694 |
+
piece of special syntax. Hopefully long code cells are mostly valid
|
| 695 |
+
Python, not using lots of IPython special syntax, so this shouldn't be
|
| 696 |
+
a performance issue.
|
| 697 |
+
"""
|
| 698 |
+
tokens_by_line = make_tokens_by_line(lines)
|
| 699 |
+
candidates = []
|
| 700 |
+
for transformer_cls in self.token_transformers:
|
| 701 |
+
transformer = transformer_cls.find(tokens_by_line)
|
| 702 |
+
if transformer:
|
| 703 |
+
candidates.append(transformer)
|
| 704 |
+
|
| 705 |
+
if not candidates:
|
| 706 |
+
# Nothing to transform
|
| 707 |
+
return False, lines
|
| 708 |
+
ordered_transformers = sorted(candidates, key=TokenTransformBase.sortby)
|
| 709 |
+
for transformer in ordered_transformers:
|
| 710 |
+
try:
|
| 711 |
+
return True, transformer.transform(lines)
|
| 712 |
+
except SyntaxError:
|
| 713 |
+
pass
|
| 714 |
+
return False, lines
|
| 715 |
+
|
| 716 |
+
def do_token_transforms(self, lines):
|
| 717 |
+
for _ in range(TRANSFORM_LOOP_LIMIT):
|
| 718 |
+
changed, lines = self.do_one_token_transform(lines)
|
| 719 |
+
if not changed:
|
| 720 |
+
return lines
|
| 721 |
+
|
| 722 |
+
raise RuntimeError("Input transformation still changing after "
|
| 723 |
+
"%d iterations. Aborting." % TRANSFORM_LOOP_LIMIT)
|
| 724 |
+
|
| 725 |
+
def transform_cell(self, cell: str) -> str:
|
| 726 |
+
"""Transforms a cell of input code"""
|
| 727 |
+
if not cell.endswith('\n'):
|
| 728 |
+
cell += '\n' # Ensure the cell has a trailing newline
|
| 729 |
+
lines = cell.splitlines(keepends=True)
|
| 730 |
+
for transform in self.cleanup_transforms + self.line_transforms:
|
| 731 |
+
lines = transform(lines)
|
| 732 |
+
|
| 733 |
+
lines = self.do_token_transforms(lines)
|
| 734 |
+
return ''.join(lines)
|
| 735 |
+
|
| 736 |
+
def check_complete(self, cell: str):
|
| 737 |
+
"""Return whether a block of code is ready to execute, or should be continued
|
| 738 |
+
|
| 739 |
+
Parameters
|
| 740 |
+
----------
|
| 741 |
+
cell : string
|
| 742 |
+
Python input code, which can be multiline.
|
| 743 |
+
|
| 744 |
+
Returns
|
| 745 |
+
-------
|
| 746 |
+
status : str
|
| 747 |
+
One of 'complete', 'incomplete', or 'invalid' if source is not a
|
| 748 |
+
prefix of valid code.
|
| 749 |
+
indent_spaces : int or None
|
| 750 |
+
The number of spaces by which to indent the next line of code. If
|
| 751 |
+
status is not 'incomplete', this is None.
|
| 752 |
+
"""
|
| 753 |
+
# Remember if the lines ends in a new line.
|
| 754 |
+
ends_with_newline = False
|
| 755 |
+
for character in reversed(cell):
|
| 756 |
+
if character == '\n':
|
| 757 |
+
ends_with_newline = True
|
| 758 |
+
break
|
| 759 |
+
elif character.strip():
|
| 760 |
+
break
|
| 761 |
+
else:
|
| 762 |
+
continue
|
| 763 |
+
|
| 764 |
+
if not ends_with_newline:
|
| 765 |
+
# Append an newline for consistent tokenization
|
| 766 |
+
# See https://bugs.python.org/issue33899
|
| 767 |
+
cell += '\n'
|
| 768 |
+
|
| 769 |
+
lines = cell.splitlines(keepends=True)
|
| 770 |
+
|
| 771 |
+
if not lines:
|
| 772 |
+
return 'complete', None
|
| 773 |
+
|
| 774 |
+
for line in reversed(lines):
|
| 775 |
+
if not line.strip():
|
| 776 |
+
continue
|
| 777 |
+
elif line.strip("\n").endswith("\\"):
|
| 778 |
+
return "incomplete", find_last_indent(lines)
|
| 779 |
+
else:
|
| 780 |
+
break
|
| 781 |
+
|
| 782 |
+
try:
|
| 783 |
+
for transform in self.cleanup_transforms:
|
| 784 |
+
if not getattr(transform, 'has_side_effects', False):
|
| 785 |
+
lines = transform(lines)
|
| 786 |
+
except SyntaxError:
|
| 787 |
+
return 'invalid', None
|
| 788 |
+
|
| 789 |
+
if lines[0].startswith('%%'):
|
| 790 |
+
# Special case for cell magics - completion marked by blank line
|
| 791 |
+
if lines[-1].strip():
|
| 792 |
+
return 'incomplete', find_last_indent(lines)
|
| 793 |
+
else:
|
| 794 |
+
return 'complete', None
|
| 795 |
+
|
| 796 |
+
try:
|
| 797 |
+
for transform in self.line_transforms:
|
| 798 |
+
if not getattr(transform, 'has_side_effects', False):
|
| 799 |
+
lines = transform(lines)
|
| 800 |
+
lines = self.do_token_transforms(lines)
|
| 801 |
+
except SyntaxError:
|
| 802 |
+
return 'invalid', None
|
| 803 |
+
|
| 804 |
+
tokens_by_line = make_tokens_by_line(lines)
|
| 805 |
+
|
| 806 |
+
# Bail if we got one line and there are more closing parentheses than
|
| 807 |
+
# the opening ones
|
| 808 |
+
if (
|
| 809 |
+
len(lines) == 1
|
| 810 |
+
and tokens_by_line
|
| 811 |
+
and has_sunken_brackets(tokens_by_line[0])
|
| 812 |
+
):
|
| 813 |
+
return "invalid", None
|
| 814 |
+
|
| 815 |
+
if not tokens_by_line:
|
| 816 |
+
return 'incomplete', find_last_indent(lines)
|
| 817 |
+
|
| 818 |
+
if (
|
| 819 |
+
tokens_by_line[-1][-1].type != tokenize.ENDMARKER
|
| 820 |
+
and tokens_by_line[-1][-1].type != tokenize.ERRORTOKEN
|
| 821 |
+
):
|
| 822 |
+
# We're in a multiline string or expression
|
| 823 |
+
return 'incomplete', find_last_indent(lines)
|
| 824 |
+
|
| 825 |
+
newline_types = {tokenize.NEWLINE, tokenize.COMMENT, tokenize.ENDMARKER} # type: ignore
|
| 826 |
+
|
| 827 |
+
# Pop the last line which only contains DEDENTs and ENDMARKER
|
| 828 |
+
last_token_line = None
|
| 829 |
+
if {t.type for t in tokens_by_line[-1]} in [
|
| 830 |
+
{tokenize.DEDENT, tokenize.ENDMARKER},
|
| 831 |
+
{tokenize.ENDMARKER}
|
| 832 |
+
] and len(tokens_by_line) > 1:
|
| 833 |
+
last_token_line = tokens_by_line.pop()
|
| 834 |
+
|
| 835 |
+
while tokens_by_line[-1] and tokens_by_line[-1][-1].type in newline_types:
|
| 836 |
+
tokens_by_line[-1].pop()
|
| 837 |
+
|
| 838 |
+
if not tokens_by_line[-1]:
|
| 839 |
+
return 'incomplete', find_last_indent(lines)
|
| 840 |
+
|
| 841 |
+
if tokens_by_line[-1][-1].string == ':':
|
| 842 |
+
# The last line starts a block (e.g. 'if foo:')
|
| 843 |
+
ix = 0
|
| 844 |
+
while tokens_by_line[-1][ix].type in {tokenize.INDENT, tokenize.DEDENT}:
|
| 845 |
+
ix += 1
|
| 846 |
+
|
| 847 |
+
indent = tokens_by_line[-1][ix].start[1]
|
| 848 |
+
return 'incomplete', indent + 4
|
| 849 |
+
|
| 850 |
+
if tokens_by_line[-1][0].line.endswith('\\'):
|
| 851 |
+
return 'incomplete', None
|
| 852 |
+
|
| 853 |
+
# At this point, our checks think the code is complete (or invalid).
|
| 854 |
+
# We'll use codeop.compile_command to check this with the real parser
|
| 855 |
+
try:
|
| 856 |
+
with warnings.catch_warnings():
|
| 857 |
+
warnings.simplefilter('error', SyntaxWarning)
|
| 858 |
+
res = compile_command(''.join(lines), symbol='exec')
|
| 859 |
+
except (SyntaxError, OverflowError, ValueError, TypeError,
|
| 860 |
+
MemoryError, SyntaxWarning):
|
| 861 |
+
return 'invalid', None
|
| 862 |
+
else:
|
| 863 |
+
if res is None:
|
| 864 |
+
return 'incomplete', find_last_indent(lines)
|
| 865 |
+
|
| 866 |
+
if last_token_line and last_token_line[0].type == tokenize.DEDENT:
|
| 867 |
+
if ends_with_newline:
|
| 868 |
+
return 'complete', None
|
| 869 |
+
return 'incomplete', find_last_indent(lines)
|
| 870 |
+
|
| 871 |
+
# If there's a blank line at the end, assume we're ready to execute
|
| 872 |
+
if not lines[-1].strip():
|
| 873 |
+
return 'complete', None
|
| 874 |
+
|
| 875 |
+
return 'complete', None
|
| 876 |
+
|
| 877 |
+
|
| 878 |
+
def find_last_indent(lines):
|
| 879 |
+
m = _indent_re.match(lines[-1])
|
| 880 |
+
if not m:
|
| 881 |
+
return 0
|
| 882 |
+
return len(m.group(0).replace('\t', ' '*4))
|
| 883 |
+
|
| 884 |
+
|
| 885 |
+
class MaybeAsyncCompile(Compile):
|
| 886 |
+
def __init__(self, extra_flags=0):
|
| 887 |
+
super().__init__()
|
| 888 |
+
self.flags |= extra_flags
|
| 889 |
+
|
| 890 |
+
|
| 891 |
+
class MaybeAsyncCommandCompiler(CommandCompiler):
|
| 892 |
+
def __init__(self, extra_flags=0):
|
| 893 |
+
self.compiler = MaybeAsyncCompile(extra_flags=extra_flags)
|
| 894 |
+
|
| 895 |
+
|
| 896 |
+
_extra_flags = ast.PyCF_ALLOW_TOP_LEVEL_AWAIT
|
| 897 |
+
|
| 898 |
+
compile_command = MaybeAsyncCommandCompiler(extra_flags=_extra_flags)
|
lib/python3.12/site-packages/IPython/core/interactiveshell.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
lib/python3.12/site-packages/IPython/core/macro.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Support for interactive macros in IPython"""
|
| 2 |
+
|
| 3 |
+
#*****************************************************************************
|
| 4 |
+
# Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
|
| 5 |
+
#
|
| 6 |
+
# Distributed under the terms of the BSD License. The full license is in
|
| 7 |
+
# the file COPYING, distributed as part of this software.
|
| 8 |
+
#*****************************************************************************
|
| 9 |
+
|
| 10 |
+
import re
|
| 11 |
+
|
| 12 |
+
from IPython.utils.encoding import DEFAULT_ENCODING
|
| 13 |
+
|
| 14 |
+
coding_declaration = re.compile(r"#\s*coding[:=]\s*([-\w.]+)")
|
| 15 |
+
|
| 16 |
+
class Macro:
|
| 17 |
+
"""Simple class to store the value of macros as strings.
|
| 18 |
+
|
| 19 |
+
Macro is just a callable that executes a string of IPython
|
| 20 |
+
input when called.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
def __init__(self,code):
|
| 24 |
+
"""store the macro value, as a single string which can be executed"""
|
| 25 |
+
lines = []
|
| 26 |
+
enc = None
|
| 27 |
+
for line in code.splitlines():
|
| 28 |
+
coding_match = coding_declaration.match(line)
|
| 29 |
+
if coding_match:
|
| 30 |
+
enc = coding_match.group(1)
|
| 31 |
+
else:
|
| 32 |
+
lines.append(line)
|
| 33 |
+
code = "\n".join(lines)
|
| 34 |
+
if isinstance(code, bytes):
|
| 35 |
+
code = code.decode(enc or DEFAULT_ENCODING)
|
| 36 |
+
self.value = code + '\n'
|
| 37 |
+
|
| 38 |
+
def __str__(self):
|
| 39 |
+
return self.value
|
| 40 |
+
|
| 41 |
+
def __repr__(self):
|
| 42 |
+
return 'IPython.macro.Macro(%s)' % repr(self.value)
|
| 43 |
+
|
| 44 |
+
def __getstate__(self):
|
| 45 |
+
""" needed for safe pickling via %store """
|
| 46 |
+
return {'value': self.value}
|
| 47 |
+
|
| 48 |
+
def __add__(self, other):
|
| 49 |
+
if isinstance(other, Macro):
|
| 50 |
+
return Macro(self.value + other.value)
|
| 51 |
+
elif isinstance(other, str):
|
| 52 |
+
return Macro(self.value + other)
|
| 53 |
+
raise TypeError
|
lib/python3.12/site-packages/IPython/core/magic_arguments.py
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'''A decorator-based method of constructing IPython magics with `argparse`
|
| 2 |
+
option handling.
|
| 3 |
+
|
| 4 |
+
New magic functions can be defined like so::
|
| 5 |
+
|
| 6 |
+
from IPython.core.magic_arguments import (argument, magic_arguments,
|
| 7 |
+
parse_argstring)
|
| 8 |
+
|
| 9 |
+
@magic_arguments()
|
| 10 |
+
@argument('-o', '--option', help='An optional argument.')
|
| 11 |
+
@argument('arg', type=int, help='An integer positional argument.')
|
| 12 |
+
def magic_cool(self, arg):
|
| 13 |
+
""" A really cool magic command.
|
| 14 |
+
|
| 15 |
+
"""
|
| 16 |
+
args = parse_argstring(magic_cool, arg)
|
| 17 |
+
...
|
| 18 |
+
|
| 19 |
+
The `@magic_arguments` decorator marks the function as having argparse arguments.
|
| 20 |
+
The `@argument` decorator adds an argument using the same syntax as argparse's
|
| 21 |
+
`add_argument()` method. More sophisticated uses may also require the
|
| 22 |
+
`@argument_group` or `@kwds` decorator to customize the formatting and the
|
| 23 |
+
parsing.
|
| 24 |
+
|
| 25 |
+
Help text for the magic is automatically generated from the docstring and the
|
| 26 |
+
arguments::
|
| 27 |
+
|
| 28 |
+
In[1]: %cool?
|
| 29 |
+
%cool [-o OPTION] arg
|
| 30 |
+
|
| 31 |
+
A really cool magic command.
|
| 32 |
+
|
| 33 |
+
positional arguments:
|
| 34 |
+
arg An integer positional argument.
|
| 35 |
+
|
| 36 |
+
optional arguments:
|
| 37 |
+
-o OPTION, --option OPTION
|
| 38 |
+
An optional argument.
|
| 39 |
+
|
| 40 |
+
Here is an elaborated example that uses default parameters in `argument` and calls the `args` in the cell magic::
|
| 41 |
+
|
| 42 |
+
from IPython.core.magic import register_cell_magic
|
| 43 |
+
from IPython.core.magic_arguments import (argument, magic_arguments,
|
| 44 |
+
parse_argstring)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@magic_arguments()
|
| 48 |
+
@argument(
|
| 49 |
+
"--option",
|
| 50 |
+
"-o",
|
| 51 |
+
help=("Add an option here"),
|
| 52 |
+
)
|
| 53 |
+
@argument(
|
| 54 |
+
"--style",
|
| 55 |
+
"-s",
|
| 56 |
+
default="foo",
|
| 57 |
+
help=("Add some style arguments"),
|
| 58 |
+
)
|
| 59 |
+
@register_cell_magic
|
| 60 |
+
def my_cell_magic(line, cell):
|
| 61 |
+
args = parse_argstring(my_cell_magic, line)
|
| 62 |
+
print(f"{args.option=}")
|
| 63 |
+
print(f"{args.style=}")
|
| 64 |
+
print(f"{cell=}")
|
| 65 |
+
|
| 66 |
+
In a jupyter notebook, this cell magic can be executed like this::
|
| 67 |
+
|
| 68 |
+
%%my_cell_magic -o Hello
|
| 69 |
+
print("bar")
|
| 70 |
+
i = 42
|
| 71 |
+
|
| 72 |
+
Inheritance diagram:
|
| 73 |
+
|
| 74 |
+
.. inheritance-diagram:: IPython.core.magic_arguments
|
| 75 |
+
:parts: 3
|
| 76 |
+
|
| 77 |
+
'''
|
| 78 |
+
#-----------------------------------------------------------------------------
|
| 79 |
+
# Copyright (C) 2010-2011, IPython Development Team.
|
| 80 |
+
#
|
| 81 |
+
# Distributed under the terms of the Modified BSD License.
|
| 82 |
+
#
|
| 83 |
+
# The full license is in the file COPYING.txt, distributed with this software.
|
| 84 |
+
#-----------------------------------------------------------------------------
|
| 85 |
+
import argparse
|
| 86 |
+
import re
|
| 87 |
+
|
| 88 |
+
# Our own imports
|
| 89 |
+
from IPython.core.error import UsageError
|
| 90 |
+
from IPython.utils.decorators import undoc
|
| 91 |
+
from IPython.utils.process import arg_split
|
| 92 |
+
from IPython.utils.text import dedent
|
| 93 |
+
|
| 94 |
+
NAME_RE = re.compile(r"[a-zA-Z][a-zA-Z0-9_-]*$")
|
| 95 |
+
|
| 96 |
+
@undoc
|
| 97 |
+
class MagicHelpFormatter(argparse.RawDescriptionHelpFormatter):
|
| 98 |
+
"""A HelpFormatter with a couple of changes to meet our needs.
|
| 99 |
+
"""
|
| 100 |
+
# Modified to dedent text.
|
| 101 |
+
def _fill_text(self, text, width, indent):
|
| 102 |
+
return argparse.RawDescriptionHelpFormatter._fill_text(self, dedent(text), width, indent)
|
| 103 |
+
|
| 104 |
+
# Modified to wrap argument placeholders in <> where necessary.
|
| 105 |
+
def _format_action_invocation(self, action):
|
| 106 |
+
if not action.option_strings:
|
| 107 |
+
metavar, = self._metavar_formatter(action, action.dest)(1)
|
| 108 |
+
return metavar
|
| 109 |
+
|
| 110 |
+
else:
|
| 111 |
+
parts = []
|
| 112 |
+
|
| 113 |
+
# if the Optional doesn't take a value, format is:
|
| 114 |
+
# -s, --long
|
| 115 |
+
if action.nargs == 0:
|
| 116 |
+
parts.extend(action.option_strings)
|
| 117 |
+
|
| 118 |
+
# if the Optional takes a value, format is:
|
| 119 |
+
# -s ARGS, --long ARGS
|
| 120 |
+
else:
|
| 121 |
+
default = action.dest.upper()
|
| 122 |
+
args_string = self._format_args(action, default)
|
| 123 |
+
# IPYTHON MODIFICATION: If args_string is not a plain name, wrap
|
| 124 |
+
# it in <> so it's valid RST.
|
| 125 |
+
if not NAME_RE.match(args_string):
|
| 126 |
+
args_string = "<%s>" % args_string
|
| 127 |
+
for option_string in action.option_strings:
|
| 128 |
+
parts.append('%s %s' % (option_string, args_string))
|
| 129 |
+
|
| 130 |
+
return ', '.join(parts)
|
| 131 |
+
|
| 132 |
+
# Override the default prefix ('usage') to our % magic escape,
|
| 133 |
+
# in a code block.
|
| 134 |
+
def add_usage(self, usage, actions, groups, prefix="::\n\n %"):
|
| 135 |
+
super(MagicHelpFormatter, self).add_usage(usage, actions, groups, prefix)
|
| 136 |
+
|
| 137 |
+
class MagicArgumentParser(argparse.ArgumentParser):
|
| 138 |
+
""" An ArgumentParser tweaked for use by IPython magics.
|
| 139 |
+
"""
|
| 140 |
+
def __init__(self,
|
| 141 |
+
prog=None,
|
| 142 |
+
usage=None,
|
| 143 |
+
description=None,
|
| 144 |
+
epilog=None,
|
| 145 |
+
parents=None,
|
| 146 |
+
formatter_class=MagicHelpFormatter,
|
| 147 |
+
prefix_chars='-',
|
| 148 |
+
argument_default=None,
|
| 149 |
+
conflict_handler='error',
|
| 150 |
+
add_help=False):
|
| 151 |
+
if parents is None:
|
| 152 |
+
parents = []
|
| 153 |
+
super(MagicArgumentParser, self).__init__(prog=prog, usage=usage,
|
| 154 |
+
description=description, epilog=epilog,
|
| 155 |
+
parents=parents, formatter_class=formatter_class,
|
| 156 |
+
prefix_chars=prefix_chars, argument_default=argument_default,
|
| 157 |
+
conflict_handler=conflict_handler, add_help=add_help)
|
| 158 |
+
|
| 159 |
+
def error(self, message):
|
| 160 |
+
""" Raise a catchable error instead of exiting.
|
| 161 |
+
"""
|
| 162 |
+
raise UsageError(message)
|
| 163 |
+
|
| 164 |
+
def parse_argstring(self, argstring, *, partial=False):
|
| 165 |
+
""" Split a string into an argument list and parse that argument list.
|
| 166 |
+
"""
|
| 167 |
+
argv = arg_split(argstring, strict=not partial)
|
| 168 |
+
if partial:
|
| 169 |
+
return self.parse_known_args(argv)
|
| 170 |
+
return self.parse_args(argv)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def construct_parser(magic_func):
|
| 174 |
+
""" Construct an argument parser using the function decorations.
|
| 175 |
+
"""
|
| 176 |
+
kwds = getattr(magic_func, 'argcmd_kwds', {})
|
| 177 |
+
if 'description' not in kwds:
|
| 178 |
+
kwds['description'] = getattr(magic_func, '__doc__', None)
|
| 179 |
+
arg_name = real_name(magic_func)
|
| 180 |
+
parser = MagicArgumentParser(arg_name, **kwds)
|
| 181 |
+
# Reverse the list of decorators in order to apply them in the
|
| 182 |
+
# order in which they appear in the source.
|
| 183 |
+
group = None
|
| 184 |
+
for deco in magic_func.decorators[::-1]:
|
| 185 |
+
result = deco.add_to_parser(parser, group)
|
| 186 |
+
if result is not None:
|
| 187 |
+
group = result
|
| 188 |
+
|
| 189 |
+
# Replace the magic function's docstring with the full help text.
|
| 190 |
+
magic_func.__doc__ = parser.format_help()
|
| 191 |
+
|
| 192 |
+
return parser
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def parse_argstring(magic_func, argstring, *, partial=False):
|
| 196 |
+
""" Parse the string of arguments for the given magic function.
|
| 197 |
+
"""
|
| 198 |
+
return magic_func.parser.parse_argstring(argstring, partial=partial)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def real_name(magic_func):
|
| 202 |
+
""" Find the real name of the magic.
|
| 203 |
+
"""
|
| 204 |
+
magic_name = magic_func.__name__
|
| 205 |
+
if magic_name.startswith('magic_'):
|
| 206 |
+
magic_name = magic_name[len('magic_'):]
|
| 207 |
+
return getattr(magic_func, 'argcmd_name', magic_name)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
class ArgDecorator:
|
| 211 |
+
""" Base class for decorators to add ArgumentParser information to a method.
|
| 212 |
+
"""
|
| 213 |
+
|
| 214 |
+
def __call__(self, func):
|
| 215 |
+
if not getattr(func, 'has_arguments', False):
|
| 216 |
+
func.has_arguments = True
|
| 217 |
+
func.decorators = []
|
| 218 |
+
func.decorators.append(self)
|
| 219 |
+
return func
|
| 220 |
+
|
| 221 |
+
def add_to_parser(self, parser, group):
|
| 222 |
+
""" Add this object's information to the parser, if necessary.
|
| 223 |
+
"""
|
| 224 |
+
pass
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
class magic_arguments(ArgDecorator):
|
| 228 |
+
""" Mark the magic as having argparse arguments and possibly adjust the
|
| 229 |
+
name.
|
| 230 |
+
"""
|
| 231 |
+
|
| 232 |
+
def __init__(self, name=None):
|
| 233 |
+
self.name = name
|
| 234 |
+
|
| 235 |
+
def __call__(self, func):
|
| 236 |
+
if not getattr(func, 'has_arguments', False):
|
| 237 |
+
func.has_arguments = True
|
| 238 |
+
func.decorators = []
|
| 239 |
+
if self.name is not None:
|
| 240 |
+
func.argcmd_name = self.name
|
| 241 |
+
# This should be the first decorator in the list of decorators, thus the
|
| 242 |
+
# last to execute. Build the parser.
|
| 243 |
+
func.parser = construct_parser(func)
|
| 244 |
+
return func
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
class ArgMethodWrapper(ArgDecorator):
|
| 248 |
+
|
| 249 |
+
"""
|
| 250 |
+
Base class to define a wrapper for ArgumentParser method.
|
| 251 |
+
|
| 252 |
+
Child class must define either `_method_name` or `add_to_parser`.
|
| 253 |
+
|
| 254 |
+
"""
|
| 255 |
+
|
| 256 |
+
_method_name: str
|
| 257 |
+
|
| 258 |
+
def __init__(self, *args, **kwds):
|
| 259 |
+
self.args = args
|
| 260 |
+
self.kwds = kwds
|
| 261 |
+
|
| 262 |
+
def add_to_parser(self, parser, group):
|
| 263 |
+
""" Add this object's information to the parser.
|
| 264 |
+
"""
|
| 265 |
+
if group is not None:
|
| 266 |
+
parser = group
|
| 267 |
+
getattr(parser, self._method_name)(*self.args, **self.kwds)
|
| 268 |
+
return None
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
class argument(ArgMethodWrapper):
|
| 272 |
+
""" Store arguments and keywords to pass to add_argument().
|
| 273 |
+
|
| 274 |
+
Instances also serve to decorate command methods.
|
| 275 |
+
"""
|
| 276 |
+
_method_name = 'add_argument'
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
class defaults(ArgMethodWrapper):
|
| 280 |
+
""" Store arguments and keywords to pass to set_defaults().
|
| 281 |
+
|
| 282 |
+
Instances also serve to decorate command methods.
|
| 283 |
+
"""
|
| 284 |
+
_method_name = 'set_defaults'
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
class argument_group(ArgMethodWrapper):
|
| 288 |
+
""" Store arguments and keywords to pass to add_argument_group().
|
| 289 |
+
|
| 290 |
+
Instances also serve to decorate command methods.
|
| 291 |
+
"""
|
| 292 |
+
|
| 293 |
+
def add_to_parser(self, parser, group):
|
| 294 |
+
""" Add this object's information to the parser.
|
| 295 |
+
"""
|
| 296 |
+
return parser.add_argument_group(*self.args, **self.kwds)
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
class kwds(ArgDecorator):
|
| 300 |
+
""" Provide other keywords to the sub-parser constructor.
|
| 301 |
+
"""
|
| 302 |
+
def __init__(self, **kwds):
|
| 303 |
+
self.kwds = kwds
|
| 304 |
+
|
| 305 |
+
def __call__(self, func):
|
| 306 |
+
func = super(kwds, self).__call__(func)
|
| 307 |
+
func.argcmd_kwds = self.kwds
|
| 308 |
+
return func
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
__all__ = ['magic_arguments', 'argument', 'argument_group', 'kwds',
|
| 312 |
+
'parse_argstring']
|
lib/python3.12/site-packages/IPython/core/oinspect.py
ADDED
|
@@ -0,0 +1,1215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
+
"""Tools for inspecting Python objects.
|
| 2 |
+
|
| 3 |
+
Uses syntax highlighting for presenting the various information elements.
|
| 4 |
+
|
| 5 |
+
Similar in spirit to the inspect module, but all calls take a name argument to
|
| 6 |
+
reference the name under which an object is being read.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
# Copyright (c) IPython Development Team.
|
| 10 |
+
# Distributed under the terms of the Modified BSD License.
|
| 11 |
+
|
| 12 |
+
__all__ = ["Inspector"]
|
| 13 |
+
|
| 14 |
+
# stdlib modules
|
| 15 |
+
from dataclasses import dataclass
|
| 16 |
+
from inspect import signature
|
| 17 |
+
from textwrap import dedent
|
| 18 |
+
import ast
|
| 19 |
+
import html
|
| 20 |
+
import inspect
|
| 21 |
+
import io as stdlib_io
|
| 22 |
+
import linecache
|
| 23 |
+
import os
|
| 24 |
+
import types
|
| 25 |
+
import warnings
|
| 26 |
+
from pygments.token import Token
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
from typing import (
|
| 30 |
+
cast,
|
| 31 |
+
Any,
|
| 32 |
+
Optional,
|
| 33 |
+
Dict,
|
| 34 |
+
Union,
|
| 35 |
+
List,
|
| 36 |
+
TypedDict,
|
| 37 |
+
TypeAlias,
|
| 38 |
+
Tuple,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
import traitlets
|
| 42 |
+
from traitlets.config import Configurable
|
| 43 |
+
|
| 44 |
+
# IPython's own
|
| 45 |
+
from IPython.core import page
|
| 46 |
+
from IPython.lib.pretty import pretty
|
| 47 |
+
from IPython.testing.skipdoctest import skip_doctest
|
| 48 |
+
from IPython.utils import PyColorize, openpy
|
| 49 |
+
from IPython.utils.dir2 import safe_hasattr
|
| 50 |
+
from IPython.utils.path import compress_user
|
| 51 |
+
from IPython.utils.text import indent
|
| 52 |
+
from IPython.utils.wildcard import list_namespace, typestr2type
|
| 53 |
+
from IPython.utils.decorators import undoc
|
| 54 |
+
|
| 55 |
+
from pygments import highlight
|
| 56 |
+
from pygments.lexers import PythonLexer
|
| 57 |
+
from pygments.formatters import HtmlFormatter
|
| 58 |
+
|
| 59 |
+
HOOK_NAME = "__custom_documentations__"
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
UnformattedBundle: TypeAlias = Dict[str, List[Tuple[str, str]]] # List of (title, body)
|
| 63 |
+
Bundle: TypeAlias = Dict[str, str]
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@dataclass
|
| 67 |
+
class OInfo:
|
| 68 |
+
ismagic: bool
|
| 69 |
+
isalias: bool
|
| 70 |
+
found: bool
|
| 71 |
+
namespace: Optional[str]
|
| 72 |
+
parent: Any
|
| 73 |
+
obj: Any
|
| 74 |
+
|
| 75 |
+
def get(self, field):
|
| 76 |
+
"""Get a field from the object for backward compatibility with before 8.12
|
| 77 |
+
|
| 78 |
+
see https://github.com/h5py/h5py/issues/2253
|
| 79 |
+
"""
|
| 80 |
+
# We need to deprecate this at some point, but the warning will show in completion.
|
| 81 |
+
# Let's comment this for now and uncomment end of 2023 ish
|
| 82 |
+
# Jan 2025: decomenting for IPython 9.0
|
| 83 |
+
warnings.warn(
|
| 84 |
+
f"OInfo dataclass with fields access since IPython 8.12 please use OInfo.{field} instead."
|
| 85 |
+
"OInfo used to be a dict but a dataclass provide static fields verification with mypy."
|
| 86 |
+
"This warning and backward compatibility `get()` method were added in 8.13.",
|
| 87 |
+
DeprecationWarning,
|
| 88 |
+
stacklevel=2,
|
| 89 |
+
)
|
| 90 |
+
return getattr(self, field)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def pylight(code):
|
| 94 |
+
return highlight(code, PythonLexer(), HtmlFormatter(noclasses=True))
|
| 95 |
+
|
| 96 |
+
# builtin docstrings to ignore
|
| 97 |
+
_func_call_docstring = types.FunctionType.__call__.__doc__
|
| 98 |
+
_object_init_docstring = object.__init__.__doc__
|
| 99 |
+
_builtin_type_docstrings = {
|
| 100 |
+
inspect.getdoc(t) for t in (types.ModuleType, types.MethodType,
|
| 101 |
+
types.FunctionType, property)
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
_builtin_func_type = type(all)
|
| 105 |
+
_builtin_meth_type = type(str.upper) # Bound methods have the same type as builtin functions
|
| 106 |
+
#****************************************************************************
|
| 107 |
+
# Builtin color schemes
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
#****************************************************************************
|
| 111 |
+
# Auxiliary functions and objects
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class InfoDict(TypedDict):
|
| 115 |
+
type_name: Optional[str]
|
| 116 |
+
base_class: Optional[str]
|
| 117 |
+
string_form: Optional[str]
|
| 118 |
+
namespace: Optional[str]
|
| 119 |
+
length: Optional[str]
|
| 120 |
+
file: Optional[str]
|
| 121 |
+
definition: Optional[str]
|
| 122 |
+
docstring: Optional[str]
|
| 123 |
+
source: Optional[str]
|
| 124 |
+
init_definition: Optional[str]
|
| 125 |
+
class_docstring: Optional[str]
|
| 126 |
+
init_docstring: Optional[str]
|
| 127 |
+
call_def: Optional[str]
|
| 128 |
+
call_docstring: Optional[str]
|
| 129 |
+
subclasses: Optional[str]
|
| 130 |
+
# These won't be printed but will be used to determine how to
|
| 131 |
+
# format the object
|
| 132 |
+
ismagic: bool
|
| 133 |
+
isalias: bool
|
| 134 |
+
isclass: bool
|
| 135 |
+
found: bool
|
| 136 |
+
name: str
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
_info_fields = list(InfoDict.__annotations__.keys())
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def __getattr__(name):
|
| 143 |
+
if name == "info_fields":
|
| 144 |
+
warnings.warn(
|
| 145 |
+
"IPython.core.oinspect's `info_fields` is considered for deprecation and may be removed in the Future. ",
|
| 146 |
+
DeprecationWarning,
|
| 147 |
+
stacklevel=2,
|
| 148 |
+
)
|
| 149 |
+
return _info_fields
|
| 150 |
+
|
| 151 |
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
@dataclass
|
| 155 |
+
class InspectorHookData:
|
| 156 |
+
"""Data passed to the mime hook"""
|
| 157 |
+
|
| 158 |
+
obj: Any
|
| 159 |
+
info: Optional[OInfo]
|
| 160 |
+
info_dict: InfoDict
|
| 161 |
+
detail_level: int
|
| 162 |
+
omit_sections: list[str]
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
@undoc
|
| 166 |
+
def object_info(
|
| 167 |
+
*,
|
| 168 |
+
name: str,
|
| 169 |
+
found: bool,
|
| 170 |
+
isclass: bool = False,
|
| 171 |
+
isalias: bool = False,
|
| 172 |
+
ismagic: bool = False,
|
| 173 |
+
**kw,
|
| 174 |
+
) -> InfoDict:
|
| 175 |
+
"""Make an object info dict with all fields present."""
|
| 176 |
+
infodict = dict(kw)
|
| 177 |
+
infodict.update({k: None for k in _info_fields if k not in infodict})
|
| 178 |
+
infodict["name"] = name # type: ignore
|
| 179 |
+
infodict["found"] = found # type: ignore
|
| 180 |
+
infodict["isclass"] = isclass # type: ignore
|
| 181 |
+
infodict["isalias"] = isalias # type: ignore
|
| 182 |
+
infodict["ismagic"] = ismagic # type: ignore
|
| 183 |
+
|
| 184 |
+
return InfoDict(**infodict) # type:ignore
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def get_encoding(obj):
|
| 188 |
+
"""Get encoding for python source file defining obj
|
| 189 |
+
|
| 190 |
+
Returns None if obj is not defined in a sourcefile.
|
| 191 |
+
"""
|
| 192 |
+
ofile = find_file(obj)
|
| 193 |
+
# run contents of file through pager starting at line where the object
|
| 194 |
+
# is defined, as long as the file isn't binary and is actually on the
|
| 195 |
+
# filesystem.
|
| 196 |
+
if ofile is None:
|
| 197 |
+
return None
|
| 198 |
+
elif ofile.endswith(('.so', '.dll', '.pyd')):
|
| 199 |
+
return None
|
| 200 |
+
elif not os.path.isfile(ofile):
|
| 201 |
+
return None
|
| 202 |
+
else:
|
| 203 |
+
# Print only text files, not extension binaries. Note that
|
| 204 |
+
# getsourcelines returns lineno with 1-offset and page() uses
|
| 205 |
+
# 0-offset, so we must adjust.
|
| 206 |
+
with stdlib_io.open(ofile, 'rb') as buffer: # Tweaked to use io.open for Python 2
|
| 207 |
+
encoding, _lines = openpy.detect_encoding(buffer.readline)
|
| 208 |
+
return encoding
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def getdoc(obj) -> Union[str, None]:
|
| 212 |
+
"""Stable wrapper around inspect.getdoc.
|
| 213 |
+
|
| 214 |
+
This can't crash because of attribute problems.
|
| 215 |
+
|
| 216 |
+
It also attempts to call a getdoc() method on the given object. This
|
| 217 |
+
allows objects which provide their docstrings via non-standard mechanisms
|
| 218 |
+
(like Pyro proxies) to still be inspected by ipython's ? system.
|
| 219 |
+
"""
|
| 220 |
+
# Allow objects to offer customized documentation via a getdoc method:
|
| 221 |
+
try:
|
| 222 |
+
ds = obj.getdoc()
|
| 223 |
+
except Exception:
|
| 224 |
+
pass
|
| 225 |
+
else:
|
| 226 |
+
if isinstance(ds, str):
|
| 227 |
+
return inspect.cleandoc(ds)
|
| 228 |
+
docstr = inspect.getdoc(obj)
|
| 229 |
+
return docstr
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def getsource(obj, oname='') -> Union[str,None]:
|
| 233 |
+
"""Wrapper around inspect.getsource.
|
| 234 |
+
|
| 235 |
+
This can be modified by other projects to provide customized source
|
| 236 |
+
extraction.
|
| 237 |
+
|
| 238 |
+
Parameters
|
| 239 |
+
----------
|
| 240 |
+
obj : object
|
| 241 |
+
an object whose source code we will attempt to extract
|
| 242 |
+
oname : str
|
| 243 |
+
(optional) a name under which the object is known
|
| 244 |
+
|
| 245 |
+
Returns
|
| 246 |
+
-------
|
| 247 |
+
src : unicode or None
|
| 248 |
+
|
| 249 |
+
"""
|
| 250 |
+
|
| 251 |
+
if isinstance(obj, property):
|
| 252 |
+
sources = []
|
| 253 |
+
for attrname in ['fget', 'fset', 'fdel']:
|
| 254 |
+
fn = getattr(obj, attrname)
|
| 255 |
+
if fn is not None:
|
| 256 |
+
oname_prefix = ('%s.' % oname) if oname else ''
|
| 257 |
+
sources.append(''.join(('# ', oname_prefix, attrname)))
|
| 258 |
+
if inspect.isfunction(fn):
|
| 259 |
+
_src = getsource(fn)
|
| 260 |
+
if _src:
|
| 261 |
+
# assert _src is not None, "please mypy"
|
| 262 |
+
sources.append(dedent(_src))
|
| 263 |
+
else:
|
| 264 |
+
# Default str/repr only prints function name,
|
| 265 |
+
# pretty.pretty prints module name too.
|
| 266 |
+
sources.append(
|
| 267 |
+
'%s%s = %s\n' % (oname_prefix, attrname, pretty(fn))
|
| 268 |
+
)
|
| 269 |
+
if sources:
|
| 270 |
+
return '\n'.join(sources)
|
| 271 |
+
else:
|
| 272 |
+
return None
|
| 273 |
+
|
| 274 |
+
else:
|
| 275 |
+
# Get source for non-property objects.
|
| 276 |
+
|
| 277 |
+
obj = _get_wrapped(obj)
|
| 278 |
+
|
| 279 |
+
try:
|
| 280 |
+
src = inspect.getsource(obj)
|
| 281 |
+
except TypeError:
|
| 282 |
+
# The object itself provided no meaningful source, try looking for
|
| 283 |
+
# its class definition instead.
|
| 284 |
+
try:
|
| 285 |
+
src = inspect.getsource(obj.__class__)
|
| 286 |
+
except (OSError, TypeError):
|
| 287 |
+
return None
|
| 288 |
+
except OSError:
|
| 289 |
+
return None
|
| 290 |
+
|
| 291 |
+
return src
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def is_simple_callable(obj):
|
| 295 |
+
"""True if obj is a function ()"""
|
| 296 |
+
return (inspect.isfunction(obj) or inspect.ismethod(obj) or \
|
| 297 |
+
isinstance(obj, _builtin_func_type) or isinstance(obj, _builtin_meth_type))
|
| 298 |
+
|
| 299 |
+
def _get_wrapped(obj):
|
| 300 |
+
"""Get the original object if wrapped in one or more @decorators
|
| 301 |
+
|
| 302 |
+
Some objects automatically construct similar objects on any unrecognised
|
| 303 |
+
attribute access (e.g. unittest.mock.call). To protect against infinite loops,
|
| 304 |
+
this will arbitrarily cut off after 100 levels of obj.__wrapped__
|
| 305 |
+
attribute access. --TK, Jan 2016
|
| 306 |
+
"""
|
| 307 |
+
orig_obj = obj
|
| 308 |
+
i = 0
|
| 309 |
+
while safe_hasattr(obj, '__wrapped__'):
|
| 310 |
+
obj = obj.__wrapped__
|
| 311 |
+
i += 1
|
| 312 |
+
if i > 100:
|
| 313 |
+
# __wrapped__ is probably a lie, so return the thing we started with
|
| 314 |
+
return orig_obj
|
| 315 |
+
return obj
|
| 316 |
+
|
| 317 |
+
def find_file(obj) -> Optional[str]:
|
| 318 |
+
"""Find the absolute path to the file where an object was defined.
|
| 319 |
+
|
| 320 |
+
This is essentially a robust wrapper around `inspect.getabsfile`.
|
| 321 |
+
|
| 322 |
+
Returns None if no file can be found.
|
| 323 |
+
|
| 324 |
+
Parameters
|
| 325 |
+
----------
|
| 326 |
+
obj : any Python object
|
| 327 |
+
|
| 328 |
+
Returns
|
| 329 |
+
-------
|
| 330 |
+
fname : str
|
| 331 |
+
The absolute path to the file where the object was defined.
|
| 332 |
+
"""
|
| 333 |
+
obj = _get_wrapped(obj)
|
| 334 |
+
|
| 335 |
+
fname: Optional[str] = None
|
| 336 |
+
try:
|
| 337 |
+
fname = inspect.getabsfile(obj)
|
| 338 |
+
except TypeError:
|
| 339 |
+
# For an instance, the file that matters is where its class was
|
| 340 |
+
# declared.
|
| 341 |
+
try:
|
| 342 |
+
fname = inspect.getabsfile(obj.__class__)
|
| 343 |
+
except (OSError, TypeError):
|
| 344 |
+
# Can happen for builtins
|
| 345 |
+
pass
|
| 346 |
+
except OSError:
|
| 347 |
+
pass
|
| 348 |
+
|
| 349 |
+
return fname
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def find_source_lines(obj):
|
| 353 |
+
"""Find the line number in a file where an object was defined.
|
| 354 |
+
|
| 355 |
+
This is essentially a robust wrapper around `inspect.getsourcelines`.
|
| 356 |
+
|
| 357 |
+
Returns None if no file can be found.
|
| 358 |
+
|
| 359 |
+
Parameters
|
| 360 |
+
----------
|
| 361 |
+
obj : any Python object
|
| 362 |
+
|
| 363 |
+
Returns
|
| 364 |
+
-------
|
| 365 |
+
lineno : int
|
| 366 |
+
The line number where the object definition starts.
|
| 367 |
+
"""
|
| 368 |
+
obj = _get_wrapped(obj)
|
| 369 |
+
|
| 370 |
+
try:
|
| 371 |
+
lineno = inspect.getsourcelines(obj)[1]
|
| 372 |
+
except TypeError:
|
| 373 |
+
# For instances, try the class object like getsource() does
|
| 374 |
+
try:
|
| 375 |
+
lineno = inspect.getsourcelines(obj.__class__)[1]
|
| 376 |
+
except (OSError, TypeError):
|
| 377 |
+
return None
|
| 378 |
+
except OSError:
|
| 379 |
+
return None
|
| 380 |
+
|
| 381 |
+
return lineno
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
_sentinel = object()
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
class Inspector(Configurable):
|
| 388 |
+
mime_hooks = traitlets.Dict(
|
| 389 |
+
config=True,
|
| 390 |
+
help="dictionary of mime to callable to add information into help mimebundle dict",
|
| 391 |
+
).tag(config=True)
|
| 392 |
+
|
| 393 |
+
_theme_name: str
|
| 394 |
+
|
| 395 |
+
def __init__(
|
| 396 |
+
self,
|
| 397 |
+
*,
|
| 398 |
+
theme_name: str,
|
| 399 |
+
str_detail_level=0,
|
| 400 |
+
parent=None,
|
| 401 |
+
config=None,
|
| 402 |
+
):
|
| 403 |
+
if theme_name in ["Linux", "LightBG", "Neutral", "NoColor"]:
|
| 404 |
+
warnings.warn(
|
| 405 |
+
f"Theme names and color schemes are lowercase in IPython 9.0 use {theme_name.lower()} instead",
|
| 406 |
+
DeprecationWarning,
|
| 407 |
+
stacklevel=2,
|
| 408 |
+
)
|
| 409 |
+
theme_name = theme_name.lower()
|
| 410 |
+
self._theme_name = theme_name
|
| 411 |
+
super(Inspector, self).__init__(parent=parent, config=config)
|
| 412 |
+
self.parser = PyColorize.Parser(out="str", theme_name=theme_name)
|
| 413 |
+
self.str_detail_level = str_detail_level
|
| 414 |
+
self.set_theme_name(theme_name)
|
| 415 |
+
|
| 416 |
+
def format(self, *args, **kwargs):
|
| 417 |
+
return self.parser.format(*args, **kwargs)
|
| 418 |
+
|
| 419 |
+
def _getdef(self,obj,oname='') -> Union[str,None]:
|
| 420 |
+
"""Return the call signature for any callable object.
|
| 421 |
+
|
| 422 |
+
If any exception is generated, None is returned instead and the
|
| 423 |
+
exception is suppressed."""
|
| 424 |
+
if not callable(obj):
|
| 425 |
+
return None
|
| 426 |
+
try:
|
| 427 |
+
return _render_signature(signature(obj), oname)
|
| 428 |
+
except:
|
| 429 |
+
return None
|
| 430 |
+
|
| 431 |
+
def __head(self, h: str) -> str:
|
| 432 |
+
"""Return a header string with proper colors."""
|
| 433 |
+
return PyColorize.theme_table[self._theme_name].format([(Token.Header, h)])
|
| 434 |
+
|
| 435 |
+
def set_theme_name(self, name: str):
|
| 436 |
+
assert name == name.lower()
|
| 437 |
+
assert name in PyColorize.theme_table.keys()
|
| 438 |
+
self._theme_name = name
|
| 439 |
+
self.parser.theme_name = name
|
| 440 |
+
|
| 441 |
+
def set_active_scheme(self, scheme: str):
|
| 442 |
+
warnings.warn(
|
| 443 |
+
"set_active_scheme is deprecated and replaced by set_theme_name as of IPython 9.0",
|
| 444 |
+
DeprecationWarning,
|
| 445 |
+
stacklevel=2,
|
| 446 |
+
)
|
| 447 |
+
assert scheme == scheme.lower()
|
| 448 |
+
if scheme is not None and self._theme_name != scheme:
|
| 449 |
+
self._theme_name = scheme
|
| 450 |
+
self.parser.theme_name = scheme
|
| 451 |
+
|
| 452 |
+
def noinfo(self, msg, oname):
|
| 453 |
+
"""Generic message when no information is found."""
|
| 454 |
+
print('No %s found' % msg, end=' ')
|
| 455 |
+
if oname:
|
| 456 |
+
print('for %s' % oname)
|
| 457 |
+
else:
|
| 458 |
+
print()
|
| 459 |
+
|
| 460 |
+
def pdef(self, obj, oname=''):
|
| 461 |
+
"""Print the call signature for any callable object.
|
| 462 |
+
|
| 463 |
+
If the object is a class, print the constructor information."""
|
| 464 |
+
|
| 465 |
+
if not callable(obj):
|
| 466 |
+
print('Object is not callable.')
|
| 467 |
+
return
|
| 468 |
+
|
| 469 |
+
header = ''
|
| 470 |
+
|
| 471 |
+
if inspect.isclass(obj):
|
| 472 |
+
header = self.__head('Class constructor information:\n')
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
output = self._getdef(obj,oname)
|
| 476 |
+
if output is None:
|
| 477 |
+
self.noinfo('definition header',oname)
|
| 478 |
+
else:
|
| 479 |
+
print(header,self.format(output), end=' ')
|
| 480 |
+
|
| 481 |
+
# In Python 3, all classes are new-style, so they all have __init__.
|
| 482 |
+
@skip_doctest
|
| 483 |
+
def pdoc(self, obj, oname='', formatter=None):
|
| 484 |
+
"""Print the docstring for any object.
|
| 485 |
+
|
| 486 |
+
Optional:
|
| 487 |
+
-formatter: a function to run the docstring through for specially
|
| 488 |
+
formatted docstrings.
|
| 489 |
+
|
| 490 |
+
Examples
|
| 491 |
+
--------
|
| 492 |
+
In [1]: class NoInit:
|
| 493 |
+
...: pass
|
| 494 |
+
|
| 495 |
+
In [2]: class NoDoc:
|
| 496 |
+
...: def __init__(self):
|
| 497 |
+
...: pass
|
| 498 |
+
|
| 499 |
+
In [3]: %pdoc NoDoc
|
| 500 |
+
No documentation found for NoDoc
|
| 501 |
+
|
| 502 |
+
In [4]: %pdoc NoInit
|
| 503 |
+
No documentation found for NoInit
|
| 504 |
+
|
| 505 |
+
In [5]: obj = NoInit()
|
| 506 |
+
|
| 507 |
+
In [6]: %pdoc obj
|
| 508 |
+
No documentation found for obj
|
| 509 |
+
|
| 510 |
+
In [5]: obj2 = NoDoc()
|
| 511 |
+
|
| 512 |
+
In [6]: %pdoc obj2
|
| 513 |
+
No documentation found for obj2
|
| 514 |
+
"""
|
| 515 |
+
|
| 516 |
+
lines = []
|
| 517 |
+
ds = getdoc(obj)
|
| 518 |
+
if formatter:
|
| 519 |
+
ds = formatter(ds).get('plain/text', ds)
|
| 520 |
+
if ds:
|
| 521 |
+
lines.append(self.__head("Class docstring:"))
|
| 522 |
+
lines.append(indent(ds))
|
| 523 |
+
if inspect.isclass(obj) and hasattr(obj, '__init__'):
|
| 524 |
+
init_ds = getdoc(obj.__init__)
|
| 525 |
+
if init_ds is not None:
|
| 526 |
+
lines.append(self.__head("Init docstring:"))
|
| 527 |
+
lines.append(indent(init_ds))
|
| 528 |
+
elif hasattr(obj,'__call__'):
|
| 529 |
+
call_ds = getdoc(obj.__call__)
|
| 530 |
+
if call_ds:
|
| 531 |
+
lines.append(self.__head("Call docstring:"))
|
| 532 |
+
lines.append(indent(call_ds))
|
| 533 |
+
|
| 534 |
+
if not lines:
|
| 535 |
+
self.noinfo('documentation',oname)
|
| 536 |
+
else:
|
| 537 |
+
page.page('\n'.join(lines))
|
| 538 |
+
|
| 539 |
+
def psource(self, obj, oname=''):
|
| 540 |
+
"""Print the source code for an object."""
|
| 541 |
+
|
| 542 |
+
# Flush the source cache because inspect can return out-of-date source
|
| 543 |
+
linecache.checkcache()
|
| 544 |
+
try:
|
| 545 |
+
src = getsource(obj, oname=oname)
|
| 546 |
+
except Exception:
|
| 547 |
+
src = None
|
| 548 |
+
|
| 549 |
+
if src is None:
|
| 550 |
+
self.noinfo('source', oname)
|
| 551 |
+
else:
|
| 552 |
+
page.page(self.format(src))
|
| 553 |
+
|
| 554 |
+
def pfile(self, obj, oname=''):
|
| 555 |
+
"""Show the whole file where an object was defined."""
|
| 556 |
+
|
| 557 |
+
lineno = find_source_lines(obj)
|
| 558 |
+
if lineno is None:
|
| 559 |
+
self.noinfo('file', oname)
|
| 560 |
+
return
|
| 561 |
+
|
| 562 |
+
ofile = find_file(obj)
|
| 563 |
+
# run contents of file through pager starting at line where the object
|
| 564 |
+
# is defined, as long as the file isn't binary and is actually on the
|
| 565 |
+
# filesystem.
|
| 566 |
+
if ofile is None:
|
| 567 |
+
print("Could not find file for object")
|
| 568 |
+
elif ofile.endswith((".so", ".dll", ".pyd")):
|
| 569 |
+
print("File %r is binary, not printing." % ofile)
|
| 570 |
+
elif not os.path.isfile(ofile):
|
| 571 |
+
print('File %r does not exist, not printing.' % ofile)
|
| 572 |
+
else:
|
| 573 |
+
# Print only text files, not extension binaries. Note that
|
| 574 |
+
# getsourcelines returns lineno with 1-offset and page() uses
|
| 575 |
+
# 0-offset, so we must adjust.
|
| 576 |
+
page.page(self.format(openpy.read_py_file(ofile, skip_encoding_cookie=False)), lineno - 1)
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
def _mime_format(self, text:str, formatter=None) -> dict:
|
| 580 |
+
"""Return a mime bundle representation of the input text.
|
| 581 |
+
|
| 582 |
+
- if `formatter` is None, the returned mime bundle has
|
| 583 |
+
a ``text/plain`` field, with the input text.
|
| 584 |
+
a ``text/html`` field with a ``<pre>`` tag containing the input text.
|
| 585 |
+
|
| 586 |
+
- if ``formatter`` is not None, it must be a callable transforming the
|
| 587 |
+
input text into a mime bundle. Default values for ``text/plain`` and
|
| 588 |
+
``text/html`` representations are the ones described above.
|
| 589 |
+
|
| 590 |
+
Note:
|
| 591 |
+
|
| 592 |
+
Formatters returning strings are supported but this behavior is deprecated.
|
| 593 |
+
|
| 594 |
+
"""
|
| 595 |
+
defaults = {
|
| 596 |
+
"text/plain": text,
|
| 597 |
+
"text/html": f"<pre>{html.escape(text)}</pre>",
|
| 598 |
+
}
|
| 599 |
+
|
| 600 |
+
if formatter is None:
|
| 601 |
+
return defaults
|
| 602 |
+
else:
|
| 603 |
+
formatted = formatter(text)
|
| 604 |
+
|
| 605 |
+
if not isinstance(formatted, dict):
|
| 606 |
+
# Handle the deprecated behavior of a formatter returning
|
| 607 |
+
# a string instead of a mime bundle.
|
| 608 |
+
return {"text/plain": formatted, "text/html": f"<pre>{formatted}</pre>"}
|
| 609 |
+
|
| 610 |
+
else:
|
| 611 |
+
return dict(defaults, **formatted)
|
| 612 |
+
|
| 613 |
+
def format_mime(self, bundle: UnformattedBundle) -> Bundle:
|
| 614 |
+
"""Format a mimebundle being created by _make_info_unformatted into a real mimebundle"""
|
| 615 |
+
# Format text/plain mimetype
|
| 616 |
+
assert isinstance(bundle["text/plain"], list)
|
| 617 |
+
for item in bundle["text/plain"]:
|
| 618 |
+
assert isinstance(item, tuple)
|
| 619 |
+
|
| 620 |
+
new_b: Bundle = {}
|
| 621 |
+
lines = []
|
| 622 |
+
_len = max(len(h) for h, _ in bundle["text/plain"])
|
| 623 |
+
|
| 624 |
+
for head, body in bundle["text/plain"]:
|
| 625 |
+
body = body.strip("\n")
|
| 626 |
+
delim = "\n" if "\n" in body else " "
|
| 627 |
+
lines.append(
|
| 628 |
+
f"{self.__head(head+':')}{(_len - len(head))*' '}{delim}{body}"
|
| 629 |
+
)
|
| 630 |
+
|
| 631 |
+
new_b["text/plain"] = "\n".join(lines)
|
| 632 |
+
|
| 633 |
+
if "text/html" in bundle:
|
| 634 |
+
assert isinstance(bundle["text/html"], list)
|
| 635 |
+
for item in bundle["text/html"]:
|
| 636 |
+
assert isinstance(item, tuple)
|
| 637 |
+
# Format the text/html mimetype
|
| 638 |
+
if isinstance(bundle["text/html"], (list, tuple)):
|
| 639 |
+
# bundle['text/html'] is a list of (head, formatted body) pairs
|
| 640 |
+
new_b["text/html"] = "\n".join(
|
| 641 |
+
f"<h1>{head}</h1>\n{body}" for (head, body) in bundle["text/html"]
|
| 642 |
+
)
|
| 643 |
+
|
| 644 |
+
for k in bundle.keys():
|
| 645 |
+
if k in ("text/html", "text/plain"):
|
| 646 |
+
continue
|
| 647 |
+
else:
|
| 648 |
+
new_b[k] = bundle[k] # type:ignore
|
| 649 |
+
return new_b
|
| 650 |
+
|
| 651 |
+
def _append_info_field(
|
| 652 |
+
self,
|
| 653 |
+
bundle: UnformattedBundle,
|
| 654 |
+
title: str,
|
| 655 |
+
key: str,
|
| 656 |
+
info,
|
| 657 |
+
omit_sections: List[str],
|
| 658 |
+
formatter,
|
| 659 |
+
):
|
| 660 |
+
"""Append an info value to the unformatted mimebundle being constructed by _make_info_unformatted"""
|
| 661 |
+
if title in omit_sections or key in omit_sections:
|
| 662 |
+
return
|
| 663 |
+
field = info[key]
|
| 664 |
+
if field is not None:
|
| 665 |
+
formatted_field = self._mime_format(field, formatter)
|
| 666 |
+
bundle["text/plain"].append((title, formatted_field["text/plain"]))
|
| 667 |
+
bundle["text/html"].append((title, formatted_field["text/html"]))
|
| 668 |
+
|
| 669 |
+
def _make_info_unformatted(
|
| 670 |
+
self, obj, info, formatter, detail_level, omit_sections
|
| 671 |
+
) -> UnformattedBundle:
|
| 672 |
+
"""Assemble the mimebundle as unformatted lists of information"""
|
| 673 |
+
bundle: UnformattedBundle = {
|
| 674 |
+
"text/plain": [],
|
| 675 |
+
"text/html": [],
|
| 676 |
+
}
|
| 677 |
+
|
| 678 |
+
# A convenience function to simplify calls below
|
| 679 |
+
def append_field(
|
| 680 |
+
bundle: UnformattedBundle, title: str, key: str, formatter=None
|
| 681 |
+
):
|
| 682 |
+
self._append_info_field(
|
| 683 |
+
bundle,
|
| 684 |
+
title=title,
|
| 685 |
+
key=key,
|
| 686 |
+
info=info,
|
| 687 |
+
omit_sections=omit_sections,
|
| 688 |
+
formatter=formatter,
|
| 689 |
+
)
|
| 690 |
+
|
| 691 |
+
def code_formatter(text) -> Bundle:
|
| 692 |
+
return {
|
| 693 |
+
'text/plain': self.format(text),
|
| 694 |
+
'text/html': pylight(text)
|
| 695 |
+
}
|
| 696 |
+
|
| 697 |
+
if info["isalias"]:
|
| 698 |
+
append_field(bundle, "Repr", "string_form")
|
| 699 |
+
|
| 700 |
+
elif info['ismagic']:
|
| 701 |
+
if detail_level > 0:
|
| 702 |
+
append_field(bundle, "Source", "source", code_formatter)
|
| 703 |
+
else:
|
| 704 |
+
append_field(bundle, "Docstring", "docstring", formatter)
|
| 705 |
+
append_field(bundle, "File", "file")
|
| 706 |
+
|
| 707 |
+
elif info['isclass'] or is_simple_callable(obj):
|
| 708 |
+
# Functions, methods, classes
|
| 709 |
+
append_field(bundle, "Signature", "definition", code_formatter)
|
| 710 |
+
append_field(bundle, "Init signature", "init_definition", code_formatter)
|
| 711 |
+
append_field(bundle, "Docstring", "docstring", formatter)
|
| 712 |
+
if detail_level > 0 and info["source"]:
|
| 713 |
+
append_field(bundle, "Source", "source", code_formatter)
|
| 714 |
+
else:
|
| 715 |
+
append_field(bundle, "Init docstring", "init_docstring", formatter)
|
| 716 |
+
|
| 717 |
+
append_field(bundle, "File", "file")
|
| 718 |
+
append_field(bundle, "Type", "type_name")
|
| 719 |
+
append_field(bundle, "Subclasses", "subclasses")
|
| 720 |
+
|
| 721 |
+
else:
|
| 722 |
+
# General Python objects
|
| 723 |
+
append_field(bundle, "Signature", "definition", code_formatter)
|
| 724 |
+
append_field(bundle, "Call signature", "call_def", code_formatter)
|
| 725 |
+
append_field(bundle, "Type", "type_name")
|
| 726 |
+
append_field(bundle, "String form", "string_form")
|
| 727 |
+
|
| 728 |
+
# Namespace
|
| 729 |
+
if info["namespace"] != "Interactive":
|
| 730 |
+
append_field(bundle, "Namespace", "namespace")
|
| 731 |
+
|
| 732 |
+
append_field(bundle, "Length", "length")
|
| 733 |
+
append_field(bundle, "File", "file")
|
| 734 |
+
|
| 735 |
+
# Source or docstring, depending on detail level and whether
|
| 736 |
+
# source found.
|
| 737 |
+
if detail_level > 0 and info["source"]:
|
| 738 |
+
append_field(bundle, "Source", "source", code_formatter)
|
| 739 |
+
else:
|
| 740 |
+
append_field(bundle, "Docstring", "docstring", formatter)
|
| 741 |
+
|
| 742 |
+
append_field(bundle, "Class docstring", "class_docstring", formatter)
|
| 743 |
+
append_field(bundle, "Init docstring", "init_docstring", formatter)
|
| 744 |
+
append_field(bundle, "Call docstring", "call_docstring", formatter)
|
| 745 |
+
return bundle
|
| 746 |
+
|
| 747 |
+
|
| 748 |
+
def _get_info(
|
| 749 |
+
self,
|
| 750 |
+
obj: Any,
|
| 751 |
+
oname: str = "",
|
| 752 |
+
formatter=None,
|
| 753 |
+
info: Optional[OInfo] = None,
|
| 754 |
+
detail_level: int = 0,
|
| 755 |
+
omit_sections: Union[List[str], Tuple[()]] = (),
|
| 756 |
+
) -> Bundle:
|
| 757 |
+
"""Retrieve an info dict and format it.
|
| 758 |
+
|
| 759 |
+
Parameters
|
| 760 |
+
----------
|
| 761 |
+
obj : any
|
| 762 |
+
Object to inspect and return info from
|
| 763 |
+
oname : str (default: ''):
|
| 764 |
+
Name of the variable pointing to `obj`.
|
| 765 |
+
formatter : callable
|
| 766 |
+
info
|
| 767 |
+
already computed information
|
| 768 |
+
detail_level : integer
|
| 769 |
+
Granularity of detail level, if set to 1, give more information.
|
| 770 |
+
omit_sections : list[str]
|
| 771 |
+
Titles or keys to omit from output (can be set, tuple, etc., anything supporting `in`)
|
| 772 |
+
"""
|
| 773 |
+
|
| 774 |
+
info_dict = self.info(obj, oname=oname, info=info, detail_level=detail_level)
|
| 775 |
+
omit_sections = list(omit_sections)
|
| 776 |
+
|
| 777 |
+
bundle = self._make_info_unformatted(
|
| 778 |
+
obj,
|
| 779 |
+
info_dict,
|
| 780 |
+
formatter,
|
| 781 |
+
detail_level=detail_level,
|
| 782 |
+
omit_sections=omit_sections,
|
| 783 |
+
)
|
| 784 |
+
if self.mime_hooks:
|
| 785 |
+
hook_data = InspectorHookData(
|
| 786 |
+
obj=obj,
|
| 787 |
+
info=info,
|
| 788 |
+
info_dict=info_dict,
|
| 789 |
+
detail_level=detail_level,
|
| 790 |
+
omit_sections=omit_sections,
|
| 791 |
+
)
|
| 792 |
+
for key, hook in self.mime_hooks.items(): # type:ignore
|
| 793 |
+
required_parameters = [
|
| 794 |
+
parameter
|
| 795 |
+
for parameter in inspect.signature(hook).parameters.values()
|
| 796 |
+
if parameter.default != inspect.Parameter.default
|
| 797 |
+
]
|
| 798 |
+
if len(required_parameters) == 1:
|
| 799 |
+
res = hook(hook_data)
|
| 800 |
+
else:
|
| 801 |
+
warnings.warn(
|
| 802 |
+
"MIME hook format changed in IPython 8.22; hooks should now accept"
|
| 803 |
+
" a single parameter (InspectorHookData); support for hooks requiring"
|
| 804 |
+
" two-parameters (obj and info) will be removed in a future version",
|
| 805 |
+
DeprecationWarning,
|
| 806 |
+
stacklevel=2,
|
| 807 |
+
)
|
| 808 |
+
res = hook(obj, info)
|
| 809 |
+
if res is not None:
|
| 810 |
+
bundle[key] = res
|
| 811 |
+
return self.format_mime(bundle)
|
| 812 |
+
|
| 813 |
+
def pinfo(
|
| 814 |
+
self,
|
| 815 |
+
obj,
|
| 816 |
+
oname="",
|
| 817 |
+
formatter=None,
|
| 818 |
+
info: Optional[OInfo] = None,
|
| 819 |
+
detail_level=0,
|
| 820 |
+
enable_html_pager=True,
|
| 821 |
+
omit_sections=(),
|
| 822 |
+
):
|
| 823 |
+
"""Show detailed information about an object.
|
| 824 |
+
|
| 825 |
+
Optional arguments:
|
| 826 |
+
|
| 827 |
+
- oname: name of the variable pointing to the object.
|
| 828 |
+
|
| 829 |
+
- formatter: callable (optional)
|
| 830 |
+
A special formatter for docstrings.
|
| 831 |
+
|
| 832 |
+
The formatter is a callable that takes a string as an input
|
| 833 |
+
and returns either a formatted string or a mime type bundle
|
| 834 |
+
in the form of a dictionary.
|
| 835 |
+
|
| 836 |
+
Although the support of custom formatter returning a string
|
| 837 |
+
instead of a mime type bundle is deprecated.
|
| 838 |
+
|
| 839 |
+
- info: a structure with some information fields which may have been
|
| 840 |
+
precomputed already.
|
| 841 |
+
|
| 842 |
+
- detail_level: if set to 1, more information is given.
|
| 843 |
+
|
| 844 |
+
- omit_sections: set of section keys and titles to omit
|
| 845 |
+
"""
|
| 846 |
+
assert info is not None
|
| 847 |
+
info_b: Bundle = self._get_info(
|
| 848 |
+
obj, oname, formatter, info, detail_level, omit_sections=omit_sections
|
| 849 |
+
)
|
| 850 |
+
if not enable_html_pager:
|
| 851 |
+
del info_b["text/html"]
|
| 852 |
+
page.page(info_b)
|
| 853 |
+
|
| 854 |
+
def info(self, obj, oname="", info=None, detail_level=0) -> InfoDict:
|
| 855 |
+
"""Compute a dict with detailed information about an object.
|
| 856 |
+
|
| 857 |
+
Parameters
|
| 858 |
+
----------
|
| 859 |
+
obj : any
|
| 860 |
+
An object to find information about
|
| 861 |
+
oname : str (default: '')
|
| 862 |
+
Name of the variable pointing to `obj`.
|
| 863 |
+
info : (default: None)
|
| 864 |
+
A struct (dict like with attr access) with some information fields
|
| 865 |
+
which may have been precomputed already.
|
| 866 |
+
detail_level : int (default:0)
|
| 867 |
+
If set to 1, more information is given.
|
| 868 |
+
|
| 869 |
+
Returns
|
| 870 |
+
-------
|
| 871 |
+
An object info dict with known fields from `info_fields` (see `InfoDict`).
|
| 872 |
+
"""
|
| 873 |
+
|
| 874 |
+
if info is None:
|
| 875 |
+
ismagic = False
|
| 876 |
+
isalias = False
|
| 877 |
+
ospace = ''
|
| 878 |
+
else:
|
| 879 |
+
ismagic = info.ismagic
|
| 880 |
+
isalias = info.isalias
|
| 881 |
+
ospace = info.namespace
|
| 882 |
+
|
| 883 |
+
# Get docstring, special-casing aliases:
|
| 884 |
+
att_name = oname.split(".")[-1]
|
| 885 |
+
parents_docs = None
|
| 886 |
+
prelude = ""
|
| 887 |
+
if info and info.parent is not None and hasattr(info.parent, HOOK_NAME):
|
| 888 |
+
parents_docs_dict = getattr(info.parent, HOOK_NAME)
|
| 889 |
+
parents_docs = parents_docs_dict.get(att_name, None)
|
| 890 |
+
out: InfoDict = cast(
|
| 891 |
+
InfoDict,
|
| 892 |
+
{
|
| 893 |
+
**{field: None for field in _info_fields},
|
| 894 |
+
**{
|
| 895 |
+
"name": oname,
|
| 896 |
+
"found": True,
|
| 897 |
+
"isalias": isalias,
|
| 898 |
+
"ismagic": ismagic,
|
| 899 |
+
"subclasses": None,
|
| 900 |
+
},
|
| 901 |
+
},
|
| 902 |
+
)
|
| 903 |
+
|
| 904 |
+
if parents_docs:
|
| 905 |
+
ds = parents_docs
|
| 906 |
+
elif isalias:
|
| 907 |
+
if not callable(obj):
|
| 908 |
+
try:
|
| 909 |
+
ds = "Alias to the system command:\n %s" % obj[1]
|
| 910 |
+
except:
|
| 911 |
+
ds = "Alias: " + str(obj)
|
| 912 |
+
else:
|
| 913 |
+
ds = "Alias to " + str(obj)
|
| 914 |
+
if obj.__doc__:
|
| 915 |
+
ds += "\nDocstring:\n" + obj.__doc__
|
| 916 |
+
else:
|
| 917 |
+
ds_or_None = getdoc(obj)
|
| 918 |
+
if ds_or_None is None:
|
| 919 |
+
ds = '<no docstring>'
|
| 920 |
+
else:
|
| 921 |
+
ds = ds_or_None
|
| 922 |
+
|
| 923 |
+
ds = prelude + ds
|
| 924 |
+
|
| 925 |
+
# store output in a dict, we initialize it here and fill it as we go
|
| 926 |
+
|
| 927 |
+
string_max = 200 # max size of strings to show (snipped if longer)
|
| 928 |
+
shalf = int((string_max - 5) / 2)
|
| 929 |
+
|
| 930 |
+
if ismagic:
|
| 931 |
+
out['type_name'] = 'Magic function'
|
| 932 |
+
elif isalias:
|
| 933 |
+
out['type_name'] = 'System alias'
|
| 934 |
+
else:
|
| 935 |
+
out['type_name'] = type(obj).__name__
|
| 936 |
+
|
| 937 |
+
try:
|
| 938 |
+
bclass = obj.__class__
|
| 939 |
+
out['base_class'] = str(bclass)
|
| 940 |
+
except:
|
| 941 |
+
pass
|
| 942 |
+
|
| 943 |
+
# String form, but snip if too long in ? form (full in ??)
|
| 944 |
+
if detail_level >= self.str_detail_level:
|
| 945 |
+
try:
|
| 946 |
+
ostr = str(obj)
|
| 947 |
+
if not detail_level and len(ostr) > string_max:
|
| 948 |
+
ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
|
| 949 |
+
# TODO: `'string_form'.expandtabs()` seems wrong, but
|
| 950 |
+
# it was (nearly) like this since the first commit ever.
|
| 951 |
+
ostr = ("\n" + " " * len("string_form".expandtabs())).join(
|
| 952 |
+
q.strip() for q in ostr.split("\n")
|
| 953 |
+
)
|
| 954 |
+
out["string_form"] = ostr
|
| 955 |
+
except:
|
| 956 |
+
pass
|
| 957 |
+
|
| 958 |
+
if ospace:
|
| 959 |
+
out['namespace'] = ospace
|
| 960 |
+
|
| 961 |
+
# Length (for strings and lists)
|
| 962 |
+
try:
|
| 963 |
+
out['length'] = str(len(obj))
|
| 964 |
+
except Exception:
|
| 965 |
+
pass
|
| 966 |
+
|
| 967 |
+
# Filename where object was defined
|
| 968 |
+
binary_file = False
|
| 969 |
+
fname = find_file(obj)
|
| 970 |
+
if fname is None:
|
| 971 |
+
# if anything goes wrong, we don't want to show source, so it's as
|
| 972 |
+
# if the file was binary
|
| 973 |
+
binary_file = True
|
| 974 |
+
else:
|
| 975 |
+
if fname.endswith(('.so', '.dll', '.pyd')):
|
| 976 |
+
binary_file = True
|
| 977 |
+
elif fname.endswith('<string>'):
|
| 978 |
+
fname = 'Dynamically generated function. No source code available.'
|
| 979 |
+
out['file'] = compress_user(fname)
|
| 980 |
+
|
| 981 |
+
# Original source code for a callable, class or property.
|
| 982 |
+
if detail_level:
|
| 983 |
+
# Flush the source cache because inspect can return out-of-date
|
| 984 |
+
# source
|
| 985 |
+
linecache.checkcache()
|
| 986 |
+
try:
|
| 987 |
+
if isinstance(obj, property) or not binary_file:
|
| 988 |
+
src = getsource(obj, oname)
|
| 989 |
+
if src is not None:
|
| 990 |
+
src = src.rstrip()
|
| 991 |
+
out['source'] = src
|
| 992 |
+
|
| 993 |
+
except Exception:
|
| 994 |
+
pass
|
| 995 |
+
|
| 996 |
+
# Add docstring only if no source is to be shown (avoid repetitions).
|
| 997 |
+
if ds and not self._source_contains_docstring(out.get('source'), ds):
|
| 998 |
+
out['docstring'] = ds
|
| 999 |
+
|
| 1000 |
+
# Constructor docstring for classes
|
| 1001 |
+
if inspect.isclass(obj):
|
| 1002 |
+
out['isclass'] = True
|
| 1003 |
+
|
| 1004 |
+
# get the init signature:
|
| 1005 |
+
try:
|
| 1006 |
+
init_def = self._getdef(obj, oname)
|
| 1007 |
+
except AttributeError:
|
| 1008 |
+
init_def = None
|
| 1009 |
+
|
| 1010 |
+
# get the __init__ docstring
|
| 1011 |
+
try:
|
| 1012 |
+
obj_init = obj.__init__
|
| 1013 |
+
except AttributeError:
|
| 1014 |
+
init_ds = None
|
| 1015 |
+
else:
|
| 1016 |
+
if init_def is None:
|
| 1017 |
+
# Get signature from init if top-level sig failed.
|
| 1018 |
+
# Can happen for built-in types (list, etc.).
|
| 1019 |
+
try:
|
| 1020 |
+
init_def = self._getdef(obj_init, oname)
|
| 1021 |
+
except AttributeError:
|
| 1022 |
+
pass
|
| 1023 |
+
init_ds = getdoc(obj_init)
|
| 1024 |
+
# Skip Python's auto-generated docstrings
|
| 1025 |
+
if init_ds == _object_init_docstring:
|
| 1026 |
+
init_ds = None
|
| 1027 |
+
|
| 1028 |
+
if init_def:
|
| 1029 |
+
out['init_definition'] = init_def
|
| 1030 |
+
|
| 1031 |
+
if init_ds:
|
| 1032 |
+
out['init_docstring'] = init_ds
|
| 1033 |
+
|
| 1034 |
+
names = [sub.__name__ for sub in type.__subclasses__(obj)]
|
| 1035 |
+
if len(names) < 10:
|
| 1036 |
+
all_names = ', '.join(names)
|
| 1037 |
+
else:
|
| 1038 |
+
all_names = ', '.join(names[:10]+['...'])
|
| 1039 |
+
out['subclasses'] = all_names
|
| 1040 |
+
# and class docstring for instances:
|
| 1041 |
+
else:
|
| 1042 |
+
# reconstruct the function definition and print it:
|
| 1043 |
+
defln = self._getdef(obj, oname)
|
| 1044 |
+
if defln:
|
| 1045 |
+
out['definition'] = defln
|
| 1046 |
+
|
| 1047 |
+
# First, check whether the instance docstring is identical to the
|
| 1048 |
+
# class one, and print it separately if they don't coincide. In
|
| 1049 |
+
# most cases they will, but it's nice to print all the info for
|
| 1050 |
+
# objects which use instance-customized docstrings.
|
| 1051 |
+
if ds:
|
| 1052 |
+
try:
|
| 1053 |
+
cls = getattr(obj,'__class__')
|
| 1054 |
+
except:
|
| 1055 |
+
class_ds = None
|
| 1056 |
+
else:
|
| 1057 |
+
class_ds = getdoc(cls)
|
| 1058 |
+
# Skip Python's auto-generated docstrings
|
| 1059 |
+
if class_ds in _builtin_type_docstrings:
|
| 1060 |
+
class_ds = None
|
| 1061 |
+
if class_ds and ds != class_ds:
|
| 1062 |
+
out['class_docstring'] = class_ds
|
| 1063 |
+
|
| 1064 |
+
# Next, try to show constructor docstrings
|
| 1065 |
+
try:
|
| 1066 |
+
init_ds = getdoc(obj.__init__)
|
| 1067 |
+
# Skip Python's auto-generated docstrings
|
| 1068 |
+
if init_ds == _object_init_docstring:
|
| 1069 |
+
init_ds = None
|
| 1070 |
+
except AttributeError:
|
| 1071 |
+
init_ds = None
|
| 1072 |
+
if init_ds:
|
| 1073 |
+
out['init_docstring'] = init_ds
|
| 1074 |
+
|
| 1075 |
+
# Call form docstring for callable instances
|
| 1076 |
+
if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
|
| 1077 |
+
call_def = self._getdef(obj.__call__, oname)
|
| 1078 |
+
if call_def and (call_def != out.get('definition')):
|
| 1079 |
+
# it may never be the case that call def and definition differ,
|
| 1080 |
+
# but don't include the same signature twice
|
| 1081 |
+
out['call_def'] = call_def
|
| 1082 |
+
call_ds = getdoc(obj.__call__)
|
| 1083 |
+
# Skip Python's auto-generated docstrings
|
| 1084 |
+
if call_ds == _func_call_docstring:
|
| 1085 |
+
call_ds = None
|
| 1086 |
+
if call_ds:
|
| 1087 |
+
out['call_docstring'] = call_ds
|
| 1088 |
+
|
| 1089 |
+
return out
|
| 1090 |
+
|
| 1091 |
+
@staticmethod
|
| 1092 |
+
def _source_contains_docstring(src, doc):
|
| 1093 |
+
"""
|
| 1094 |
+
Check whether the source *src* contains the docstring *doc*.
|
| 1095 |
+
|
| 1096 |
+
This is is helper function to skip displaying the docstring if the
|
| 1097 |
+
source already contains it, avoiding repetition of information.
|
| 1098 |
+
"""
|
| 1099 |
+
try:
|
| 1100 |
+
(def_node,) = ast.parse(dedent(src)).body
|
| 1101 |
+
return ast.get_docstring(def_node) == doc # type: ignore[arg-type]
|
| 1102 |
+
except Exception:
|
| 1103 |
+
# The source can become invalid or even non-existent (because it
|
| 1104 |
+
# is re-fetched from the source file) so the above code fail in
|
| 1105 |
+
# arbitrary ways.
|
| 1106 |
+
return False
|
| 1107 |
+
|
| 1108 |
+
def psearch(self,pattern,ns_table,ns_search=[],
|
| 1109 |
+
ignore_case=False,show_all=False, *, list_types=False):
|
| 1110 |
+
"""Search namespaces with wildcards for objects.
|
| 1111 |
+
|
| 1112 |
+
Arguments:
|
| 1113 |
+
|
| 1114 |
+
- pattern: string containing shell-like wildcards to use in namespace
|
| 1115 |
+
searches and optionally a type specification to narrow the search to
|
| 1116 |
+
objects of that type.
|
| 1117 |
+
|
| 1118 |
+
- ns_table: dict of name->namespaces for search.
|
| 1119 |
+
|
| 1120 |
+
Optional arguments:
|
| 1121 |
+
|
| 1122 |
+
- ns_search: list of namespace names to include in search.
|
| 1123 |
+
|
| 1124 |
+
- ignore_case(False): make the search case-insensitive.
|
| 1125 |
+
|
| 1126 |
+
- show_all(False): show all names, including those starting with
|
| 1127 |
+
underscores.
|
| 1128 |
+
|
| 1129 |
+
- list_types(False): list all available object types for object matching.
|
| 1130 |
+
"""
|
| 1131 |
+
# print('ps pattern:<%r>' % pattern) # dbg
|
| 1132 |
+
|
| 1133 |
+
# defaults
|
| 1134 |
+
type_pattern = 'all'
|
| 1135 |
+
filter = ''
|
| 1136 |
+
|
| 1137 |
+
# list all object types
|
| 1138 |
+
if list_types:
|
| 1139 |
+
page.page('\n'.join(sorted(typestr2type)))
|
| 1140 |
+
return
|
| 1141 |
+
|
| 1142 |
+
cmds = pattern.split()
|
| 1143 |
+
len_cmds = len(cmds)
|
| 1144 |
+
if len_cmds == 1:
|
| 1145 |
+
# Only filter pattern given
|
| 1146 |
+
filter = cmds[0]
|
| 1147 |
+
elif len_cmds == 2:
|
| 1148 |
+
# Both filter and type specified
|
| 1149 |
+
filter,type_pattern = cmds
|
| 1150 |
+
else:
|
| 1151 |
+
raise ValueError('invalid argument string for psearch: <%s>' %
|
| 1152 |
+
pattern)
|
| 1153 |
+
|
| 1154 |
+
# filter search namespaces
|
| 1155 |
+
for name in ns_search:
|
| 1156 |
+
if name not in ns_table:
|
| 1157 |
+
raise ValueError('invalid namespace <%s>. Valid names: %s' %
|
| 1158 |
+
(name,ns_table.keys()))
|
| 1159 |
+
|
| 1160 |
+
# print('type_pattern:',type_pattern) # dbg
|
| 1161 |
+
search_result, namespaces_seen = set(), set()
|
| 1162 |
+
for ns_name in ns_search:
|
| 1163 |
+
ns = ns_table[ns_name]
|
| 1164 |
+
# Normally, locals and globals are the same, so we just check one.
|
| 1165 |
+
if id(ns) in namespaces_seen:
|
| 1166 |
+
continue
|
| 1167 |
+
namespaces_seen.add(id(ns))
|
| 1168 |
+
tmp_res = list_namespace(ns, type_pattern, filter,
|
| 1169 |
+
ignore_case=ignore_case, show_all=show_all)
|
| 1170 |
+
search_result.update(tmp_res)
|
| 1171 |
+
|
| 1172 |
+
page.page('\n'.join(sorted(search_result)))
|
| 1173 |
+
|
| 1174 |
+
|
| 1175 |
+
def _render_signature(obj_signature, obj_name) -> str:
|
| 1176 |
+
"""
|
| 1177 |
+
This was mostly taken from inspect.Signature.__str__.
|
| 1178 |
+
Look there for the comments.
|
| 1179 |
+
The only change is to add linebreaks when this gets too long.
|
| 1180 |
+
"""
|
| 1181 |
+
result = []
|
| 1182 |
+
pos_only = False
|
| 1183 |
+
kw_only = True
|
| 1184 |
+
for param in obj_signature.parameters.values():
|
| 1185 |
+
if param.kind == inspect.Parameter.POSITIONAL_ONLY:
|
| 1186 |
+
pos_only = True
|
| 1187 |
+
elif pos_only:
|
| 1188 |
+
result.append('/')
|
| 1189 |
+
pos_only = False
|
| 1190 |
+
|
| 1191 |
+
if param.kind == inspect.Parameter.VAR_POSITIONAL:
|
| 1192 |
+
kw_only = False
|
| 1193 |
+
elif param.kind == inspect.Parameter.KEYWORD_ONLY and kw_only:
|
| 1194 |
+
result.append('*')
|
| 1195 |
+
kw_only = False
|
| 1196 |
+
|
| 1197 |
+
result.append(str(param))
|
| 1198 |
+
|
| 1199 |
+
if pos_only:
|
| 1200 |
+
result.append('/')
|
| 1201 |
+
|
| 1202 |
+
# add up name, parameters, braces (2), and commas
|
| 1203 |
+
if len(obj_name) + sum(len(r) + 2 for r in result) > 75:
|
| 1204 |
+
# This doesn’t fit behind “Signature: ” in an inspect window.
|
| 1205 |
+
rendered = '{}(\n{})'.format(obj_name, ''.join(
|
| 1206 |
+
' {},\n'.format(r) for r in result)
|
| 1207 |
+
)
|
| 1208 |
+
else:
|
| 1209 |
+
rendered = '{}({})'.format(obj_name, ', '.join(result))
|
| 1210 |
+
|
| 1211 |
+
if obj_signature.return_annotation is not inspect._empty:
|
| 1212 |
+
anno = inspect.formatannotation(obj_signature.return_annotation)
|
| 1213 |
+
rendered += ' -> {}'.format(anno)
|
| 1214 |
+
|
| 1215 |
+
return rendered
|
lib/python3.12/site-packages/IPython/core/page.py
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# encoding: utf-8
|
| 2 |
+
"""
|
| 3 |
+
Paging capabilities for IPython.core
|
| 4 |
+
|
| 5 |
+
Notes
|
| 6 |
+
-----
|
| 7 |
+
|
| 8 |
+
For now this uses IPython hooks, so it can't be in IPython.utils. If we can get
|
| 9 |
+
rid of that dependency, we could move it there.
|
| 10 |
+
-----
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
# Copyright (c) IPython Development Team.
|
| 14 |
+
# Distributed under the terms of the Modified BSD License.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
import io
|
| 19 |
+
import re
|
| 20 |
+
import sys
|
| 21 |
+
import tempfile
|
| 22 |
+
import subprocess
|
| 23 |
+
|
| 24 |
+
from io import UnsupportedOperation
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
from IPython import get_ipython
|
| 28 |
+
from IPython.display import display
|
| 29 |
+
from IPython.core.error import TryNext
|
| 30 |
+
from IPython.utils.data import chop
|
| 31 |
+
from IPython.utils.process import system
|
| 32 |
+
from IPython.utils.terminal import get_terminal_size
|
| 33 |
+
from IPython.utils import py3compat
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def display_page(strng, start=0, screen_lines=25):
|
| 37 |
+
"""Just display, no paging. screen_lines is ignored."""
|
| 38 |
+
if isinstance(strng, dict):
|
| 39 |
+
data = strng
|
| 40 |
+
else:
|
| 41 |
+
if start:
|
| 42 |
+
strng = u'\n'.join(strng.splitlines()[start:])
|
| 43 |
+
data = { 'text/plain': strng }
|
| 44 |
+
display(data, raw=True)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def as_hook(page_func):
|
| 48 |
+
"""Wrap a pager func to strip the `self` arg
|
| 49 |
+
|
| 50 |
+
so it can be called as a hook.
|
| 51 |
+
"""
|
| 52 |
+
return lambda self, *args, **kwargs: page_func(*args, **kwargs)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
esc_re = re.compile(r"(\x1b[^m]+m)")
|
| 56 |
+
|
| 57 |
+
def page_dumb(strng, start=0, screen_lines=25):
|
| 58 |
+
"""Very dumb 'pager' in Python, for when nothing else works.
|
| 59 |
+
|
| 60 |
+
Only moves forward, same interface as page(), except for pager_cmd and
|
| 61 |
+
mode.
|
| 62 |
+
"""
|
| 63 |
+
if isinstance(strng, dict):
|
| 64 |
+
strng = strng.get('text/plain', '')
|
| 65 |
+
out_ln = strng.splitlines()[start:]
|
| 66 |
+
screens = chop(out_ln,screen_lines-1)
|
| 67 |
+
if len(screens) == 1:
|
| 68 |
+
print(os.linesep.join(screens[0]))
|
| 69 |
+
else:
|
| 70 |
+
last_escape = ""
|
| 71 |
+
for scr in screens[0:-1]:
|
| 72 |
+
hunk = os.linesep.join(scr)
|
| 73 |
+
print(last_escape + hunk)
|
| 74 |
+
if not page_more():
|
| 75 |
+
return
|
| 76 |
+
esc_list = esc_re.findall(hunk)
|
| 77 |
+
if len(esc_list) > 0:
|
| 78 |
+
last_escape = esc_list[-1]
|
| 79 |
+
print(last_escape + os.linesep.join(screens[-1]))
|
| 80 |
+
|
| 81 |
+
def _detect_screen_size(screen_lines_def):
|
| 82 |
+
"""Attempt to work out the number of lines on the screen.
|
| 83 |
+
|
| 84 |
+
This is called by page(). It can raise an error (e.g. when run in the
|
| 85 |
+
test suite), so it's separated out so it can easily be called in a try block.
|
| 86 |
+
"""
|
| 87 |
+
TERM = os.environ.get('TERM',None)
|
| 88 |
+
if not((TERM=='xterm' or TERM=='xterm-color') and sys.platform != 'sunos5'):
|
| 89 |
+
# curses causes problems on many terminals other than xterm, and
|
| 90 |
+
# some termios calls lock up on Sun OS5.
|
| 91 |
+
return screen_lines_def
|
| 92 |
+
|
| 93 |
+
try:
|
| 94 |
+
import termios
|
| 95 |
+
import curses
|
| 96 |
+
except ImportError:
|
| 97 |
+
return screen_lines_def
|
| 98 |
+
|
| 99 |
+
# There is a bug in curses, where *sometimes* it fails to properly
|
| 100 |
+
# initialize, and then after the endwin() call is made, the
|
| 101 |
+
# terminal is left in an unusable state. Rather than trying to
|
| 102 |
+
# check every time for this (by requesting and comparing termios
|
| 103 |
+
# flags each time), we just save the initial terminal state and
|
| 104 |
+
# unconditionally reset it every time. It's cheaper than making
|
| 105 |
+
# the checks.
|
| 106 |
+
try:
|
| 107 |
+
term_flags = termios.tcgetattr(sys.stdout)
|
| 108 |
+
except termios.error as err:
|
| 109 |
+
# can fail on Linux 2.6, pager_page will catch the TypeError
|
| 110 |
+
raise TypeError('termios error: {0}'.format(err)) from err
|
| 111 |
+
|
| 112 |
+
try:
|
| 113 |
+
scr = curses.initscr()
|
| 114 |
+
except AttributeError:
|
| 115 |
+
# Curses on Solaris may not be complete, so we can't use it there
|
| 116 |
+
return screen_lines_def
|
| 117 |
+
|
| 118 |
+
screen_lines_real,screen_cols = scr.getmaxyx()
|
| 119 |
+
curses.endwin()
|
| 120 |
+
|
| 121 |
+
# Restore terminal state in case endwin() didn't.
|
| 122 |
+
termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
|
| 123 |
+
# Now we have what we needed: the screen size in rows/columns
|
| 124 |
+
return screen_lines_real
|
| 125 |
+
# print('***Screen size:',screen_lines_real,'lines x',
|
| 126 |
+
# screen_cols,'columns.') # dbg
|
| 127 |
+
|
| 128 |
+
def pager_page(strng, start=0, screen_lines=0, pager_cmd=None) -> None:
|
| 129 |
+
"""Display a string, piping through a pager after a certain length.
|
| 130 |
+
|
| 131 |
+
strng can be a mime-bundle dict, supplying multiple representations,
|
| 132 |
+
keyed by mime-type.
|
| 133 |
+
|
| 134 |
+
The screen_lines parameter specifies the number of *usable* lines of your
|
| 135 |
+
terminal screen (total lines minus lines you need to reserve to show other
|
| 136 |
+
information).
|
| 137 |
+
|
| 138 |
+
If you set screen_lines to a number <=0, page() will try to auto-determine
|
| 139 |
+
your screen size and will only use up to (screen_size+screen_lines) for
|
| 140 |
+
printing, paging after that. That is, if you want auto-detection but need
|
| 141 |
+
to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
|
| 142 |
+
auto-detection without any lines reserved simply use screen_lines = 0.
|
| 143 |
+
|
| 144 |
+
If a string won't fit in the allowed lines, it is sent through the
|
| 145 |
+
specified pager command. If none given, look for PAGER in the environment,
|
| 146 |
+
and ultimately default to less.
|
| 147 |
+
|
| 148 |
+
If no system pager works, the string is sent through a 'dumb pager'
|
| 149 |
+
written in python, very simplistic.
|
| 150 |
+
"""
|
| 151 |
+
|
| 152 |
+
# for compatibility with mime-bundle form:
|
| 153 |
+
if isinstance(strng, dict):
|
| 154 |
+
strng = strng['text/plain']
|
| 155 |
+
|
| 156 |
+
# Ugly kludge, but calling curses.initscr() flat out crashes in emacs
|
| 157 |
+
TERM = os.environ.get('TERM','dumb')
|
| 158 |
+
if TERM in ['dumb','emacs'] and os.name != 'nt':
|
| 159 |
+
print(strng)
|
| 160 |
+
return
|
| 161 |
+
# chop off the topmost part of the string we don't want to see
|
| 162 |
+
str_lines = strng.splitlines()[start:]
|
| 163 |
+
str_toprint = os.linesep.join(str_lines)
|
| 164 |
+
num_newlines = len(str_lines)
|
| 165 |
+
len_str = len(str_toprint)
|
| 166 |
+
|
| 167 |
+
# Dumb heuristics to guesstimate number of on-screen lines the string
|
| 168 |
+
# takes. Very basic, but good enough for docstrings in reasonable
|
| 169 |
+
# terminals. If someone later feels like refining it, it's not hard.
|
| 170 |
+
numlines = max(num_newlines,int(len_str/80)+1)
|
| 171 |
+
|
| 172 |
+
screen_lines_def = get_terminal_size()[1]
|
| 173 |
+
|
| 174 |
+
# auto-determine screen size
|
| 175 |
+
if screen_lines <= 0:
|
| 176 |
+
try:
|
| 177 |
+
screen_lines += _detect_screen_size(screen_lines_def)
|
| 178 |
+
except (TypeError, UnsupportedOperation):
|
| 179 |
+
print(str_toprint)
|
| 180 |
+
return
|
| 181 |
+
|
| 182 |
+
# print('numlines',numlines,'screenlines',screen_lines) # dbg
|
| 183 |
+
if numlines <= screen_lines :
|
| 184 |
+
# print('*** normal print') # dbg
|
| 185 |
+
print(str_toprint)
|
| 186 |
+
else:
|
| 187 |
+
# Try to open pager and default to internal one if that fails.
|
| 188 |
+
# All failure modes are tagged as 'retval=1', to match the return
|
| 189 |
+
# value of a failed system command. If any intermediate attempt
|
| 190 |
+
# sets retval to 1, at the end we resort to our own page_dumb() pager.
|
| 191 |
+
pager_cmd = get_pager_cmd(pager_cmd)
|
| 192 |
+
pager_cmd += ' ' + get_pager_start(pager_cmd,start)
|
| 193 |
+
if os.name == 'nt':
|
| 194 |
+
if pager_cmd.startswith('type'):
|
| 195 |
+
# The default WinXP 'type' command is failing on complex strings.
|
| 196 |
+
retval = 1
|
| 197 |
+
else:
|
| 198 |
+
fd, tmpname = tempfile.mkstemp('.txt')
|
| 199 |
+
tmppath = Path(tmpname)
|
| 200 |
+
try:
|
| 201 |
+
os.close(fd)
|
| 202 |
+
with tmppath.open("wt", encoding="utf-8") as tmpfile:
|
| 203 |
+
tmpfile.write(strng)
|
| 204 |
+
cmd = "%s < %s" % (pager_cmd, tmppath)
|
| 205 |
+
# tmpfile needs to be closed for windows
|
| 206 |
+
if os.system(cmd):
|
| 207 |
+
retval = 1
|
| 208 |
+
else:
|
| 209 |
+
retval = None
|
| 210 |
+
finally:
|
| 211 |
+
Path.unlink(tmppath)
|
| 212 |
+
else:
|
| 213 |
+
try:
|
| 214 |
+
retval = None
|
| 215 |
+
# Emulate os.popen, but redirect stderr
|
| 216 |
+
proc = subprocess.Popen(
|
| 217 |
+
pager_cmd,
|
| 218 |
+
shell=True,
|
| 219 |
+
stdin=subprocess.PIPE,
|
| 220 |
+
stderr=subprocess.DEVNULL,
|
| 221 |
+
)
|
| 222 |
+
pager = os._wrap_close(
|
| 223 |
+
io.TextIOWrapper(proc.stdin, encoding="utf-8"), proc
|
| 224 |
+
)
|
| 225 |
+
try:
|
| 226 |
+
pager_encoding = pager.encoding or sys.stdout.encoding
|
| 227 |
+
pager.write(strng)
|
| 228 |
+
finally:
|
| 229 |
+
retval = pager.close()
|
| 230 |
+
except IOError as msg: # broken pipe when user quits
|
| 231 |
+
if msg.args == (32, 'Broken pipe'):
|
| 232 |
+
retval = None
|
| 233 |
+
else:
|
| 234 |
+
retval = 1
|
| 235 |
+
except OSError:
|
| 236 |
+
# Other strange problems, sometimes seen in Win2k/cygwin
|
| 237 |
+
retval = 1
|
| 238 |
+
if retval is not None:
|
| 239 |
+
page_dumb(strng,screen_lines=screen_lines)
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def page(data, start: int = 0, screen_lines: int = 0, pager_cmd=None):
|
| 243 |
+
"""Display content in a pager, piping through a pager after a certain length.
|
| 244 |
+
|
| 245 |
+
data can be a mime-bundle dict, supplying multiple representations,
|
| 246 |
+
keyed by mime-type, or text.
|
| 247 |
+
|
| 248 |
+
Pager is dispatched via the `show_in_pager` IPython hook.
|
| 249 |
+
If no hook is registered, `pager_page` will be used.
|
| 250 |
+
"""
|
| 251 |
+
# Some routines may auto-compute start offsets incorrectly and pass a
|
| 252 |
+
# negative value. Offset to 0 for robustness.
|
| 253 |
+
start = max(0, start)
|
| 254 |
+
|
| 255 |
+
# first, try the hook
|
| 256 |
+
ip = get_ipython()
|
| 257 |
+
if ip:
|
| 258 |
+
try:
|
| 259 |
+
ip.hooks.show_in_pager(data, start=start, screen_lines=screen_lines)
|
| 260 |
+
return
|
| 261 |
+
except TryNext:
|
| 262 |
+
pass
|
| 263 |
+
|
| 264 |
+
# fallback on default pager
|
| 265 |
+
return pager_page(data, start, screen_lines, pager_cmd)
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def page_file(fname, start=0, pager_cmd=None):
|
| 269 |
+
"""Page a file, using an optional pager command and starting line.
|
| 270 |
+
"""
|
| 271 |
+
|
| 272 |
+
pager_cmd = get_pager_cmd(pager_cmd)
|
| 273 |
+
pager_cmd += ' ' + get_pager_start(pager_cmd,start)
|
| 274 |
+
|
| 275 |
+
try:
|
| 276 |
+
if os.environ['TERM'] in ['emacs','dumb']:
|
| 277 |
+
raise EnvironmentError
|
| 278 |
+
system(pager_cmd + ' ' + fname)
|
| 279 |
+
except:
|
| 280 |
+
try:
|
| 281 |
+
if start > 0:
|
| 282 |
+
start -= 1
|
| 283 |
+
page(open(fname, encoding="utf-8").read(), start)
|
| 284 |
+
except:
|
| 285 |
+
print('Unable to show file',repr(fname))
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def get_pager_cmd(pager_cmd=None):
|
| 289 |
+
"""Return a pager command.
|
| 290 |
+
|
| 291 |
+
Makes some attempts at finding an OS-correct one.
|
| 292 |
+
"""
|
| 293 |
+
if os.name == 'posix':
|
| 294 |
+
default_pager_cmd = 'less -R' # -R for color control sequences
|
| 295 |
+
elif os.name in ['nt','dos']:
|
| 296 |
+
default_pager_cmd = 'type'
|
| 297 |
+
|
| 298 |
+
if pager_cmd is None:
|
| 299 |
+
try:
|
| 300 |
+
pager_cmd = os.environ['PAGER']
|
| 301 |
+
except:
|
| 302 |
+
pager_cmd = default_pager_cmd
|
| 303 |
+
|
| 304 |
+
if pager_cmd == 'less' and '-r' not in os.environ.get('LESS', '').lower():
|
| 305 |
+
pager_cmd += ' -R'
|
| 306 |
+
|
| 307 |
+
return pager_cmd
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def get_pager_start(pager, start):
|
| 311 |
+
"""Return the string for paging files with an offset.
|
| 312 |
+
|
| 313 |
+
This is the '+N' argument which less and more (under Unix) accept.
|
| 314 |
+
"""
|
| 315 |
+
|
| 316 |
+
if pager in ['less','more']:
|
| 317 |
+
if start:
|
| 318 |
+
start_string = '+' + str(start)
|
| 319 |
+
else:
|
| 320 |
+
start_string = ''
|
| 321 |
+
else:
|
| 322 |
+
start_string = ''
|
| 323 |
+
return start_string
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
# (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch()
|
| 327 |
+
if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
|
| 328 |
+
import msvcrt
|
| 329 |
+
def page_more():
|
| 330 |
+
""" Smart pausing between pages
|
| 331 |
+
|
| 332 |
+
@return: True if need print more lines, False if quit
|
| 333 |
+
"""
|
| 334 |
+
sys.stdout.write('---Return to continue, q to quit--- ')
|
| 335 |
+
ans = msvcrt.getwch()
|
| 336 |
+
if ans in ("q", "Q"):
|
| 337 |
+
result = False
|
| 338 |
+
else:
|
| 339 |
+
result = True
|
| 340 |
+
sys.stdout.write("\b"*37 + " "*37 + "\b"*37)
|
| 341 |
+
return result
|
| 342 |
+
else:
|
| 343 |
+
def page_more():
|
| 344 |
+
ans = py3compat.input('---Return to continue, q to quit--- ')
|
| 345 |
+
if ans.lower().startswith('q'):
|
| 346 |
+
return False
|
| 347 |
+
else:
|
| 348 |
+
return True
|
lib/python3.12/site-packages/IPython/core/payload.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""Payload system for IPython.
|
| 3 |
+
|
| 4 |
+
Authors:
|
| 5 |
+
|
| 6 |
+
* Fernando Perez
|
| 7 |
+
* Brian Granger
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
#-----------------------------------------------------------------------------
|
| 11 |
+
# Copyright (C) 2008-2011 The IPython Development Team
|
| 12 |
+
#
|
| 13 |
+
# Distributed under the terms of the BSD License. The full license is in
|
| 14 |
+
# the file COPYING, distributed as part of this software.
|
| 15 |
+
#-----------------------------------------------------------------------------
|
| 16 |
+
|
| 17 |
+
#-----------------------------------------------------------------------------
|
| 18 |
+
# Imports
|
| 19 |
+
#-----------------------------------------------------------------------------
|
| 20 |
+
|
| 21 |
+
from traitlets.config.configurable import Configurable
|
| 22 |
+
from traitlets import List
|
| 23 |
+
|
| 24 |
+
#-----------------------------------------------------------------------------
|
| 25 |
+
# Main payload class
|
| 26 |
+
#-----------------------------------------------------------------------------
|
| 27 |
+
|
| 28 |
+
class PayloadManager(Configurable):
|
| 29 |
+
_payload: List = List([])
|
| 30 |
+
|
| 31 |
+
def write_payload(self, data, single=True):
|
| 32 |
+
"""Include or update the specified `data` payload in the PayloadManager.
|
| 33 |
+
|
| 34 |
+
If a previous payload with the same source exists and `single` is True,
|
| 35 |
+
it will be overwritten with the new one.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
if not isinstance(data, dict):
|
| 39 |
+
raise TypeError('Each payload write must be a dict, got: %r' % data)
|
| 40 |
+
|
| 41 |
+
if single and 'source' in data:
|
| 42 |
+
source = data['source']
|
| 43 |
+
for i, pl in enumerate(self._payload):
|
| 44 |
+
if 'source' in pl and pl['source'] == source:
|
| 45 |
+
self._payload[i] = data
|
| 46 |
+
return
|
| 47 |
+
|
| 48 |
+
self._payload.append(data)
|
| 49 |
+
|
| 50 |
+
def read_payload(self):
|
| 51 |
+
return self._payload
|
| 52 |
+
|
| 53 |
+
def clear_payload(self):
|
| 54 |
+
self._payload = []
|
lib/python3.12/site-packages/IPython/core/payloadpage.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A payload based version of page."""
|
| 2 |
+
|
| 3 |
+
# Copyright (c) IPython Development Team.
|
| 4 |
+
# Distributed under the terms of the Modified BSD License.
|
| 5 |
+
|
| 6 |
+
import warnings
|
| 7 |
+
from IPython.core.getipython import get_ipython
|
| 8 |
+
|
| 9 |
+
# see https://github.com/ipython/ipykernel/issues/1304
|
| 10 |
+
# this should be moved to ipykernel and removed in the long run.
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def page(strng, start=0, screen_lines=0, pager_cmd=None):
|
| 14 |
+
"""Print a string, piping through a pager.
|
| 15 |
+
|
| 16 |
+
This version ignores the screen_lines and pager_cmd arguments and uses
|
| 17 |
+
IPython's payload system instead.
|
| 18 |
+
|
| 19 |
+
Parameters
|
| 20 |
+
----------
|
| 21 |
+
strng : str or mime-dict
|
| 22 |
+
Text to page, or a mime-type keyed dict of already formatted data.
|
| 23 |
+
start : int
|
| 24 |
+
Starting line at which to place the display.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
# Some routines may auto-compute start offsets incorrectly and pass a
|
| 28 |
+
# negative value. Offset to 0 for robustness.
|
| 29 |
+
start = max(0, start)
|
| 30 |
+
shell = get_ipython()
|
| 31 |
+
|
| 32 |
+
if isinstance(strng, dict):
|
| 33 |
+
data = strng
|
| 34 |
+
else:
|
| 35 |
+
data = {"text/plain": strng}
|
| 36 |
+
payload = dict(
|
| 37 |
+
source="page",
|
| 38 |
+
data=data,
|
| 39 |
+
start=start,
|
| 40 |
+
)
|
| 41 |
+
shell.payload_manager.write_payload(payload)
|
lib/python3.12/site-packages/IPython/core/prefilter.py
ADDED
|
@@ -0,0 +1,707 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# encoding: utf-8
|
| 2 |
+
"""
|
| 3 |
+
Prefiltering components.
|
| 4 |
+
|
| 5 |
+
Prefilters transform user input before it is exec'd by Python. These
|
| 6 |
+
transforms are used to implement additional syntax such as !ls and %magic.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
# Copyright (c) IPython Development Team.
|
| 10 |
+
# Distributed under the terms of the Modified BSD License.
|
| 11 |
+
|
| 12 |
+
from keyword import iskeyword
|
| 13 |
+
import re
|
| 14 |
+
|
| 15 |
+
from .autocall import IPyAutocall
|
| 16 |
+
from traitlets.config.configurable import Configurable
|
| 17 |
+
from .inputtransformer2 import (
|
| 18 |
+
ESC_MAGIC,
|
| 19 |
+
ESC_QUOTE,
|
| 20 |
+
ESC_QUOTE2,
|
| 21 |
+
ESC_PAREN,
|
| 22 |
+
)
|
| 23 |
+
from .macro import Macro
|
| 24 |
+
from .splitinput import LineInfo
|
| 25 |
+
|
| 26 |
+
from traitlets import (
|
| 27 |
+
List, Integer, Unicode, Bool, Instance, CRegExp
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
#-----------------------------------------------------------------------------
|
| 31 |
+
# Global utilities, errors and constants
|
| 32 |
+
#-----------------------------------------------------------------------------
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class PrefilterError(Exception):
|
| 36 |
+
pass
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# RegExp to identify potential function names
|
| 40 |
+
re_fun_name = re.compile(r'[^\W\d]([\w.]*) *$')
|
| 41 |
+
|
| 42 |
+
# RegExp to exclude strings with this start from autocalling. In
|
| 43 |
+
# particular, all binary operators should be excluded, so that if foo is
|
| 44 |
+
# callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
|
| 45 |
+
# characters '!=()' don't need to be checked for, as the checkPythonChars
|
| 46 |
+
# routine explicitly does so, to catch direct calls and rebindings of
|
| 47 |
+
# existing names.
|
| 48 |
+
|
| 49 |
+
# Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
|
| 50 |
+
# it affects the rest of the group in square brackets.
|
| 51 |
+
re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
|
| 52 |
+
r'|^is |^not |^in |^and |^or ')
|
| 53 |
+
|
| 54 |
+
# try to catch also methods for stuff in lists/tuples/dicts: off
|
| 55 |
+
# (experimental). For this to work, the line_split regexp would need
|
| 56 |
+
# to be modified so it wouldn't break things at '['. That line is
|
| 57 |
+
# nasty enough that I shouldn't change it until I can test it _well_.
|
| 58 |
+
#self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# Handler Check Utilities
|
| 62 |
+
def is_shadowed(identifier, ip):
|
| 63 |
+
"""Is the given identifier defined in one of the namespaces which shadow
|
| 64 |
+
the alias and magic namespaces? Note that an identifier is different
|
| 65 |
+
than ifun, because it can not contain a '.' character."""
|
| 66 |
+
# This is much safer than calling ofind, which can change state
|
| 67 |
+
return (identifier in ip.user_ns \
|
| 68 |
+
or identifier in ip.user_global_ns \
|
| 69 |
+
or identifier in ip.ns_table['builtin']\
|
| 70 |
+
or iskeyword(identifier))
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
#-----------------------------------------------------------------------------
|
| 74 |
+
# Main Prefilter manager
|
| 75 |
+
#-----------------------------------------------------------------------------
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class PrefilterManager(Configurable):
|
| 79 |
+
"""Main prefilter component.
|
| 80 |
+
|
| 81 |
+
The IPython prefilter is run on all user input before it is run. The
|
| 82 |
+
prefilter consumes lines of input and produces transformed lines of
|
| 83 |
+
input.
|
| 84 |
+
|
| 85 |
+
The implementation consists of two phases:
|
| 86 |
+
|
| 87 |
+
1. Transformers
|
| 88 |
+
2. Checkers and handlers
|
| 89 |
+
|
| 90 |
+
Over time, we plan on deprecating the checkers and handlers and doing
|
| 91 |
+
everything in the transformers.
|
| 92 |
+
|
| 93 |
+
The transformers are instances of :class:`PrefilterTransformer` and have
|
| 94 |
+
a single method :meth:`transform` that takes a line and returns a
|
| 95 |
+
transformed line. The transformation can be accomplished using any
|
| 96 |
+
tool, but our current ones use regular expressions for speed.
|
| 97 |
+
|
| 98 |
+
After all the transformers have been run, the line is fed to the checkers,
|
| 99 |
+
which are instances of :class:`PrefilterChecker`. The line is passed to
|
| 100 |
+
the :meth:`check` method, which either returns `None` or a
|
| 101 |
+
:class:`PrefilterHandler` instance. If `None` is returned, the other
|
| 102 |
+
checkers are tried. If an :class:`PrefilterHandler` instance is returned,
|
| 103 |
+
the line is passed to the :meth:`handle` method of the returned
|
| 104 |
+
handler and no further checkers are tried.
|
| 105 |
+
|
| 106 |
+
Both transformers and checkers have a `priority` attribute, that determines
|
| 107 |
+
the order in which they are called. Smaller priorities are tried first.
|
| 108 |
+
|
| 109 |
+
Both transformers and checkers also have `enabled` attribute, which is
|
| 110 |
+
a boolean that determines if the instance is used.
|
| 111 |
+
|
| 112 |
+
Users or developers can change the priority or enabled attribute of
|
| 113 |
+
transformers or checkers, but they must call the :meth:`sort_checkers`
|
| 114 |
+
or :meth:`sort_transformers` method after changing the priority.
|
| 115 |
+
"""
|
| 116 |
+
|
| 117 |
+
multi_line_specials = Bool(True).tag(config=True)
|
| 118 |
+
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
|
| 119 |
+
|
| 120 |
+
def __init__(self, shell=None, **kwargs):
|
| 121 |
+
super(PrefilterManager, self).__init__(shell=shell, **kwargs)
|
| 122 |
+
self.shell = shell
|
| 123 |
+
self._transformers = []
|
| 124 |
+
self.init_handlers()
|
| 125 |
+
self.init_checkers()
|
| 126 |
+
|
| 127 |
+
#-------------------------------------------------------------------------
|
| 128 |
+
# API for managing transformers
|
| 129 |
+
#-------------------------------------------------------------------------
|
| 130 |
+
|
| 131 |
+
def sort_transformers(self):
|
| 132 |
+
"""Sort the transformers by priority.
|
| 133 |
+
|
| 134 |
+
This must be called after the priority of a transformer is changed.
|
| 135 |
+
The :meth:`register_transformer` method calls this automatically.
|
| 136 |
+
"""
|
| 137 |
+
self._transformers.sort(key=lambda x: x.priority)
|
| 138 |
+
|
| 139 |
+
@property
|
| 140 |
+
def transformers(self):
|
| 141 |
+
"""Return a list of checkers, sorted by priority."""
|
| 142 |
+
return self._transformers
|
| 143 |
+
|
| 144 |
+
def register_transformer(self, transformer):
|
| 145 |
+
"""Register a transformer instance."""
|
| 146 |
+
if transformer not in self._transformers:
|
| 147 |
+
self._transformers.append(transformer)
|
| 148 |
+
self.sort_transformers()
|
| 149 |
+
|
| 150 |
+
def unregister_transformer(self, transformer):
|
| 151 |
+
"""Unregister a transformer instance."""
|
| 152 |
+
if transformer in self._transformers:
|
| 153 |
+
self._transformers.remove(transformer)
|
| 154 |
+
|
| 155 |
+
#-------------------------------------------------------------------------
|
| 156 |
+
# API for managing checkers
|
| 157 |
+
#-------------------------------------------------------------------------
|
| 158 |
+
|
| 159 |
+
def init_checkers(self):
|
| 160 |
+
"""Create the default checkers."""
|
| 161 |
+
self._checkers = []
|
| 162 |
+
for checker in _default_checkers:
|
| 163 |
+
checker(
|
| 164 |
+
shell=self.shell, prefilter_manager=self, parent=self
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
def sort_checkers(self):
|
| 168 |
+
"""Sort the checkers by priority.
|
| 169 |
+
|
| 170 |
+
This must be called after the priority of a checker is changed.
|
| 171 |
+
The :meth:`register_checker` method calls this automatically.
|
| 172 |
+
"""
|
| 173 |
+
self._checkers.sort(key=lambda x: x.priority)
|
| 174 |
+
|
| 175 |
+
@property
|
| 176 |
+
def checkers(self):
|
| 177 |
+
"""Return a list of checkers, sorted by priority."""
|
| 178 |
+
return self._checkers
|
| 179 |
+
|
| 180 |
+
def register_checker(self, checker):
|
| 181 |
+
"""Register a checker instance."""
|
| 182 |
+
if checker not in self._checkers:
|
| 183 |
+
self._checkers.append(checker)
|
| 184 |
+
self.sort_checkers()
|
| 185 |
+
|
| 186 |
+
def unregister_checker(self, checker):
|
| 187 |
+
"""Unregister a checker instance."""
|
| 188 |
+
if checker in self._checkers:
|
| 189 |
+
self._checkers.remove(checker)
|
| 190 |
+
|
| 191 |
+
#-------------------------------------------------------------------------
|
| 192 |
+
# API for managing handlers
|
| 193 |
+
#-------------------------------------------------------------------------
|
| 194 |
+
|
| 195 |
+
def init_handlers(self):
|
| 196 |
+
"""Create the default handlers."""
|
| 197 |
+
self._handlers = {}
|
| 198 |
+
self._esc_handlers = {}
|
| 199 |
+
for handler in _default_handlers:
|
| 200 |
+
handler(
|
| 201 |
+
shell=self.shell, prefilter_manager=self, parent=self
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
@property
|
| 205 |
+
def handlers(self):
|
| 206 |
+
"""Return a dict of all the handlers."""
|
| 207 |
+
return self._handlers
|
| 208 |
+
|
| 209 |
+
def register_handler(self, name, handler, esc_strings):
|
| 210 |
+
"""Register a handler instance by name with esc_strings."""
|
| 211 |
+
self._handlers[name] = handler
|
| 212 |
+
for esc_str in esc_strings:
|
| 213 |
+
self._esc_handlers[esc_str] = handler
|
| 214 |
+
|
| 215 |
+
def unregister_handler(self, name, handler, esc_strings):
|
| 216 |
+
"""Unregister a handler instance by name with esc_strings."""
|
| 217 |
+
try:
|
| 218 |
+
del self._handlers[name]
|
| 219 |
+
except KeyError:
|
| 220 |
+
pass
|
| 221 |
+
for esc_str in esc_strings:
|
| 222 |
+
h = self._esc_handlers.get(esc_str)
|
| 223 |
+
if h is handler:
|
| 224 |
+
del self._esc_handlers[esc_str]
|
| 225 |
+
|
| 226 |
+
def get_handler_by_name(self, name):
|
| 227 |
+
"""Get a handler by its name."""
|
| 228 |
+
return self._handlers.get(name)
|
| 229 |
+
|
| 230 |
+
def get_handler_by_esc(self, esc_str):
|
| 231 |
+
"""Get a handler by its escape string."""
|
| 232 |
+
return self._esc_handlers.get(esc_str)
|
| 233 |
+
|
| 234 |
+
#-------------------------------------------------------------------------
|
| 235 |
+
# Main prefiltering API
|
| 236 |
+
#-------------------------------------------------------------------------
|
| 237 |
+
|
| 238 |
+
def prefilter_line_info(self, line_info):
|
| 239 |
+
"""Prefilter a line that has been converted to a LineInfo object.
|
| 240 |
+
|
| 241 |
+
This implements the checker/handler part of the prefilter pipe.
|
| 242 |
+
"""
|
| 243 |
+
# print("prefilter_line_info: ", line_info)
|
| 244 |
+
handler = self.find_handler(line_info)
|
| 245 |
+
return handler.handle(line_info)
|
| 246 |
+
|
| 247 |
+
def find_handler(self, line_info):
|
| 248 |
+
"""Find a handler for the line_info by trying checkers."""
|
| 249 |
+
for checker in self.checkers:
|
| 250 |
+
if checker.enabled:
|
| 251 |
+
handler = checker.check(line_info)
|
| 252 |
+
if handler:
|
| 253 |
+
return handler
|
| 254 |
+
return self.get_handler_by_name('normal')
|
| 255 |
+
|
| 256 |
+
def transform_line(self, line, continue_prompt):
|
| 257 |
+
"""Calls the enabled transformers in order of increasing priority."""
|
| 258 |
+
for transformer in self.transformers:
|
| 259 |
+
if transformer.enabled:
|
| 260 |
+
line = transformer.transform(line, continue_prompt)
|
| 261 |
+
return line
|
| 262 |
+
|
| 263 |
+
def prefilter_line(self, line, continue_prompt=False):
|
| 264 |
+
"""Prefilter a single input line as text.
|
| 265 |
+
|
| 266 |
+
This method prefilters a single line of text by calling the
|
| 267 |
+
transformers and then the checkers/handlers.
|
| 268 |
+
"""
|
| 269 |
+
|
| 270 |
+
# print("prefilter_line: ", line, continue_prompt)
|
| 271 |
+
# All handlers *must* return a value, even if it's blank ('').
|
| 272 |
+
|
| 273 |
+
# save the line away in case we crash, so the post-mortem handler can
|
| 274 |
+
# record it
|
| 275 |
+
self.shell._last_input_line = line
|
| 276 |
+
|
| 277 |
+
if not line:
|
| 278 |
+
# Return immediately on purely empty lines, so that if the user
|
| 279 |
+
# previously typed some whitespace that started a continuation
|
| 280 |
+
# prompt, he can break out of that loop with just an empty line.
|
| 281 |
+
# This is how the default python prompt works.
|
| 282 |
+
return ''
|
| 283 |
+
|
| 284 |
+
# At this point, we invoke our transformers.
|
| 285 |
+
if not continue_prompt or (continue_prompt and self.multi_line_specials):
|
| 286 |
+
line = self.transform_line(line, continue_prompt)
|
| 287 |
+
|
| 288 |
+
# Now we compute line_info for the checkers and handlers
|
| 289 |
+
line_info = LineInfo(line, continue_prompt)
|
| 290 |
+
|
| 291 |
+
# the input history needs to track even empty lines
|
| 292 |
+
stripped = line.strip()
|
| 293 |
+
|
| 294 |
+
normal_handler = self.get_handler_by_name('normal')
|
| 295 |
+
if not stripped:
|
| 296 |
+
return normal_handler.handle(line_info)
|
| 297 |
+
|
| 298 |
+
# special handlers are only allowed for single line statements
|
| 299 |
+
if continue_prompt and not self.multi_line_specials:
|
| 300 |
+
return normal_handler.handle(line_info)
|
| 301 |
+
|
| 302 |
+
prefiltered = self.prefilter_line_info(line_info)
|
| 303 |
+
# print("prefiltered line: %r" % prefiltered)
|
| 304 |
+
return prefiltered
|
| 305 |
+
|
| 306 |
+
def prefilter_lines(self, lines, continue_prompt=False):
|
| 307 |
+
"""Prefilter multiple input lines of text.
|
| 308 |
+
|
| 309 |
+
This is the main entry point for prefiltering multiple lines of
|
| 310 |
+
input. This simply calls :meth:`prefilter_line` for each line of
|
| 311 |
+
input.
|
| 312 |
+
|
| 313 |
+
This covers cases where there are multiple lines in the user entry,
|
| 314 |
+
which is the case when the user goes back to a multiline history
|
| 315 |
+
entry and presses enter.
|
| 316 |
+
"""
|
| 317 |
+
llines = lines.rstrip('\n').split('\n')
|
| 318 |
+
# We can get multiple lines in one shot, where multiline input 'blends'
|
| 319 |
+
# into one line, in cases like recalling from the readline history
|
| 320 |
+
# buffer. We need to make sure that in such cases, we correctly
|
| 321 |
+
# communicate downstream which line is first and which are continuation
|
| 322 |
+
# ones.
|
| 323 |
+
if len(llines) > 1:
|
| 324 |
+
out = '\n'.join([self.prefilter_line(line, lnum>0)
|
| 325 |
+
for lnum, line in enumerate(llines) ])
|
| 326 |
+
else:
|
| 327 |
+
out = self.prefilter_line(llines[0], continue_prompt)
|
| 328 |
+
|
| 329 |
+
return out
|
| 330 |
+
|
| 331 |
+
#-----------------------------------------------------------------------------
|
| 332 |
+
# Prefilter transformers
|
| 333 |
+
#-----------------------------------------------------------------------------
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
class PrefilterTransformer(Configurable):
|
| 337 |
+
"""Transform a line of user input."""
|
| 338 |
+
|
| 339 |
+
priority = Integer(100).tag(config=True)
|
| 340 |
+
# Transformers don't currently use shell or prefilter_manager, but as we
|
| 341 |
+
# move away from checkers and handlers, they will need them.
|
| 342 |
+
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
|
| 343 |
+
prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
|
| 344 |
+
enabled = Bool(True).tag(config=True)
|
| 345 |
+
|
| 346 |
+
def __init__(self, shell=None, prefilter_manager=None, **kwargs):
|
| 347 |
+
super(PrefilterTransformer, self).__init__(
|
| 348 |
+
shell=shell, prefilter_manager=prefilter_manager, **kwargs
|
| 349 |
+
)
|
| 350 |
+
self.prefilter_manager.register_transformer(self)
|
| 351 |
+
|
| 352 |
+
def transform(self, line, continue_prompt):
|
| 353 |
+
"""Transform a line, returning the new one."""
|
| 354 |
+
return None
|
| 355 |
+
|
| 356 |
+
def __repr__(self):
|
| 357 |
+
return "<%s(priority=%r, enabled=%r)>" % (
|
| 358 |
+
self.__class__.__name__, self.priority, self.enabled)
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
#-----------------------------------------------------------------------------
|
| 362 |
+
# Prefilter checkers
|
| 363 |
+
#-----------------------------------------------------------------------------
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
class PrefilterChecker(Configurable):
|
| 367 |
+
"""Inspect an input line and return a handler for that line."""
|
| 368 |
+
|
| 369 |
+
priority = Integer(100).tag(config=True)
|
| 370 |
+
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
|
| 371 |
+
prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
|
| 372 |
+
enabled = Bool(True).tag(config=True)
|
| 373 |
+
|
| 374 |
+
def __init__(self, shell=None, prefilter_manager=None, **kwargs):
|
| 375 |
+
super(PrefilterChecker, self).__init__(
|
| 376 |
+
shell=shell, prefilter_manager=prefilter_manager, **kwargs
|
| 377 |
+
)
|
| 378 |
+
self.prefilter_manager.register_checker(self)
|
| 379 |
+
|
| 380 |
+
def check(self, line_info):
|
| 381 |
+
"""Inspect line_info and return a handler instance or None."""
|
| 382 |
+
return None
|
| 383 |
+
|
| 384 |
+
def __repr__(self):
|
| 385 |
+
return "<%s(priority=%r, enabled=%r)>" % (
|
| 386 |
+
self.__class__.__name__, self.priority, self.enabled)
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
class EmacsChecker(PrefilterChecker):
|
| 390 |
+
|
| 391 |
+
priority = Integer(100).tag(config=True)
|
| 392 |
+
enabled = Bool(False).tag(config=True)
|
| 393 |
+
|
| 394 |
+
def check(self, line_info):
|
| 395 |
+
"Emacs ipython-mode tags certain input lines."
|
| 396 |
+
if line_info.line.endswith('# PYTHON-MODE'):
|
| 397 |
+
return self.prefilter_manager.get_handler_by_name('emacs')
|
| 398 |
+
else:
|
| 399 |
+
return None
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
class MacroChecker(PrefilterChecker):
|
| 403 |
+
|
| 404 |
+
priority = Integer(250).tag(config=True)
|
| 405 |
+
|
| 406 |
+
def check(self, line_info):
|
| 407 |
+
obj = self.shell.user_ns.get(line_info.ifun)
|
| 408 |
+
if isinstance(obj, Macro):
|
| 409 |
+
return self.prefilter_manager.get_handler_by_name('macro')
|
| 410 |
+
else:
|
| 411 |
+
return None
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
class IPyAutocallChecker(PrefilterChecker):
|
| 415 |
+
|
| 416 |
+
priority = Integer(300).tag(config=True)
|
| 417 |
+
|
| 418 |
+
def check(self, line_info):
|
| 419 |
+
"Instances of IPyAutocall in user_ns get autocalled immediately"
|
| 420 |
+
obj = self.shell.user_ns.get(line_info.ifun, None)
|
| 421 |
+
if isinstance(obj, IPyAutocall):
|
| 422 |
+
obj.set_ip(self.shell)
|
| 423 |
+
return self.prefilter_manager.get_handler_by_name('auto')
|
| 424 |
+
else:
|
| 425 |
+
return None
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
class AssignmentChecker(PrefilterChecker):
|
| 429 |
+
|
| 430 |
+
priority = Integer(600).tag(config=True)
|
| 431 |
+
|
| 432 |
+
def check(self, line_info):
|
| 433 |
+
"""Check to see if user is assigning to a var for the first time, in
|
| 434 |
+
which case we want to avoid any sort of automagic / autocall games.
|
| 435 |
+
|
| 436 |
+
This allows users to assign to either alias or magic names true python
|
| 437 |
+
variables (the magic/alias systems always take second seat to true
|
| 438 |
+
python code). E.g. ls='hi', or ls,that=1,2"""
|
| 439 |
+
if line_info.the_rest:
|
| 440 |
+
if line_info.the_rest[0] in '=,':
|
| 441 |
+
return self.prefilter_manager.get_handler_by_name('normal')
|
| 442 |
+
else:
|
| 443 |
+
return None
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
class AutoMagicChecker(PrefilterChecker):
|
| 447 |
+
|
| 448 |
+
priority = Integer(700).tag(config=True)
|
| 449 |
+
|
| 450 |
+
def check(self, line_info):
|
| 451 |
+
"""If the ifun is magic, and automagic is on, run it. Note: normal,
|
| 452 |
+
non-auto magic would already have been triggered via '%' in
|
| 453 |
+
check_esc_chars. This just checks for automagic. Also, before
|
| 454 |
+
triggering the magic handler, make sure that there is nothing in the
|
| 455 |
+
user namespace which could shadow it."""
|
| 456 |
+
if not self.shell.automagic or not self.shell.find_magic(line_info.ifun):
|
| 457 |
+
return None
|
| 458 |
+
|
| 459 |
+
# We have a likely magic method. Make sure we should actually call it.
|
| 460 |
+
if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials:
|
| 461 |
+
return None
|
| 462 |
+
|
| 463 |
+
head = line_info.ifun.split('.',1)[0]
|
| 464 |
+
if is_shadowed(head, self.shell):
|
| 465 |
+
return None
|
| 466 |
+
|
| 467 |
+
return self.prefilter_manager.get_handler_by_name('magic')
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
class PythonOpsChecker(PrefilterChecker):
|
| 471 |
+
|
| 472 |
+
priority = Integer(900).tag(config=True)
|
| 473 |
+
|
| 474 |
+
def check(self, line_info):
|
| 475 |
+
"""If the 'rest' of the line begins with a function call or pretty much
|
| 476 |
+
any python operator, we should simply execute the line (regardless of
|
| 477 |
+
whether or not there's a possible autocall expansion). This avoids
|
| 478 |
+
spurious (and very confusing) geattr() accesses."""
|
| 479 |
+
if line_info.the_rest and line_info.the_rest[0] in "!=()<>,+*/%^&|":
|
| 480 |
+
return self.prefilter_manager.get_handler_by_name("normal")
|
| 481 |
+
else:
|
| 482 |
+
return None
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
class AutocallChecker(PrefilterChecker):
|
| 486 |
+
|
| 487 |
+
priority = Integer(1000).tag(config=True)
|
| 488 |
+
|
| 489 |
+
function_name_regexp = CRegExp(re_fun_name,
|
| 490 |
+
help="RegExp to identify potential function names."
|
| 491 |
+
).tag(config=True)
|
| 492 |
+
exclude_regexp = CRegExp(re_exclude_auto,
|
| 493 |
+
help="RegExp to exclude strings with this start from autocalling."
|
| 494 |
+
).tag(config=True)
|
| 495 |
+
|
| 496 |
+
def check(self, line_info):
|
| 497 |
+
"Check if the initial word/function is callable and autocall is on."
|
| 498 |
+
if not self.shell.autocall:
|
| 499 |
+
return None
|
| 500 |
+
|
| 501 |
+
oinfo = self.shell._ofind(line_info.ifun) # This can mutate state via getattr
|
| 502 |
+
if not oinfo.found:
|
| 503 |
+
return None
|
| 504 |
+
|
| 505 |
+
ignored_funs = ['b', 'f', 'r', 'u', 'br', 'rb', 'fr', 'rf']
|
| 506 |
+
ifun = line_info.ifun
|
| 507 |
+
line = line_info.line
|
| 508 |
+
if ifun.lower() in ignored_funs and (line.startswith(ifun + "'") or line.startswith(ifun + '"')):
|
| 509 |
+
return None
|
| 510 |
+
|
| 511 |
+
if (
|
| 512 |
+
callable(oinfo.obj)
|
| 513 |
+
and (not self.exclude_regexp.match(line_info.the_rest))
|
| 514 |
+
and self.function_name_regexp.match(line_info.ifun)
|
| 515 |
+
and (
|
| 516 |
+
line_info.raw_the_rest.startswith(" ")
|
| 517 |
+
or not line_info.raw_the_rest.strip()
|
| 518 |
+
)
|
| 519 |
+
):
|
| 520 |
+
return self.prefilter_manager.get_handler_by_name("auto")
|
| 521 |
+
else:
|
| 522 |
+
return None
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
#-----------------------------------------------------------------------------
|
| 526 |
+
# Prefilter handlers
|
| 527 |
+
#-----------------------------------------------------------------------------
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
class PrefilterHandler(Configurable):
|
| 531 |
+
handler_name = Unicode("normal")
|
| 532 |
+
esc_strings: List = List([])
|
| 533 |
+
shell = Instance(
|
| 534 |
+
"IPython.core.interactiveshell.InteractiveShellABC", allow_none=True
|
| 535 |
+
)
|
| 536 |
+
prefilter_manager = Instance(
|
| 537 |
+
"IPython.core.prefilter.PrefilterManager", allow_none=True
|
| 538 |
+
)
|
| 539 |
+
|
| 540 |
+
def __init__(self, shell=None, prefilter_manager=None, **kwargs):
|
| 541 |
+
super(PrefilterHandler, self).__init__(
|
| 542 |
+
shell=shell, prefilter_manager=prefilter_manager, **kwargs
|
| 543 |
+
)
|
| 544 |
+
self.prefilter_manager.register_handler(
|
| 545 |
+
self.handler_name,
|
| 546 |
+
self,
|
| 547 |
+
self.esc_strings
|
| 548 |
+
)
|
| 549 |
+
|
| 550 |
+
def handle(self, line_info):
|
| 551 |
+
# print("normal: ", line_info)
|
| 552 |
+
"""Handle normal input lines. Use as a template for handlers."""
|
| 553 |
+
|
| 554 |
+
# With autoindent on, we need some way to exit the input loop, and I
|
| 555 |
+
# don't want to force the user to have to backspace all the way to
|
| 556 |
+
# clear the line. The rule will be in this case, that either two
|
| 557 |
+
# lines of pure whitespace in a row, or a line of pure whitespace but
|
| 558 |
+
# of a size different to the indent level, will exit the input loop.
|
| 559 |
+
line = line_info.line
|
| 560 |
+
continue_prompt = line_info.continue_prompt
|
| 561 |
+
|
| 562 |
+
if (continue_prompt and
|
| 563 |
+
self.shell.autoindent and
|
| 564 |
+
line.isspace() and
|
| 565 |
+
0 < abs(len(line) - self.shell.indent_current_nsp) <= 2):
|
| 566 |
+
line = ''
|
| 567 |
+
|
| 568 |
+
return line
|
| 569 |
+
|
| 570 |
+
def __str__(self):
|
| 571 |
+
return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
class MacroHandler(PrefilterHandler):
|
| 575 |
+
handler_name = Unicode("macro")
|
| 576 |
+
|
| 577 |
+
def handle(self, line_info):
|
| 578 |
+
obj = self.shell.user_ns.get(line_info.ifun)
|
| 579 |
+
pre_space = line_info.pre_whitespace
|
| 580 |
+
line_sep = "\n" + pre_space
|
| 581 |
+
return pre_space + line_sep.join(obj.value.splitlines())
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
class MagicHandler(PrefilterHandler):
|
| 585 |
+
|
| 586 |
+
handler_name = Unicode('magic')
|
| 587 |
+
esc_strings = List([ESC_MAGIC])
|
| 588 |
+
|
| 589 |
+
def handle(self, line_info):
|
| 590 |
+
"""Execute magic functions."""
|
| 591 |
+
ifun = line_info.ifun
|
| 592 |
+
the_rest = line_info.the_rest
|
| 593 |
+
#Prepare arguments for get_ipython().run_line_magic(magic_name, magic_args)
|
| 594 |
+
t_arg_s = ifun + " " + the_rest
|
| 595 |
+
t_magic_name, _, t_magic_arg_s = t_arg_s.partition(' ')
|
| 596 |
+
t_magic_name = t_magic_name.lstrip(ESC_MAGIC)
|
| 597 |
+
cmd = '%sget_ipython().run_line_magic(%r, %r)' % (line_info.pre_whitespace, t_magic_name, t_magic_arg_s)
|
| 598 |
+
return cmd
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
class AutoHandler(PrefilterHandler):
|
| 602 |
+
|
| 603 |
+
handler_name = Unicode('auto')
|
| 604 |
+
esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
|
| 605 |
+
|
| 606 |
+
def handle(self, line_info):
|
| 607 |
+
"""Handle lines which can be auto-executed, quoting if requested."""
|
| 608 |
+
line = line_info.line
|
| 609 |
+
ifun = line_info.ifun
|
| 610 |
+
the_rest = line_info.the_rest
|
| 611 |
+
esc = line_info.esc
|
| 612 |
+
continue_prompt = line_info.continue_prompt
|
| 613 |
+
obj = self.shell._ofind(line_info.ifun).obj
|
| 614 |
+
|
| 615 |
+
# This should only be active for single-line input!
|
| 616 |
+
if continue_prompt:
|
| 617 |
+
return line
|
| 618 |
+
|
| 619 |
+
force_auto = isinstance(obj, IPyAutocall)
|
| 620 |
+
|
| 621 |
+
# User objects sometimes raise exceptions on attribute access other
|
| 622 |
+
# than AttributeError (we've seen it in the past), so it's safest to be
|
| 623 |
+
# ultra-conservative here and catch all.
|
| 624 |
+
try:
|
| 625 |
+
auto_rewrite = obj.rewrite
|
| 626 |
+
except Exception:
|
| 627 |
+
auto_rewrite = True
|
| 628 |
+
|
| 629 |
+
if esc == ESC_QUOTE:
|
| 630 |
+
# Auto-quote splitting on whitespace
|
| 631 |
+
newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
|
| 632 |
+
elif esc == ESC_QUOTE2:
|
| 633 |
+
# Auto-quote whole string
|
| 634 |
+
newcmd = '%s("%s")' % (ifun,the_rest)
|
| 635 |
+
elif esc == ESC_PAREN:
|
| 636 |
+
newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
|
| 637 |
+
else:
|
| 638 |
+
# Auto-paren.
|
| 639 |
+
if force_auto:
|
| 640 |
+
# Don't rewrite if it is already a call.
|
| 641 |
+
do_rewrite = not the_rest.startswith('(')
|
| 642 |
+
else:
|
| 643 |
+
if not the_rest:
|
| 644 |
+
# We only apply it to argument-less calls if the autocall
|
| 645 |
+
# parameter is set to 2.
|
| 646 |
+
do_rewrite = (self.shell.autocall >= 2)
|
| 647 |
+
elif the_rest.startswith('[') and hasattr(obj, '__getitem__'):
|
| 648 |
+
# Don't autocall in this case: item access for an object
|
| 649 |
+
# which is BOTH callable and implements __getitem__.
|
| 650 |
+
do_rewrite = False
|
| 651 |
+
else:
|
| 652 |
+
do_rewrite = True
|
| 653 |
+
|
| 654 |
+
# Figure out the rewritten command
|
| 655 |
+
if do_rewrite:
|
| 656 |
+
if the_rest.endswith(';'):
|
| 657 |
+
newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
|
| 658 |
+
else:
|
| 659 |
+
newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
|
| 660 |
+
else:
|
| 661 |
+
normal_handler = self.prefilter_manager.get_handler_by_name('normal')
|
| 662 |
+
return normal_handler.handle(line_info)
|
| 663 |
+
|
| 664 |
+
# Display the rewritten call
|
| 665 |
+
if auto_rewrite:
|
| 666 |
+
self.shell.auto_rewrite_input(newcmd)
|
| 667 |
+
|
| 668 |
+
return newcmd
|
| 669 |
+
|
| 670 |
+
|
| 671 |
+
class EmacsHandler(PrefilterHandler):
|
| 672 |
+
|
| 673 |
+
handler_name = Unicode('emacs')
|
| 674 |
+
esc_strings = List([])
|
| 675 |
+
|
| 676 |
+
def handle(self, line_info):
|
| 677 |
+
"""Handle input lines marked by python-mode."""
|
| 678 |
+
|
| 679 |
+
# Currently, nothing is done. Later more functionality can be added
|
| 680 |
+
# here if needed.
|
| 681 |
+
|
| 682 |
+
# The input cache shouldn't be updated
|
| 683 |
+
return line_info.line
|
| 684 |
+
|
| 685 |
+
|
| 686 |
+
#-----------------------------------------------------------------------------
|
| 687 |
+
# Defaults
|
| 688 |
+
#-----------------------------------------------------------------------------
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
_default_checkers = [
|
| 692 |
+
EmacsChecker,
|
| 693 |
+
MacroChecker,
|
| 694 |
+
IPyAutocallChecker,
|
| 695 |
+
AssignmentChecker,
|
| 696 |
+
AutoMagicChecker,
|
| 697 |
+
PythonOpsChecker,
|
| 698 |
+
AutocallChecker
|
| 699 |
+
]
|
| 700 |
+
|
| 701 |
+
_default_handlers = [
|
| 702 |
+
PrefilterHandler,
|
| 703 |
+
MacroHandler,
|
| 704 |
+
MagicHandler,
|
| 705 |
+
AutoHandler,
|
| 706 |
+
EmacsHandler
|
| 707 |
+
]
|
lib/python3.12/site-packages/IPython/core/profileapp.py
ADDED
|
@@ -0,0 +1,315 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# encoding: utf-8
|
| 2 |
+
"""
|
| 3 |
+
An application for managing IPython profiles.
|
| 4 |
+
|
| 5 |
+
To be invoked as the `ipython profile` subcommand.
|
| 6 |
+
|
| 7 |
+
Authors:
|
| 8 |
+
|
| 9 |
+
* Min RK
|
| 10 |
+
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
#-----------------------------------------------------------------------------
|
| 14 |
+
# Copyright (C) 2008 The IPython Development Team
|
| 15 |
+
#
|
| 16 |
+
# Distributed under the terms of the BSD License. The full license is in
|
| 17 |
+
# the file COPYING, distributed as part of this software.
|
| 18 |
+
#-----------------------------------------------------------------------------
|
| 19 |
+
|
| 20 |
+
#-----------------------------------------------------------------------------
|
| 21 |
+
# Imports
|
| 22 |
+
#-----------------------------------------------------------------------------
|
| 23 |
+
|
| 24 |
+
import os
|
| 25 |
+
|
| 26 |
+
from traitlets.config.application import Application
|
| 27 |
+
from IPython.core.application import (
|
| 28 |
+
BaseIPythonApplication, base_flags
|
| 29 |
+
)
|
| 30 |
+
from IPython.core.profiledir import ProfileDir
|
| 31 |
+
from IPython.utils.importstring import import_item
|
| 32 |
+
from IPython.paths import get_ipython_dir, get_ipython_package_dir
|
| 33 |
+
from traitlets import Unicode, Bool, Dict, observe
|
| 34 |
+
|
| 35 |
+
#-----------------------------------------------------------------------------
|
| 36 |
+
# Constants
|
| 37 |
+
#-----------------------------------------------------------------------------
|
| 38 |
+
|
| 39 |
+
create_help = """Create an IPython profile by name
|
| 40 |
+
|
| 41 |
+
Create an ipython profile directory by its name or
|
| 42 |
+
profile directory path. Profile directories contain
|
| 43 |
+
configuration, log and security related files and are named
|
| 44 |
+
using the convention 'profile_<name>'. By default they are
|
| 45 |
+
located in your ipython directory. Once created, you will
|
| 46 |
+
can edit the configuration files in the profile
|
| 47 |
+
directory to configure IPython. Most users will create a
|
| 48 |
+
profile directory by name,
|
| 49 |
+
`ipython profile create myprofile`, which will put the directory
|
| 50 |
+
in `<ipython_dir>/profile_myprofile`.
|
| 51 |
+
"""
|
| 52 |
+
list_help = """List available IPython profiles
|
| 53 |
+
|
| 54 |
+
List all available profiles, by profile location, that can
|
| 55 |
+
be found in the current working directly or in the ipython
|
| 56 |
+
directory. Profile directories are named using the convention
|
| 57 |
+
'profile_<profile>'.
|
| 58 |
+
"""
|
| 59 |
+
profile_help = """Manage IPython profiles
|
| 60 |
+
|
| 61 |
+
Profile directories contain
|
| 62 |
+
configuration, log and security related files and are named
|
| 63 |
+
using the convention 'profile_<name>'. By default they are
|
| 64 |
+
located in your ipython directory. You can create profiles
|
| 65 |
+
with `ipython profile create <name>`, or see the profiles you
|
| 66 |
+
already have with `ipython profile list`
|
| 67 |
+
|
| 68 |
+
To get started configuring IPython, simply do:
|
| 69 |
+
|
| 70 |
+
$> ipython profile create
|
| 71 |
+
|
| 72 |
+
and IPython will create the default profile in <ipython_dir>/profile_default,
|
| 73 |
+
where you can edit ipython_config.py to start configuring IPython.
|
| 74 |
+
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
_list_examples = "ipython profile list # list all profiles"
|
| 78 |
+
|
| 79 |
+
_create_examples = """
|
| 80 |
+
ipython profile create foo # create profile foo w/ default config files
|
| 81 |
+
ipython profile create foo --reset # restage default config files over current
|
| 82 |
+
ipython profile create foo --parallel # also stage parallel config files
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
_main_examples = """
|
| 86 |
+
ipython profile create -h # show the help string for the create subcommand
|
| 87 |
+
ipython profile list -h # show the help string for the list subcommand
|
| 88 |
+
|
| 89 |
+
ipython locate profile foo # print the path to the directory for profile 'foo'
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
#-----------------------------------------------------------------------------
|
| 93 |
+
# Profile Application Class (for `ipython profile` subcommand)
|
| 94 |
+
#-----------------------------------------------------------------------------
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def list_profiles_in(path):
|
| 98 |
+
"""list profiles in a given root directory"""
|
| 99 |
+
profiles = []
|
| 100 |
+
|
| 101 |
+
# for python 3.6+ rewrite to: with os.scandir(path) as dirlist:
|
| 102 |
+
files = os.scandir(path)
|
| 103 |
+
for f in files:
|
| 104 |
+
if f.is_dir() and f.name.startswith('profile_'):
|
| 105 |
+
profiles.append(f.name.split('_', 1)[-1])
|
| 106 |
+
return profiles
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def list_bundled_profiles():
|
| 110 |
+
"""list profiles that are bundled with IPython."""
|
| 111 |
+
path = os.path.join(get_ipython_package_dir(), u'core', u'profile')
|
| 112 |
+
profiles = []
|
| 113 |
+
|
| 114 |
+
# for python 3.6+ rewrite to: with os.scandir(path) as dirlist:
|
| 115 |
+
files = os.scandir(path)
|
| 116 |
+
for profile in files:
|
| 117 |
+
if profile.is_dir() and profile.name != "__pycache__":
|
| 118 |
+
profiles.append(profile.name)
|
| 119 |
+
return profiles
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class ProfileLocate(BaseIPythonApplication):
|
| 123 |
+
description = """print the path to an IPython profile dir"""
|
| 124 |
+
|
| 125 |
+
def parse_command_line(self, argv=None):
|
| 126 |
+
super(ProfileLocate, self).parse_command_line(argv)
|
| 127 |
+
if self.extra_args:
|
| 128 |
+
self.profile = self.extra_args[0]
|
| 129 |
+
|
| 130 |
+
def start(self):
|
| 131 |
+
print(self.profile_dir.location)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class ProfileList(Application):
|
| 135 |
+
name = u'ipython-profile'
|
| 136 |
+
description = list_help
|
| 137 |
+
examples = _list_examples
|
| 138 |
+
|
| 139 |
+
aliases = Dict({
|
| 140 |
+
'ipython-dir' : 'ProfileList.ipython_dir',
|
| 141 |
+
'log-level' : 'Application.log_level',
|
| 142 |
+
})
|
| 143 |
+
flags = Dict(dict(
|
| 144 |
+
debug = ({'Application' : {'log_level' : 0}},
|
| 145 |
+
"Set Application.log_level to 0, maximizing log output."
|
| 146 |
+
)
|
| 147 |
+
))
|
| 148 |
+
|
| 149 |
+
ipython_dir = Unicode(get_ipython_dir(),
|
| 150 |
+
help="""
|
| 151 |
+
The name of the IPython directory. This directory is used for logging
|
| 152 |
+
configuration (through profiles), history storage, etc. The default
|
| 153 |
+
is usually $HOME/.ipython. This options can also be specified through
|
| 154 |
+
the environment variable IPYTHONDIR.
|
| 155 |
+
"""
|
| 156 |
+
).tag(config=True)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def _print_profiles(self, profiles):
|
| 160 |
+
"""print list of profiles, indented."""
|
| 161 |
+
for profile in profiles:
|
| 162 |
+
print(' %s' % profile)
|
| 163 |
+
|
| 164 |
+
def list_profile_dirs(self):
|
| 165 |
+
profiles = list_bundled_profiles()
|
| 166 |
+
if profiles:
|
| 167 |
+
print()
|
| 168 |
+
print("Available profiles in IPython:")
|
| 169 |
+
self._print_profiles(profiles)
|
| 170 |
+
print()
|
| 171 |
+
print(" The first request for a bundled profile will copy it")
|
| 172 |
+
print(" into your IPython directory (%s)," % self.ipython_dir)
|
| 173 |
+
print(" where you can customize it.")
|
| 174 |
+
|
| 175 |
+
profiles = list_profiles_in(self.ipython_dir)
|
| 176 |
+
if profiles:
|
| 177 |
+
print()
|
| 178 |
+
print("Available profiles in %s:" % self.ipython_dir)
|
| 179 |
+
self._print_profiles(profiles)
|
| 180 |
+
|
| 181 |
+
profiles = list_profiles_in(os.getcwd())
|
| 182 |
+
if profiles:
|
| 183 |
+
print()
|
| 184 |
+
print(
|
| 185 |
+
"Profiles from CWD have been removed for security reason, see CVE-2022-21699:"
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
print()
|
| 189 |
+
print("To use any of the above profiles, start IPython with:")
|
| 190 |
+
print(" ipython --profile=<name>")
|
| 191 |
+
print()
|
| 192 |
+
|
| 193 |
+
def start(self):
|
| 194 |
+
self.list_profile_dirs()
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
create_flags = {}
|
| 198 |
+
create_flags.update(base_flags)
|
| 199 |
+
# don't include '--init' flag, which implies running profile create in other apps
|
| 200 |
+
create_flags.pop('init')
|
| 201 |
+
create_flags['reset'] = ({'ProfileCreate': {'overwrite' : True}},
|
| 202 |
+
"reset config files in this profile to the defaults.")
|
| 203 |
+
create_flags['parallel'] = ({'ProfileCreate': {'parallel' : True}},
|
| 204 |
+
"Include the config files for parallel "
|
| 205 |
+
"computing apps (ipengine, ipcontroller, etc.)")
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
class ProfileCreate(BaseIPythonApplication):
|
| 209 |
+
name = u'ipython-profile'
|
| 210 |
+
description = create_help
|
| 211 |
+
examples = _create_examples
|
| 212 |
+
auto_create = Bool(True).tag(config=True)
|
| 213 |
+
def _log_format_default(self):
|
| 214 |
+
return "[%(name)s] %(message)s"
|
| 215 |
+
|
| 216 |
+
def _copy_config_files_default(self):
|
| 217 |
+
return True
|
| 218 |
+
|
| 219 |
+
parallel = Bool(False,
|
| 220 |
+
help="whether to include parallel computing config files"
|
| 221 |
+
).tag(config=True)
|
| 222 |
+
|
| 223 |
+
@observe('parallel')
|
| 224 |
+
def _parallel_changed(self, change):
|
| 225 |
+
parallel_files = [ 'ipcontroller_config.py',
|
| 226 |
+
'ipengine_config.py',
|
| 227 |
+
'ipcluster_config.py'
|
| 228 |
+
]
|
| 229 |
+
if change['new']:
|
| 230 |
+
for cf in parallel_files:
|
| 231 |
+
self.config_files.append(cf)
|
| 232 |
+
else:
|
| 233 |
+
for cf in parallel_files:
|
| 234 |
+
if cf in self.config_files:
|
| 235 |
+
self.config_files.remove(cf)
|
| 236 |
+
|
| 237 |
+
def parse_command_line(self, argv):
|
| 238 |
+
super(ProfileCreate, self).parse_command_line(argv)
|
| 239 |
+
# accept positional arg as profile name
|
| 240 |
+
if self.extra_args:
|
| 241 |
+
self.profile = self.extra_args[0]
|
| 242 |
+
|
| 243 |
+
flags = Dict(create_flags)
|
| 244 |
+
|
| 245 |
+
classes = [ProfileDir]
|
| 246 |
+
|
| 247 |
+
def _import_app(self, app_path):
|
| 248 |
+
"""import an app class"""
|
| 249 |
+
app = None
|
| 250 |
+
name = app_path.rsplit('.', 1)[-1]
|
| 251 |
+
try:
|
| 252 |
+
app = import_item(app_path)
|
| 253 |
+
except ImportError:
|
| 254 |
+
self.log.info("Couldn't import %s, config file will be excluded", name)
|
| 255 |
+
except Exception:
|
| 256 |
+
self.log.warning('Unexpected error importing %s', name, exc_info=True)
|
| 257 |
+
return app
|
| 258 |
+
|
| 259 |
+
def init_config_files(self):
|
| 260 |
+
super(ProfileCreate, self).init_config_files()
|
| 261 |
+
# use local imports, since these classes may import from here
|
| 262 |
+
from IPython.terminal.ipapp import TerminalIPythonApp
|
| 263 |
+
apps = [TerminalIPythonApp]
|
| 264 |
+
for app_path in (
|
| 265 |
+
'ipykernel.kernelapp.IPKernelApp',
|
| 266 |
+
):
|
| 267 |
+
app = self._import_app(app_path)
|
| 268 |
+
if app is not None:
|
| 269 |
+
apps.append(app)
|
| 270 |
+
if self.parallel:
|
| 271 |
+
from ipyparallel.apps.ipcontrollerapp import IPControllerApp
|
| 272 |
+
from ipyparallel.apps.ipengineapp import IPEngineApp
|
| 273 |
+
from ipyparallel.apps.ipclusterapp import IPClusterStart
|
| 274 |
+
apps.extend([
|
| 275 |
+
IPControllerApp,
|
| 276 |
+
IPEngineApp,
|
| 277 |
+
IPClusterStart,
|
| 278 |
+
])
|
| 279 |
+
for App in apps:
|
| 280 |
+
app = App()
|
| 281 |
+
app.config.update(self.config)
|
| 282 |
+
app.log = self.log
|
| 283 |
+
app.overwrite = self.overwrite
|
| 284 |
+
app.copy_config_files=True
|
| 285 |
+
app.ipython_dir=self.ipython_dir
|
| 286 |
+
app.profile_dir=self.profile_dir
|
| 287 |
+
app.init_config_files()
|
| 288 |
+
|
| 289 |
+
def stage_default_config_file(self):
|
| 290 |
+
pass
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
class ProfileApp(Application):
|
| 294 |
+
name = u'ipython profile'
|
| 295 |
+
description = profile_help
|
| 296 |
+
examples = _main_examples
|
| 297 |
+
|
| 298 |
+
subcommands = Dict(dict(
|
| 299 |
+
create = (ProfileCreate, ProfileCreate.description.splitlines()[0]),
|
| 300 |
+
list = (ProfileList, ProfileList.description.splitlines()[0]),
|
| 301 |
+
locate = (ProfileLocate, ProfileLocate.description.splitlines()[0]),
|
| 302 |
+
))
|
| 303 |
+
|
| 304 |
+
def start(self):
|
| 305 |
+
if self.subapp is None:
|
| 306 |
+
print(
|
| 307 |
+
"No subcommand specified. Must specify one of: "
|
| 308 |
+
+ ", ".join(map(repr, self.subcommands))
|
| 309 |
+
+ ".\n"
|
| 310 |
+
)
|
| 311 |
+
self.print_description()
|
| 312 |
+
self.print_subcommands()
|
| 313 |
+
self.exit(1)
|
| 314 |
+
else:
|
| 315 |
+
return self.subapp.start()
|
lib/python3.12/site-packages/IPython/core/profiledir.py
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# encoding: utf-8
|
| 2 |
+
"""An object for managing IPython profile directories."""
|
| 3 |
+
|
| 4 |
+
# Copyright (c) IPython Development Team.
|
| 5 |
+
# Distributed under the terms of the Modified BSD License.
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import shutil
|
| 9 |
+
import errno
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
from traitlets.config.configurable import LoggingConfigurable
|
| 13 |
+
from ..paths import get_ipython_package_dir
|
| 14 |
+
from ..utils.path import expand_path, ensure_dir_exists
|
| 15 |
+
from traitlets import Unicode, Bool, observe
|
| 16 |
+
|
| 17 |
+
from typing import Optional
|
| 18 |
+
|
| 19 |
+
#-----------------------------------------------------------------------------
|
| 20 |
+
# Module errors
|
| 21 |
+
#-----------------------------------------------------------------------------
|
| 22 |
+
|
| 23 |
+
class ProfileDirError(Exception):
|
| 24 |
+
pass
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
#-----------------------------------------------------------------------------
|
| 28 |
+
# Class for managing profile directories
|
| 29 |
+
#-----------------------------------------------------------------------------
|
| 30 |
+
|
| 31 |
+
class ProfileDir(LoggingConfigurable):
|
| 32 |
+
"""An object to manage the profile directory and its resources.
|
| 33 |
+
|
| 34 |
+
The profile directory is used by all IPython applications, to manage
|
| 35 |
+
configuration, logging and security.
|
| 36 |
+
|
| 37 |
+
This object knows how to find, create and manage these directories. This
|
| 38 |
+
should be used by any code that wants to handle profiles.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
security_dir_name = Unicode('security')
|
| 42 |
+
log_dir_name = Unicode('log')
|
| 43 |
+
startup_dir_name = Unicode('startup')
|
| 44 |
+
pid_dir_name = Unicode('pid')
|
| 45 |
+
static_dir_name = Unicode('static')
|
| 46 |
+
security_dir = Unicode(u'')
|
| 47 |
+
log_dir = Unicode(u'')
|
| 48 |
+
startup_dir = Unicode(u'')
|
| 49 |
+
pid_dir = Unicode(u'')
|
| 50 |
+
static_dir = Unicode(u'')
|
| 51 |
+
|
| 52 |
+
location = Unicode(u'',
|
| 53 |
+
help="""Set the profile location directly. This overrides the logic used by the
|
| 54 |
+
`profile` option.""",
|
| 55 |
+
).tag(config=True)
|
| 56 |
+
|
| 57 |
+
_location_isset = Bool(False) # flag for detecting multiply set location
|
| 58 |
+
@observe('location')
|
| 59 |
+
def _location_changed(self, change):
|
| 60 |
+
if self._location_isset:
|
| 61 |
+
raise RuntimeError("Cannot set profile location more than once.")
|
| 62 |
+
self._location_isset = True
|
| 63 |
+
new = change['new']
|
| 64 |
+
ensure_dir_exists(new)
|
| 65 |
+
|
| 66 |
+
# ensure config files exist:
|
| 67 |
+
self.security_dir = os.path.join(new, self.security_dir_name)
|
| 68 |
+
self.log_dir = os.path.join(new, self.log_dir_name)
|
| 69 |
+
self.startup_dir = os.path.join(new, self.startup_dir_name)
|
| 70 |
+
self.pid_dir = os.path.join(new, self.pid_dir_name)
|
| 71 |
+
self.static_dir = os.path.join(new, self.static_dir_name)
|
| 72 |
+
self.check_dirs()
|
| 73 |
+
|
| 74 |
+
def _mkdir(self, path: str, mode: Optional[int] = None) -> bool:
|
| 75 |
+
"""ensure a directory exists at a given path
|
| 76 |
+
|
| 77 |
+
This is a version of os.mkdir, with the following differences:
|
| 78 |
+
|
| 79 |
+
- returns whether the directory has been created or not.
|
| 80 |
+
- ignores EEXIST, protecting against race conditions where
|
| 81 |
+
the dir may have been created in between the check and
|
| 82 |
+
the creation
|
| 83 |
+
- sets permissions if requested and the dir already exists
|
| 84 |
+
|
| 85 |
+
Parameters
|
| 86 |
+
----------
|
| 87 |
+
path: str
|
| 88 |
+
path of the dir to create
|
| 89 |
+
mode: int
|
| 90 |
+
see `mode` of `os.mkdir`
|
| 91 |
+
|
| 92 |
+
Returns
|
| 93 |
+
-------
|
| 94 |
+
bool:
|
| 95 |
+
returns True if it created the directory, False otherwise
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
if os.path.exists(path):
|
| 99 |
+
if mode and os.stat(path).st_mode != mode:
|
| 100 |
+
try:
|
| 101 |
+
os.chmod(path, mode)
|
| 102 |
+
except OSError:
|
| 103 |
+
self.log.warning(
|
| 104 |
+
"Could not set permissions on %s",
|
| 105 |
+
path
|
| 106 |
+
)
|
| 107 |
+
return False
|
| 108 |
+
try:
|
| 109 |
+
if mode:
|
| 110 |
+
os.mkdir(path, mode)
|
| 111 |
+
else:
|
| 112 |
+
os.mkdir(path)
|
| 113 |
+
except OSError as e:
|
| 114 |
+
if e.errno == errno.EEXIST:
|
| 115 |
+
return False
|
| 116 |
+
else:
|
| 117 |
+
raise
|
| 118 |
+
|
| 119 |
+
return True
|
| 120 |
+
|
| 121 |
+
@observe('log_dir')
|
| 122 |
+
def check_log_dir(self, change=None):
|
| 123 |
+
self._mkdir(self.log_dir)
|
| 124 |
+
|
| 125 |
+
@observe('startup_dir')
|
| 126 |
+
def check_startup_dir(self, change=None):
|
| 127 |
+
if self._mkdir(self.startup_dir):
|
| 128 |
+
readme = os.path.join(self.startup_dir, "README")
|
| 129 |
+
src = os.path.join(
|
| 130 |
+
get_ipython_package_dir(), "core", "profile", "README_STARTUP"
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
if os.path.exists(src):
|
| 134 |
+
if not os.path.exists(readme):
|
| 135 |
+
shutil.copy(src, readme)
|
| 136 |
+
else:
|
| 137 |
+
self.log.warning(
|
| 138 |
+
"Could not copy README_STARTUP to startup dir. Source file %s does not exist.",
|
| 139 |
+
src,
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
@observe('security_dir')
|
| 143 |
+
def check_security_dir(self, change=None):
|
| 144 |
+
self._mkdir(self.security_dir, 0o40700)
|
| 145 |
+
|
| 146 |
+
@observe('pid_dir')
|
| 147 |
+
def check_pid_dir(self, change=None):
|
| 148 |
+
self._mkdir(self.pid_dir, 0o40700)
|
| 149 |
+
|
| 150 |
+
def check_dirs(self):
|
| 151 |
+
self.check_security_dir()
|
| 152 |
+
self.check_log_dir()
|
| 153 |
+
self.check_pid_dir()
|
| 154 |
+
self.check_startup_dir()
|
| 155 |
+
|
| 156 |
+
def copy_config_file(self, config_file: str, path: Path, overwrite=False) -> bool:
|
| 157 |
+
"""Copy a default config file into the active profile directory.
|
| 158 |
+
|
| 159 |
+
Default configuration files are kept in :mod:`IPython.core.profile`.
|
| 160 |
+
This function moves these from that location to the working profile
|
| 161 |
+
directory.
|
| 162 |
+
"""
|
| 163 |
+
dst = Path(os.path.join(self.location, config_file))
|
| 164 |
+
if dst.exists() and not overwrite:
|
| 165 |
+
return False
|
| 166 |
+
if path is None:
|
| 167 |
+
path = os.path.join(get_ipython_package_dir(), u'core', u'profile', u'default')
|
| 168 |
+
assert isinstance(path, Path)
|
| 169 |
+
src = path / config_file
|
| 170 |
+
shutil.copy(src, dst)
|
| 171 |
+
return True
|
| 172 |
+
|
| 173 |
+
@classmethod
|
| 174 |
+
def create_profile_dir(cls, profile_dir, config=None):
|
| 175 |
+
"""Create a new profile directory given a full path.
|
| 176 |
+
|
| 177 |
+
Parameters
|
| 178 |
+
----------
|
| 179 |
+
profile_dir : str
|
| 180 |
+
The full path to the profile directory. If it does exist, it will
|
| 181 |
+
be used. If not, it will be created.
|
| 182 |
+
"""
|
| 183 |
+
return cls(location=profile_dir, config=config)
|
| 184 |
+
|
| 185 |
+
@classmethod
|
| 186 |
+
def create_profile_dir_by_name(cls, path, name=u'default', config=None):
|
| 187 |
+
"""Create a profile dir by profile name and path.
|
| 188 |
+
|
| 189 |
+
Parameters
|
| 190 |
+
----------
|
| 191 |
+
path : unicode
|
| 192 |
+
The path (directory) to put the profile directory in.
|
| 193 |
+
name : unicode
|
| 194 |
+
The name of the profile. The name of the profile directory will
|
| 195 |
+
be "profile_<profile>".
|
| 196 |
+
"""
|
| 197 |
+
if not os.path.isdir(path):
|
| 198 |
+
raise ProfileDirError('Directory not found: %s' % path)
|
| 199 |
+
profile_dir = os.path.join(path, u'profile_' + name)
|
| 200 |
+
return cls(location=profile_dir, config=config)
|
| 201 |
+
|
| 202 |
+
@classmethod
|
| 203 |
+
def find_profile_dir_by_name(cls, ipython_dir, name=u'default', config=None):
|
| 204 |
+
"""Find an existing profile dir by profile name, return its ProfileDir.
|
| 205 |
+
|
| 206 |
+
This searches through a sequence of paths for a profile dir. If it
|
| 207 |
+
is not found, a :class:`ProfileDirError` exception will be raised.
|
| 208 |
+
|
| 209 |
+
The search path algorithm is:
|
| 210 |
+
1. ``os.getcwd()`` # removed for security reason.
|
| 211 |
+
2. ``ipython_dir``
|
| 212 |
+
|
| 213 |
+
Parameters
|
| 214 |
+
----------
|
| 215 |
+
ipython_dir : unicode or str
|
| 216 |
+
The IPython directory to use.
|
| 217 |
+
name : unicode or str
|
| 218 |
+
The name of the profile. The name of the profile directory
|
| 219 |
+
will be "profile_<profile>".
|
| 220 |
+
"""
|
| 221 |
+
dirname = u'profile_' + name
|
| 222 |
+
paths = [ipython_dir]
|
| 223 |
+
for p in paths:
|
| 224 |
+
profile_dir = os.path.join(p, dirname)
|
| 225 |
+
if os.path.isdir(profile_dir):
|
| 226 |
+
return cls(location=profile_dir, config=config)
|
| 227 |
+
else:
|
| 228 |
+
raise ProfileDirError('Profile directory not found in paths: %s' % dirname)
|
| 229 |
+
|
| 230 |
+
@classmethod
|
| 231 |
+
def find_profile_dir(cls, profile_dir, config=None):
|
| 232 |
+
"""Find/create a profile dir and return its ProfileDir.
|
| 233 |
+
|
| 234 |
+
This will create the profile directory if it doesn't exist.
|
| 235 |
+
|
| 236 |
+
Parameters
|
| 237 |
+
----------
|
| 238 |
+
profile_dir : unicode or str
|
| 239 |
+
The path of the profile directory.
|
| 240 |
+
"""
|
| 241 |
+
profile_dir = expand_path(profile_dir)
|
| 242 |
+
if not os.path.isdir(profile_dir):
|
| 243 |
+
raise ProfileDirError('Profile directory not found: %s' % profile_dir)
|
| 244 |
+
return cls(location=profile_dir, config=config)
|
lib/python3.12/site-packages/IPython/core/pylabtools.py
ADDED
|
@@ -0,0 +1,514 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""Pylab (matplotlib) support utilities."""
|
| 3 |
+
|
| 4 |
+
# Copyright (c) IPython Development Team.
|
| 5 |
+
# Distributed under the terms of the Modified BSD License.
|
| 6 |
+
|
| 7 |
+
from io import BytesIO
|
| 8 |
+
from binascii import b2a_base64
|
| 9 |
+
from functools import partial
|
| 10 |
+
import warnings
|
| 11 |
+
|
| 12 |
+
from IPython.core.display import _pngxy
|
| 13 |
+
from IPython.utils.decorators import flag_calls
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# Matplotlib backend resolution functionality moved from IPython to Matplotlib
|
| 17 |
+
# in IPython 8.24 and Matplotlib 3.9.0. Need to keep `backends` and `backend2gui`
|
| 18 |
+
# here for earlier Matplotlib and for external backend libraries such as
|
| 19 |
+
# mplcairo that might rely upon it.
|
| 20 |
+
_deprecated_backends = {
|
| 21 |
+
"tk": "TkAgg",
|
| 22 |
+
"gtk": "GTKAgg",
|
| 23 |
+
"gtk3": "GTK3Agg",
|
| 24 |
+
"gtk4": "GTK4Agg",
|
| 25 |
+
"wx": "WXAgg",
|
| 26 |
+
"qt4": "Qt4Agg",
|
| 27 |
+
"qt5": "Qt5Agg",
|
| 28 |
+
"qt6": "QtAgg",
|
| 29 |
+
"qt": "QtAgg",
|
| 30 |
+
"osx": "MacOSX",
|
| 31 |
+
"nbagg": "nbAgg",
|
| 32 |
+
"webagg": "WebAgg",
|
| 33 |
+
"notebook": "nbAgg",
|
| 34 |
+
"agg": "agg",
|
| 35 |
+
"svg": "svg",
|
| 36 |
+
"pdf": "pdf",
|
| 37 |
+
"ps": "ps",
|
| 38 |
+
"inline": "module://matplotlib_inline.backend_inline",
|
| 39 |
+
"ipympl": "module://ipympl.backend_nbagg",
|
| 40 |
+
"widget": "module://ipympl.backend_nbagg",
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
# We also need a reverse backends2guis mapping that will properly choose which
|
| 44 |
+
# GUI support to activate based on the desired matplotlib backend. For the
|
| 45 |
+
# most part it's just a reverse of the above dict, but we also need to add a
|
| 46 |
+
# few others that map to the same GUI manually:
|
| 47 |
+
_deprecated_backend2gui = dict(
|
| 48 |
+
zip(_deprecated_backends.values(), _deprecated_backends.keys())
|
| 49 |
+
)
|
| 50 |
+
# In the reverse mapping, there are a few extra valid matplotlib backends that
|
| 51 |
+
# map to the same GUI support
|
| 52 |
+
_deprecated_backend2gui["GTK"] = _deprecated_backend2gui["GTKCairo"] = "gtk"
|
| 53 |
+
_deprecated_backend2gui["GTK3Cairo"] = "gtk3"
|
| 54 |
+
_deprecated_backend2gui["GTK4Cairo"] = "gtk4"
|
| 55 |
+
_deprecated_backend2gui["WX"] = "wx"
|
| 56 |
+
_deprecated_backend2gui["CocoaAgg"] = "osx"
|
| 57 |
+
# There needs to be a hysteresis here as the new QtAgg Matplotlib backend
|
| 58 |
+
# supports either Qt5 or Qt6 and the IPython qt event loop support Qt4, Qt5,
|
| 59 |
+
# and Qt6.
|
| 60 |
+
_deprecated_backend2gui["QtAgg"] = "qt"
|
| 61 |
+
_deprecated_backend2gui["Qt4Agg"] = "qt4"
|
| 62 |
+
_deprecated_backend2gui["Qt5Agg"] = "qt5"
|
| 63 |
+
|
| 64 |
+
# And some backends that don't need GUI integration
|
| 65 |
+
del _deprecated_backend2gui["nbAgg"]
|
| 66 |
+
del _deprecated_backend2gui["agg"]
|
| 67 |
+
del _deprecated_backend2gui["svg"]
|
| 68 |
+
del _deprecated_backend2gui["pdf"]
|
| 69 |
+
del _deprecated_backend2gui["ps"]
|
| 70 |
+
del _deprecated_backend2gui["module://matplotlib_inline.backend_inline"]
|
| 71 |
+
del _deprecated_backend2gui["module://ipympl.backend_nbagg"]
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
# Deprecated attributes backends and backend2gui mostly following PEP 562.
|
| 75 |
+
def __getattr__(name):
|
| 76 |
+
if name in ("backends", "backend2gui"):
|
| 77 |
+
warnings.warn(
|
| 78 |
+
f"{name} is deprecated since IPython 8.24, backends are managed "
|
| 79 |
+
"in matplotlib and can be externally registered.",
|
| 80 |
+
DeprecationWarning,
|
| 81 |
+
)
|
| 82 |
+
return globals()[f"_deprecated_{name}"]
|
| 83 |
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
#-----------------------------------------------------------------------------
|
| 87 |
+
# Matplotlib utilities
|
| 88 |
+
#-----------------------------------------------------------------------------
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def getfigs(*fig_nums):
|
| 92 |
+
"""Get a list of matplotlib figures by figure numbers.
|
| 93 |
+
|
| 94 |
+
If no arguments are given, all available figures are returned. If the
|
| 95 |
+
argument list contains references to invalid figures, a warning is printed
|
| 96 |
+
but the function continues pasting further figures.
|
| 97 |
+
|
| 98 |
+
Parameters
|
| 99 |
+
----------
|
| 100 |
+
figs : tuple
|
| 101 |
+
A tuple of ints giving the figure numbers of the figures to return.
|
| 102 |
+
"""
|
| 103 |
+
from matplotlib._pylab_helpers import Gcf
|
| 104 |
+
if not fig_nums:
|
| 105 |
+
fig_managers = Gcf.get_all_fig_managers()
|
| 106 |
+
return [fm.canvas.figure for fm in fig_managers]
|
| 107 |
+
else:
|
| 108 |
+
figs = []
|
| 109 |
+
for num in fig_nums:
|
| 110 |
+
f = Gcf.figs.get(num)
|
| 111 |
+
if f is None:
|
| 112 |
+
print('Warning: figure %s not available.' % num)
|
| 113 |
+
else:
|
| 114 |
+
figs.append(f.canvas.figure)
|
| 115 |
+
return figs
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def figsize(sizex, sizey):
|
| 119 |
+
"""Set the default figure size to be [sizex, sizey].
|
| 120 |
+
|
| 121 |
+
This is just an easy to remember, convenience wrapper that sets::
|
| 122 |
+
|
| 123 |
+
matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
|
| 124 |
+
"""
|
| 125 |
+
import matplotlib
|
| 126 |
+
matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def print_figure(fig, fmt="png", bbox_inches="tight", base64=False, **kwargs):
|
| 130 |
+
"""Print a figure to an image, and return the resulting file data
|
| 131 |
+
|
| 132 |
+
Returned data will be bytes unless ``fmt='svg'``,
|
| 133 |
+
in which case it will be unicode.
|
| 134 |
+
|
| 135 |
+
Any keyword args are passed to fig.canvas.print_figure,
|
| 136 |
+
such as ``quality`` or ``bbox_inches``.
|
| 137 |
+
|
| 138 |
+
If `base64` is True, return base64-encoded str instead of raw bytes
|
| 139 |
+
for binary-encoded image formats
|
| 140 |
+
|
| 141 |
+
.. versionadded:: 7.29
|
| 142 |
+
base64 argument
|
| 143 |
+
"""
|
| 144 |
+
# When there's an empty figure, we shouldn't return anything, otherwise we
|
| 145 |
+
# get big blank areas in the qt console.
|
| 146 |
+
if not fig.axes and not fig.lines:
|
| 147 |
+
return
|
| 148 |
+
|
| 149 |
+
dpi = fig.dpi
|
| 150 |
+
if fmt == 'retina':
|
| 151 |
+
dpi = dpi * 2
|
| 152 |
+
fmt = 'png'
|
| 153 |
+
|
| 154 |
+
# build keyword args
|
| 155 |
+
kw = {
|
| 156 |
+
"format":fmt,
|
| 157 |
+
"facecolor":fig.get_facecolor(),
|
| 158 |
+
"edgecolor":fig.get_edgecolor(),
|
| 159 |
+
"dpi":dpi,
|
| 160 |
+
"bbox_inches":bbox_inches,
|
| 161 |
+
}
|
| 162 |
+
# **kwargs get higher priority
|
| 163 |
+
kw.update(kwargs)
|
| 164 |
+
|
| 165 |
+
bytes_io = BytesIO()
|
| 166 |
+
if fig.canvas is None:
|
| 167 |
+
from matplotlib.backend_bases import FigureCanvasBase
|
| 168 |
+
FigureCanvasBase(fig)
|
| 169 |
+
|
| 170 |
+
fig.canvas.print_figure(bytes_io, **kw)
|
| 171 |
+
data = bytes_io.getvalue()
|
| 172 |
+
if fmt == 'svg':
|
| 173 |
+
data = data.decode('utf-8')
|
| 174 |
+
elif base64:
|
| 175 |
+
data = b2a_base64(data, newline=False).decode("ascii")
|
| 176 |
+
return data
|
| 177 |
+
|
| 178 |
+
def retina_figure(fig, base64=False, **kwargs):
|
| 179 |
+
"""format a figure as a pixel-doubled (retina) PNG
|
| 180 |
+
|
| 181 |
+
If `base64` is True, return base64-encoded str instead of raw bytes
|
| 182 |
+
for binary-encoded image formats
|
| 183 |
+
|
| 184 |
+
.. versionadded:: 7.29
|
| 185 |
+
base64 argument
|
| 186 |
+
"""
|
| 187 |
+
pngdata = print_figure(fig, fmt="retina", base64=False, **kwargs)
|
| 188 |
+
# Make sure that retina_figure acts just like print_figure and returns
|
| 189 |
+
# None when the figure is empty.
|
| 190 |
+
if pngdata is None:
|
| 191 |
+
return
|
| 192 |
+
w, h = _pngxy(pngdata)
|
| 193 |
+
metadata = {"width": w//2, "height":h//2}
|
| 194 |
+
if base64:
|
| 195 |
+
pngdata = b2a_base64(pngdata, newline=False).decode("ascii")
|
| 196 |
+
return pngdata, metadata
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
# We need a little factory function here to create the closure where
|
| 200 |
+
# safe_execfile can live.
|
| 201 |
+
def mpl_runner(safe_execfile):
|
| 202 |
+
"""Factory to return a matplotlib-enabled runner for %run.
|
| 203 |
+
|
| 204 |
+
Parameters
|
| 205 |
+
----------
|
| 206 |
+
safe_execfile : function
|
| 207 |
+
This must be a function with the same interface as the
|
| 208 |
+
:meth:`safe_execfile` method of IPython.
|
| 209 |
+
|
| 210 |
+
Returns
|
| 211 |
+
-------
|
| 212 |
+
A function suitable for use as the ``runner`` argument of the %run magic
|
| 213 |
+
function.
|
| 214 |
+
"""
|
| 215 |
+
|
| 216 |
+
def mpl_execfile(fname,*where,**kw):
|
| 217 |
+
"""matplotlib-aware wrapper around safe_execfile.
|
| 218 |
+
|
| 219 |
+
Its interface is identical to that of the :func:`execfile` builtin.
|
| 220 |
+
|
| 221 |
+
This is ultimately a call to execfile(), but wrapped in safeties to
|
| 222 |
+
properly handle interactive rendering."""
|
| 223 |
+
|
| 224 |
+
import matplotlib
|
| 225 |
+
import matplotlib.pyplot as plt
|
| 226 |
+
|
| 227 |
+
# print('*** Matplotlib runner ***') # dbg
|
| 228 |
+
# turn off rendering until end of script
|
| 229 |
+
with matplotlib.rc_context({"interactive": False}):
|
| 230 |
+
safe_execfile(fname, *where, **kw)
|
| 231 |
+
|
| 232 |
+
if matplotlib.is_interactive():
|
| 233 |
+
plt.show()
|
| 234 |
+
|
| 235 |
+
# make rendering call now, if the user tried to do it
|
| 236 |
+
if plt.draw_if_interactive.called:
|
| 237 |
+
plt.draw()
|
| 238 |
+
plt.draw_if_interactive.called = False
|
| 239 |
+
|
| 240 |
+
# re-draw everything that is stale
|
| 241 |
+
try:
|
| 242 |
+
da = plt.draw_all
|
| 243 |
+
except AttributeError:
|
| 244 |
+
pass
|
| 245 |
+
else:
|
| 246 |
+
da()
|
| 247 |
+
|
| 248 |
+
return mpl_execfile
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def _reshow_nbagg_figure(fig):
|
| 252 |
+
"""reshow an nbagg figure"""
|
| 253 |
+
try:
|
| 254 |
+
reshow = fig.canvas.manager.reshow
|
| 255 |
+
except AttributeError as e:
|
| 256 |
+
raise NotImplementedError() from e
|
| 257 |
+
else:
|
| 258 |
+
reshow()
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def select_figure_formats(shell, formats, **kwargs):
|
| 262 |
+
"""Select figure formats for the inline backend.
|
| 263 |
+
|
| 264 |
+
Parameters
|
| 265 |
+
----------
|
| 266 |
+
shell : InteractiveShell
|
| 267 |
+
The main IPython instance.
|
| 268 |
+
formats : str or set
|
| 269 |
+
One or a set of figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'.
|
| 270 |
+
**kwargs : any
|
| 271 |
+
Extra keyword arguments to be passed to fig.canvas.print_figure.
|
| 272 |
+
"""
|
| 273 |
+
import matplotlib
|
| 274 |
+
from matplotlib.figure import Figure
|
| 275 |
+
|
| 276 |
+
svg_formatter = shell.display_formatter.formatters['image/svg+xml']
|
| 277 |
+
png_formatter = shell.display_formatter.formatters['image/png']
|
| 278 |
+
jpg_formatter = shell.display_formatter.formatters['image/jpeg']
|
| 279 |
+
pdf_formatter = shell.display_formatter.formatters['application/pdf']
|
| 280 |
+
|
| 281 |
+
if isinstance(formats, str):
|
| 282 |
+
formats = {formats}
|
| 283 |
+
# cast in case of list / tuple
|
| 284 |
+
formats = set(formats)
|
| 285 |
+
|
| 286 |
+
[ f.pop(Figure, None) for f in shell.display_formatter.formatters.values() ]
|
| 287 |
+
mplbackend = matplotlib.get_backend().lower()
|
| 288 |
+
if mplbackend in ("nbagg", "ipympl", "widget", "module://ipympl.backend_nbagg"):
|
| 289 |
+
formatter = shell.display_formatter.ipython_display_formatter
|
| 290 |
+
formatter.for_type(Figure, _reshow_nbagg_figure)
|
| 291 |
+
|
| 292 |
+
supported = {'png', 'png2x', 'retina', 'jpg', 'jpeg', 'svg', 'pdf'}
|
| 293 |
+
bad = formats.difference(supported)
|
| 294 |
+
if bad:
|
| 295 |
+
bs = "%s" % ','.join([repr(f) for f in bad])
|
| 296 |
+
gs = "%s" % ','.join([repr(f) for f in supported])
|
| 297 |
+
raise ValueError("supported formats are: %s not %s" % (gs, bs))
|
| 298 |
+
|
| 299 |
+
if "png" in formats:
|
| 300 |
+
png_formatter.for_type(
|
| 301 |
+
Figure, partial(print_figure, fmt="png", base64=True, **kwargs)
|
| 302 |
+
)
|
| 303 |
+
if "retina" in formats or "png2x" in formats:
|
| 304 |
+
png_formatter.for_type(Figure, partial(retina_figure, base64=True, **kwargs))
|
| 305 |
+
if "jpg" in formats or "jpeg" in formats:
|
| 306 |
+
jpg_formatter.for_type(
|
| 307 |
+
Figure, partial(print_figure, fmt="jpg", base64=True, **kwargs)
|
| 308 |
+
)
|
| 309 |
+
if "svg" in formats:
|
| 310 |
+
svg_formatter.for_type(Figure, partial(print_figure, fmt="svg", **kwargs))
|
| 311 |
+
if "pdf" in formats:
|
| 312 |
+
pdf_formatter.for_type(
|
| 313 |
+
Figure, partial(print_figure, fmt="pdf", base64=True, **kwargs)
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
#-----------------------------------------------------------------------------
|
| 317 |
+
# Code for initializing matplotlib and importing pylab
|
| 318 |
+
#-----------------------------------------------------------------------------
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def find_gui_and_backend(gui=None, gui_select=None):
|
| 322 |
+
"""Given a gui string return the gui and mpl backend.
|
| 323 |
+
|
| 324 |
+
Parameters
|
| 325 |
+
----------
|
| 326 |
+
gui : str
|
| 327 |
+
Can be one of ('tk','gtk','wx','qt','qt4','inline','agg').
|
| 328 |
+
gui_select : str
|
| 329 |
+
Can be one of ('tk','gtk','wx','qt','qt4','inline').
|
| 330 |
+
This is any gui already selected by the shell.
|
| 331 |
+
|
| 332 |
+
Returns
|
| 333 |
+
-------
|
| 334 |
+
A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg',
|
| 335 |
+
'WXAgg','Qt4Agg','module://matplotlib_inline.backend_inline','agg').
|
| 336 |
+
"""
|
| 337 |
+
|
| 338 |
+
import matplotlib
|
| 339 |
+
|
| 340 |
+
if _matplotlib_manages_backends():
|
| 341 |
+
backend_registry = matplotlib.backends.registry.backend_registry
|
| 342 |
+
|
| 343 |
+
# gui argument may be a gui event loop or may be a backend name.
|
| 344 |
+
if gui in ("auto", None):
|
| 345 |
+
backend = matplotlib.rcParamsOrig["backend"]
|
| 346 |
+
backend, gui = backend_registry.resolve_backend(backend)
|
| 347 |
+
else:
|
| 348 |
+
gui = _convert_gui_to_matplotlib(gui)
|
| 349 |
+
backend, gui = backend_registry.resolve_gui_or_backend(gui)
|
| 350 |
+
|
| 351 |
+
gui = _convert_gui_from_matplotlib(gui)
|
| 352 |
+
return gui, backend
|
| 353 |
+
|
| 354 |
+
# Fallback to previous behaviour (Matplotlib < 3.9)
|
| 355 |
+
mpl_version_info = getattr(matplotlib, "__version_info__", (0, 0))
|
| 356 |
+
has_unified_qt_backend = mpl_version_info >= (3, 5)
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
backends_ = dict(_deprecated_backends)
|
| 360 |
+
if not has_unified_qt_backend:
|
| 361 |
+
backends_["qt"] = "qt5agg"
|
| 362 |
+
|
| 363 |
+
if gui and gui != 'auto':
|
| 364 |
+
# select backend based on requested gui
|
| 365 |
+
backend = backends_[gui]
|
| 366 |
+
if gui == 'agg':
|
| 367 |
+
gui = None
|
| 368 |
+
else:
|
| 369 |
+
# We need to read the backend from the original data structure, *not*
|
| 370 |
+
# from mpl.rcParams, since a prior invocation of %matplotlib may have
|
| 371 |
+
# overwritten that.
|
| 372 |
+
# WARNING: this assumes matplotlib 1.1 or newer!!
|
| 373 |
+
backend = matplotlib.rcParamsOrig['backend']
|
| 374 |
+
|
| 375 |
+
# In this case, we need to find what the appropriate gui selection call
|
| 376 |
+
# should be for IPython, so we can activate inputhook accordingly
|
| 377 |
+
gui = _deprecated_backend2gui.get(backend, None)
|
| 378 |
+
|
| 379 |
+
# If we have already had a gui active, we need it and inline are the
|
| 380 |
+
# ones allowed.
|
| 381 |
+
if gui_select and gui != gui_select:
|
| 382 |
+
gui = gui_select
|
| 383 |
+
backend = backends_[gui]
|
| 384 |
+
|
| 385 |
+
# Matplotlib before _matplotlib_manages_backends() can return "inline" for
|
| 386 |
+
# no gui event loop rather than the None that IPython >= 8.24.0 expects.
|
| 387 |
+
if gui == "inline":
|
| 388 |
+
gui = None
|
| 389 |
+
|
| 390 |
+
return gui, backend
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def activate_matplotlib(backend):
|
| 394 |
+
"""Activate the given backend and set interactive to True."""
|
| 395 |
+
|
| 396 |
+
import matplotlib
|
| 397 |
+
matplotlib.interactive(True)
|
| 398 |
+
|
| 399 |
+
# Matplotlib had a bug where even switch_backend could not force
|
| 400 |
+
# the rcParam to update. This needs to be set *before* the module
|
| 401 |
+
# magic of switch_backend().
|
| 402 |
+
matplotlib.rcParams['backend'] = backend
|
| 403 |
+
|
| 404 |
+
# Due to circular imports, pyplot may be only partially initialised
|
| 405 |
+
# when this function runs.
|
| 406 |
+
# So avoid needing matplotlib attribute-lookup to access pyplot.
|
| 407 |
+
from matplotlib import pyplot as plt
|
| 408 |
+
|
| 409 |
+
plt.switch_backend(backend)
|
| 410 |
+
|
| 411 |
+
plt.show._needmain = False
|
| 412 |
+
# We need to detect at runtime whether show() is called by the user.
|
| 413 |
+
# For this, we wrap it into a decorator which adds a 'called' flag.
|
| 414 |
+
plt.draw_if_interactive = flag_calls(plt.draw_if_interactive)
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def import_pylab(user_ns, import_all=True):
|
| 418 |
+
"""Populate the namespace with pylab-related values.
|
| 419 |
+
|
| 420 |
+
Imports matplotlib, pylab, numpy, and everything from pylab and numpy.
|
| 421 |
+
|
| 422 |
+
Also imports a few names from IPython (figsize, display, getfigs)
|
| 423 |
+
|
| 424 |
+
"""
|
| 425 |
+
|
| 426 |
+
# Import numpy as np/pyplot as plt are conventions we're trying to
|
| 427 |
+
# somewhat standardize on. Making them available to users by default
|
| 428 |
+
# will greatly help this.
|
| 429 |
+
s = ("import numpy\n"
|
| 430 |
+
"import matplotlib\n"
|
| 431 |
+
"from matplotlib import pylab, mlab, pyplot\n"
|
| 432 |
+
"np = numpy\n"
|
| 433 |
+
"plt = pyplot\n"
|
| 434 |
+
)
|
| 435 |
+
exec(s, user_ns)
|
| 436 |
+
|
| 437 |
+
if import_all:
|
| 438 |
+
s = ("from matplotlib.pylab import *\n"
|
| 439 |
+
"from numpy import *\n")
|
| 440 |
+
exec(s, user_ns)
|
| 441 |
+
|
| 442 |
+
# IPython symbols to add
|
| 443 |
+
user_ns['figsize'] = figsize
|
| 444 |
+
from IPython.display import display
|
| 445 |
+
# Add display and getfigs to the user's namespace
|
| 446 |
+
user_ns['display'] = display
|
| 447 |
+
user_ns['getfigs'] = getfigs
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
# Determine if Matplotlib manages backends only if needed, and cache result.
|
| 451 |
+
# Do not read this directly, instead use _matplotlib_manages_backends().
|
| 452 |
+
_matplotlib_manages_backends_value: bool | None = None
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
def _matplotlib_manages_backends() -> bool:
|
| 456 |
+
"""Return True if Matplotlib manages backends, False otherwise.
|
| 457 |
+
|
| 458 |
+
If it returns True, the caller can be sure that
|
| 459 |
+
matplotlib.backends.registry.backend_registry is available along with
|
| 460 |
+
member functions resolve_gui_or_backend, resolve_backend, list_all, and
|
| 461 |
+
list_gui_frameworks.
|
| 462 |
+
|
| 463 |
+
This function can be removed as it will always return True when Python
|
| 464 |
+
3.12, the latest version supported by Matplotlib < 3.9, reaches
|
| 465 |
+
end-of-life in late 2028.
|
| 466 |
+
"""
|
| 467 |
+
global _matplotlib_manages_backends_value
|
| 468 |
+
if _matplotlib_manages_backends_value is None:
|
| 469 |
+
try:
|
| 470 |
+
from matplotlib.backends.registry import backend_registry
|
| 471 |
+
|
| 472 |
+
_matplotlib_manages_backends_value = hasattr(
|
| 473 |
+
backend_registry, "resolve_gui_or_backend"
|
| 474 |
+
)
|
| 475 |
+
except ImportError:
|
| 476 |
+
_matplotlib_manages_backends_value = False
|
| 477 |
+
|
| 478 |
+
return _matplotlib_manages_backends_value
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
def _list_matplotlib_backends_and_gui_loops() -> list[str]:
|
| 482 |
+
"""Return list of all Matplotlib backends and GUI event loops.
|
| 483 |
+
|
| 484 |
+
This is the list returned by
|
| 485 |
+
%matplotlib --list
|
| 486 |
+
"""
|
| 487 |
+
if _matplotlib_manages_backends():
|
| 488 |
+
from matplotlib.backends.registry import backend_registry
|
| 489 |
+
|
| 490 |
+
ret = backend_registry.list_all() + [
|
| 491 |
+
_convert_gui_from_matplotlib(gui)
|
| 492 |
+
for gui in backend_registry.list_gui_frameworks()
|
| 493 |
+
]
|
| 494 |
+
else:
|
| 495 |
+
from IPython.core import pylabtools
|
| 496 |
+
|
| 497 |
+
ret = list(pylabtools.backends.keys())
|
| 498 |
+
|
| 499 |
+
return sorted(["auto"] + ret)
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
# Matplotlib and IPython do not always use the same gui framework name.
|
| 503 |
+
# Always use the appropriate one of these conversion functions when passing a
|
| 504 |
+
# gui framework name to/from Matplotlib.
|
| 505 |
+
def _convert_gui_to_matplotlib(gui: str | None) -> str | None:
|
| 506 |
+
if gui and gui.lower() == "osx":
|
| 507 |
+
return "macosx"
|
| 508 |
+
return gui
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
def _convert_gui_from_matplotlib(gui: str | None) -> str | None:
|
| 512 |
+
if gui and gui.lower() == "macosx":
|
| 513 |
+
return "osx"
|
| 514 |
+
return gui
|
lib/python3.12/site-packages/IPython/core/shellapp.py
ADDED
|
@@ -0,0 +1,500 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# encoding: utf-8
|
| 2 |
+
"""
|
| 3 |
+
A mixin for :class:`~IPython.core.application.Application` classes that
|
| 4 |
+
launch InteractiveShell instances, load extensions, etc.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
# Copyright (c) IPython Development Team.
|
| 8 |
+
# Distributed under the terms of the Modified BSD License.
|
| 9 |
+
|
| 10 |
+
import glob
|
| 11 |
+
from itertools import chain
|
| 12 |
+
import os
|
| 13 |
+
import sys
|
| 14 |
+
import typing as t
|
| 15 |
+
|
| 16 |
+
from traitlets.config.application import boolean_flag
|
| 17 |
+
from traitlets.config.configurable import Configurable
|
| 18 |
+
from traitlets.config.loader import Config
|
| 19 |
+
from IPython.core.application import SYSTEM_CONFIG_DIRS, ENV_CONFIG_DIRS
|
| 20 |
+
from IPython.utils.contexts import preserve_keys
|
| 21 |
+
from IPython.utils.path import filefind
|
| 22 |
+
from traitlets import (
|
| 23 |
+
Unicode,
|
| 24 |
+
Instance,
|
| 25 |
+
List,
|
| 26 |
+
Bool,
|
| 27 |
+
CaselessStrEnum,
|
| 28 |
+
observe,
|
| 29 |
+
DottedObjectName,
|
| 30 |
+
Undefined,
|
| 31 |
+
)
|
| 32 |
+
from IPython.terminal import pt_inputhooks
|
| 33 |
+
|
| 34 |
+
# -----------------------------------------------------------------------------
|
| 35 |
+
# Aliases and Flags
|
| 36 |
+
# -----------------------------------------------------------------------------
|
| 37 |
+
|
| 38 |
+
gui_keys = tuple(sorted(pt_inputhooks.backends) + sorted(pt_inputhooks.aliases))
|
| 39 |
+
|
| 40 |
+
shell_flags = {}
|
| 41 |
+
|
| 42 |
+
addflag = lambda *args: shell_flags.update(boolean_flag(*args))
|
| 43 |
+
addflag(
|
| 44 |
+
"autoindent",
|
| 45 |
+
"InteractiveShell.autoindent",
|
| 46 |
+
"Turn on autoindenting.",
|
| 47 |
+
"Turn off autoindenting.",
|
| 48 |
+
)
|
| 49 |
+
addflag(
|
| 50 |
+
"automagic",
|
| 51 |
+
"InteractiveShell.automagic",
|
| 52 |
+
"""Turn on the auto calling of magic commands. Type %%magic at the
|
| 53 |
+
IPython prompt for more information.""",
|
| 54 |
+
'Turn off the auto calling of magic commands.'
|
| 55 |
+
)
|
| 56 |
+
addflag('pdb', 'InteractiveShell.pdb',
|
| 57 |
+
"Enable auto calling the pdb debugger after every exception.",
|
| 58 |
+
"Disable auto calling the pdb debugger after every exception."
|
| 59 |
+
)
|
| 60 |
+
addflag('pprint', 'PlainTextFormatter.pprint',
|
| 61 |
+
"Enable auto pretty printing of results.",
|
| 62 |
+
"Disable auto pretty printing of results."
|
| 63 |
+
)
|
| 64 |
+
addflag('color-info', 'InteractiveShell.color_info',
|
| 65 |
+
"""IPython can display information about objects via a set of functions,
|
| 66 |
+
and optionally can use colors for this, syntax highlighting
|
| 67 |
+
source code and various other elements. This is on by default, but can cause
|
| 68 |
+
problems with some pagers. If you see such problems, you can disable the
|
| 69 |
+
colours.""",
|
| 70 |
+
"Disable using colors for info related things."
|
| 71 |
+
)
|
| 72 |
+
addflag('ignore-cwd', 'InteractiveShellApp.ignore_cwd',
|
| 73 |
+
"Exclude the current working directory from sys.path",
|
| 74 |
+
"Include the current working directory in sys.path",
|
| 75 |
+
)
|
| 76 |
+
nosep_config = Config()
|
| 77 |
+
nosep_config.InteractiveShell.separate_in = ''
|
| 78 |
+
nosep_config.InteractiveShell.separate_out = ''
|
| 79 |
+
nosep_config.InteractiveShell.separate_out2 = ''
|
| 80 |
+
|
| 81 |
+
shell_flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.")
|
| 82 |
+
shell_flags['pylab'] = (
|
| 83 |
+
{'InteractiveShellApp' : {'pylab' : 'auto'}},
|
| 84 |
+
"""Pre-load matplotlib and numpy for interactive use with
|
| 85 |
+
the default matplotlib backend. The exact options available
|
| 86 |
+
depend on what Matplotlib provides at runtime.""",
|
| 87 |
+
)
|
| 88 |
+
shell_flags['matplotlib'] = (
|
| 89 |
+
{'InteractiveShellApp' : {'matplotlib' : 'auto'}},
|
| 90 |
+
"""Configure matplotlib for interactive use with
|
| 91 |
+
the default matplotlib backend. The exact options available
|
| 92 |
+
depend on what Matplotlib provides at runtime.""",
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
# it's possible we don't want short aliases for *all* of these:
|
| 96 |
+
shell_aliases = dict(
|
| 97 |
+
autocall="InteractiveShell.autocall",
|
| 98 |
+
colors="InteractiveShell.colors",
|
| 99 |
+
theme="InteractiveShell.colors",
|
| 100 |
+
logfile="InteractiveShell.logfile",
|
| 101 |
+
logappend="InteractiveShell.logappend",
|
| 102 |
+
c="InteractiveShellApp.code_to_run",
|
| 103 |
+
m="InteractiveShellApp.module_to_run",
|
| 104 |
+
ext="InteractiveShellApp.extra_extensions",
|
| 105 |
+
gui='InteractiveShellApp.gui',
|
| 106 |
+
pylab='InteractiveShellApp.pylab',
|
| 107 |
+
matplotlib='InteractiveShellApp.matplotlib',
|
| 108 |
+
)
|
| 109 |
+
shell_aliases['cache-size'] = 'InteractiveShell.cache_size'
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# -----------------------------------------------------------------------------
|
| 113 |
+
# Traitlets
|
| 114 |
+
# -----------------------------------------------------------------------------
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class MatplotlibBackendCaselessStrEnum(CaselessStrEnum):
|
| 118 |
+
"""An enum of Matplotlib backend strings where the case should be ignored.
|
| 119 |
+
|
| 120 |
+
Prior to Matplotlib 3.9.0 the list of valid backends is hardcoded in
|
| 121 |
+
pylabtools.backends. After that, Matplotlib manages backends.
|
| 122 |
+
|
| 123 |
+
The list of valid backends is determined when it is first needed to avoid
|
| 124 |
+
wasting unnecessary initialisation time.
|
| 125 |
+
"""
|
| 126 |
+
|
| 127 |
+
def __init__(
|
| 128 |
+
self: CaselessStrEnum[t.Any],
|
| 129 |
+
default_value: t.Any = Undefined,
|
| 130 |
+
**kwargs: t.Any,
|
| 131 |
+
) -> None:
|
| 132 |
+
super().__init__(None, default_value=default_value, **kwargs)
|
| 133 |
+
|
| 134 |
+
def __getattribute__(self, name):
|
| 135 |
+
if name == "values" and object.__getattribute__(self, name) is None:
|
| 136 |
+
from IPython.core.pylabtools import _list_matplotlib_backends_and_gui_loops
|
| 137 |
+
|
| 138 |
+
self.values = _list_matplotlib_backends_and_gui_loops()
|
| 139 |
+
return object.__getattribute__(self, name)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
#-----------------------------------------------------------------------------
|
| 143 |
+
# Main classes and functions
|
| 144 |
+
#-----------------------------------------------------------------------------
|
| 145 |
+
|
| 146 |
+
class InteractiveShellApp(Configurable):
|
| 147 |
+
"""A Mixin for applications that start InteractiveShell instances.
|
| 148 |
+
|
| 149 |
+
Provides configurables for loading extensions and executing files
|
| 150 |
+
as part of configuring a Shell environment.
|
| 151 |
+
|
| 152 |
+
The following methods should be called by the :meth:`initialize` method
|
| 153 |
+
of the subclass:
|
| 154 |
+
|
| 155 |
+
- :meth:`init_path`
|
| 156 |
+
- :meth:`init_shell` (to be implemented by the subclass)
|
| 157 |
+
- :meth:`init_gui_pylab`
|
| 158 |
+
- :meth:`init_extensions`
|
| 159 |
+
- :meth:`init_code`
|
| 160 |
+
"""
|
| 161 |
+
extensions = List(Unicode(),
|
| 162 |
+
help="A list of dotted module names of IPython extensions to load."
|
| 163 |
+
).tag(config=True)
|
| 164 |
+
|
| 165 |
+
extra_extensions = List(
|
| 166 |
+
DottedObjectName(),
|
| 167 |
+
help="""
|
| 168 |
+
Dotted module name(s) of one or more IPython extensions to load.
|
| 169 |
+
|
| 170 |
+
For specifying extra extensions to load on the command-line.
|
| 171 |
+
|
| 172 |
+
.. versionadded:: 7.10
|
| 173 |
+
""",
|
| 174 |
+
).tag(config=True)
|
| 175 |
+
|
| 176 |
+
reraise_ipython_extension_failures = Bool(False,
|
| 177 |
+
help="Reraise exceptions encountered loading IPython extensions?",
|
| 178 |
+
).tag(config=True)
|
| 179 |
+
|
| 180 |
+
# Extensions that are always loaded (not configurable)
|
| 181 |
+
default_extensions = List(Unicode(), [u'storemagic']).tag(config=False)
|
| 182 |
+
|
| 183 |
+
hide_initial_ns = Bool(True,
|
| 184 |
+
help="""Should variables loaded at startup (by startup files, exec_lines, etc.)
|
| 185 |
+
be hidden from tools like %who?"""
|
| 186 |
+
).tag(config=True)
|
| 187 |
+
|
| 188 |
+
exec_files = List(Unicode(),
|
| 189 |
+
help="""List of files to run at IPython startup."""
|
| 190 |
+
).tag(config=True)
|
| 191 |
+
exec_PYTHONSTARTUP = Bool(True,
|
| 192 |
+
help="""Run the file referenced by the PYTHONSTARTUP environment
|
| 193 |
+
variable at IPython startup."""
|
| 194 |
+
).tag(config=True)
|
| 195 |
+
file_to_run = Unicode('',
|
| 196 |
+
help="""A file to be run""").tag(config=True)
|
| 197 |
+
|
| 198 |
+
exec_lines = List(Unicode(),
|
| 199 |
+
help="""lines of code to run at IPython startup."""
|
| 200 |
+
).tag(config=True)
|
| 201 |
+
code_to_run = Unicode("", help="Execute the given command string.").tag(config=True)
|
| 202 |
+
module_to_run = Unicode("", help="Run the module as a script.").tag(config=True)
|
| 203 |
+
gui = CaselessStrEnum(
|
| 204 |
+
gui_keys,
|
| 205 |
+
allow_none=True,
|
| 206 |
+
help="Enable GUI event loop integration with any of {0}.".format(gui_keys),
|
| 207 |
+
).tag(config=True)
|
| 208 |
+
matplotlib = MatplotlibBackendCaselessStrEnum(
|
| 209 |
+
allow_none=True,
|
| 210 |
+
help="""Configure matplotlib for interactive use with
|
| 211 |
+
the default matplotlib backend. The exact options available
|
| 212 |
+
depend on what Matplotlib provides at runtime.""",
|
| 213 |
+
).tag(config=True)
|
| 214 |
+
pylab = MatplotlibBackendCaselessStrEnum(
|
| 215 |
+
allow_none=True,
|
| 216 |
+
help="""Pre-load matplotlib and numpy for interactive use,
|
| 217 |
+
selecting a particular matplotlib backend and loop integration.
|
| 218 |
+
The exact options available depend on what Matplotlib provides at runtime.
|
| 219 |
+
""",
|
| 220 |
+
).tag(config=True)
|
| 221 |
+
pylab_import_all = Bool(
|
| 222 |
+
True,
|
| 223 |
+
help="""If true, IPython will populate the user namespace with numpy, pylab, etc.
|
| 224 |
+
and an ``import *`` is done from numpy and pylab, when using pylab mode.
|
| 225 |
+
|
| 226 |
+
When False, pylab mode should not import any names into the user namespace.
|
| 227 |
+
""",
|
| 228 |
+
).tag(config=True)
|
| 229 |
+
ignore_cwd = Bool(
|
| 230 |
+
False,
|
| 231 |
+
help="""If True, IPython will not add the current working directory to sys.path.
|
| 232 |
+
When False, the current working directory is added to sys.path, allowing imports
|
| 233 |
+
of modules defined in the current directory."""
|
| 234 |
+
).tag(config=True)
|
| 235 |
+
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
|
| 236 |
+
allow_none=True)
|
| 237 |
+
# whether interact-loop should start
|
| 238 |
+
interact = Bool(True)
|
| 239 |
+
|
| 240 |
+
user_ns = Instance(dict, args=None, allow_none=True)
|
| 241 |
+
@observe('user_ns')
|
| 242 |
+
def _user_ns_changed(self, change):
|
| 243 |
+
if self.shell is not None:
|
| 244 |
+
self.shell.user_ns = change['new']
|
| 245 |
+
self.shell.init_user_ns()
|
| 246 |
+
|
| 247 |
+
def init_path(self):
|
| 248 |
+
"""Add current working directory, '', to sys.path
|
| 249 |
+
|
| 250 |
+
Unless disabled by ignore_cwd config or sys.flags.safe_path.
|
| 251 |
+
|
| 252 |
+
Unlike Python's default, we insert before the first `site-packages`
|
| 253 |
+
or `dist-packages` directory,
|
| 254 |
+
so that it is after the standard library.
|
| 255 |
+
|
| 256 |
+
.. versionchanged:: 7.2
|
| 257 |
+
Try to insert after the standard library, instead of first.
|
| 258 |
+
.. versionchanged:: 8.0
|
| 259 |
+
Allow optionally not including the current directory in sys.path
|
| 260 |
+
.. versionchanged:: 9.7
|
| 261 |
+
Respect sys.flags.safe_path (PYTHONSAFEPATH and -P flag)
|
| 262 |
+
"""
|
| 263 |
+
if "" in sys.path or self.ignore_cwd or sys.flags.safe_path:
|
| 264 |
+
return
|
| 265 |
+
for idx, path in enumerate(sys.path):
|
| 266 |
+
parent, last_part = os.path.split(path)
|
| 267 |
+
if last_part in {'site-packages', 'dist-packages'}:
|
| 268 |
+
break
|
| 269 |
+
else:
|
| 270 |
+
# no site-packages or dist-packages found (?!)
|
| 271 |
+
# back to original behavior of inserting at the front
|
| 272 |
+
idx = 0
|
| 273 |
+
sys.path.insert(idx, '')
|
| 274 |
+
|
| 275 |
+
def init_shell(self):
|
| 276 |
+
raise NotImplementedError("Override in subclasses")
|
| 277 |
+
|
| 278 |
+
def init_gui_pylab(self):
|
| 279 |
+
"""Enable GUI event loop integration, taking pylab into account."""
|
| 280 |
+
enable = False
|
| 281 |
+
shell = self.shell
|
| 282 |
+
if self.pylab:
|
| 283 |
+
enable = lambda key: shell.enable_pylab(key, import_all=self.pylab_import_all)
|
| 284 |
+
key = self.pylab
|
| 285 |
+
elif self.matplotlib:
|
| 286 |
+
enable = shell.enable_matplotlib
|
| 287 |
+
key = self.matplotlib
|
| 288 |
+
elif self.gui:
|
| 289 |
+
enable = shell.enable_gui
|
| 290 |
+
key = self.gui
|
| 291 |
+
|
| 292 |
+
if not enable:
|
| 293 |
+
return
|
| 294 |
+
|
| 295 |
+
try:
|
| 296 |
+
r = enable(key)
|
| 297 |
+
except ImportError:
|
| 298 |
+
self.log.warning("Eventloop or matplotlib integration failed. Is matplotlib installed?")
|
| 299 |
+
self.shell.showtraceback()
|
| 300 |
+
return
|
| 301 |
+
except Exception:
|
| 302 |
+
self.log.warning("GUI event loop or pylab initialization failed")
|
| 303 |
+
self.shell.showtraceback()
|
| 304 |
+
return
|
| 305 |
+
|
| 306 |
+
if isinstance(r, tuple):
|
| 307 |
+
gui, backend = r[:2]
|
| 308 |
+
self.log.info("Enabling GUI event loop integration, "
|
| 309 |
+
"eventloop=%s, matplotlib=%s", gui, backend)
|
| 310 |
+
if key == "auto":
|
| 311 |
+
print("Using matplotlib backend: %s" % backend)
|
| 312 |
+
else:
|
| 313 |
+
gui = r
|
| 314 |
+
self.log.info("Enabling GUI event loop integration, "
|
| 315 |
+
"eventloop=%s", gui)
|
| 316 |
+
|
| 317 |
+
def init_extensions(self):
|
| 318 |
+
"""Load all IPython extensions in IPythonApp.extensions.
|
| 319 |
+
|
| 320 |
+
This uses the :meth:`ExtensionManager.load_extensions` to load all
|
| 321 |
+
the extensions listed in ``self.extensions``.
|
| 322 |
+
"""
|
| 323 |
+
try:
|
| 324 |
+
self.log.debug("Loading IPython extensions...")
|
| 325 |
+
extensions = (
|
| 326 |
+
self.default_extensions + self.extensions + self.extra_extensions
|
| 327 |
+
)
|
| 328 |
+
for ext in extensions:
|
| 329 |
+
try:
|
| 330 |
+
self.log.info("Loading IPython extension: %s", ext)
|
| 331 |
+
self.shell.extension_manager.load_extension(ext)
|
| 332 |
+
except:
|
| 333 |
+
if self.reraise_ipython_extension_failures:
|
| 334 |
+
raise
|
| 335 |
+
msg = ("Error in loading extension: {ext}\n"
|
| 336 |
+
"Check your config files in {location}".format(
|
| 337 |
+
ext=ext,
|
| 338 |
+
location=self.profile_dir.location
|
| 339 |
+
))
|
| 340 |
+
self.log.warning(msg, exc_info=True)
|
| 341 |
+
except:
|
| 342 |
+
if self.reraise_ipython_extension_failures:
|
| 343 |
+
raise
|
| 344 |
+
self.log.warning("Unknown error in loading extensions:", exc_info=True)
|
| 345 |
+
|
| 346 |
+
def init_code(self):
|
| 347 |
+
"""run the pre-flight code, specified via exec_lines"""
|
| 348 |
+
self._run_startup_files()
|
| 349 |
+
self._run_exec_lines()
|
| 350 |
+
self._run_exec_files()
|
| 351 |
+
|
| 352 |
+
# Hide variables defined here from %who etc.
|
| 353 |
+
if self.hide_initial_ns:
|
| 354 |
+
self.shell.user_ns_hidden.update(self.shell.user_ns)
|
| 355 |
+
|
| 356 |
+
# command-line execution (ipython -i script.py, ipython -m module)
|
| 357 |
+
# should *not* be excluded from %whos
|
| 358 |
+
self._run_cmd_line_code()
|
| 359 |
+
self._run_module()
|
| 360 |
+
|
| 361 |
+
# flush output, so itwon't be attached to the first cell
|
| 362 |
+
sys.stdout.flush()
|
| 363 |
+
sys.stderr.flush()
|
| 364 |
+
self.shell._sys_modules_keys = set(sys.modules.keys())
|
| 365 |
+
|
| 366 |
+
def _run_exec_lines(self):
|
| 367 |
+
"""Run lines of code in IPythonApp.exec_lines in the user's namespace."""
|
| 368 |
+
if not self.exec_lines:
|
| 369 |
+
return
|
| 370 |
+
try:
|
| 371 |
+
self.log.debug("Running code from IPythonApp.exec_lines...")
|
| 372 |
+
for line in self.exec_lines:
|
| 373 |
+
try:
|
| 374 |
+
self.log.info("Running code in user namespace: %s" %
|
| 375 |
+
line)
|
| 376 |
+
self.shell.run_cell(line, store_history=False)
|
| 377 |
+
except:
|
| 378 |
+
self.log.warning("Error in executing line in user "
|
| 379 |
+
"namespace: %s" % line)
|
| 380 |
+
self.shell.showtraceback()
|
| 381 |
+
except:
|
| 382 |
+
self.log.warning("Unknown error in handling IPythonApp.exec_lines:")
|
| 383 |
+
self.shell.showtraceback()
|
| 384 |
+
|
| 385 |
+
def _exec_file(self, fname, shell_futures=False):
|
| 386 |
+
try:
|
| 387 |
+
full_filename = filefind(fname, [u'.', self.ipython_dir])
|
| 388 |
+
except IOError:
|
| 389 |
+
self.log.warning("File not found: %r"%fname)
|
| 390 |
+
return
|
| 391 |
+
# Make sure that the running script gets a proper sys.argv as if it
|
| 392 |
+
# were run from a system shell.
|
| 393 |
+
save_argv = sys.argv
|
| 394 |
+
sys.argv = [full_filename] + self.extra_args[1:]
|
| 395 |
+
try:
|
| 396 |
+
if os.path.isfile(full_filename):
|
| 397 |
+
self.log.info("Running file in user namespace: %s" %
|
| 398 |
+
full_filename)
|
| 399 |
+
# Ensure that __file__ is always defined to match Python
|
| 400 |
+
# behavior.
|
| 401 |
+
with preserve_keys(self.shell.user_ns, '__file__'):
|
| 402 |
+
self.shell.user_ns['__file__'] = fname
|
| 403 |
+
if full_filename.endswith('.ipy') or full_filename.endswith('.ipynb'):
|
| 404 |
+
self.shell.safe_execfile_ipy(full_filename,
|
| 405 |
+
shell_futures=shell_futures)
|
| 406 |
+
else:
|
| 407 |
+
# default to python, even without extension
|
| 408 |
+
self.shell.safe_execfile(full_filename,
|
| 409 |
+
self.shell.user_ns,
|
| 410 |
+
shell_futures=shell_futures,
|
| 411 |
+
raise_exceptions=True)
|
| 412 |
+
finally:
|
| 413 |
+
sys.argv = save_argv
|
| 414 |
+
|
| 415 |
+
def _run_startup_files(self):
|
| 416 |
+
"""Run files from profile startup directory"""
|
| 417 |
+
startup_dirs = [self.profile_dir.startup_dir] + [
|
| 418 |
+
os.path.join(p, 'startup') for p in chain(ENV_CONFIG_DIRS, SYSTEM_CONFIG_DIRS)
|
| 419 |
+
]
|
| 420 |
+
startup_files = []
|
| 421 |
+
|
| 422 |
+
if self.exec_PYTHONSTARTUP and os.environ.get('PYTHONSTARTUP', False) and \
|
| 423 |
+
not (self.file_to_run or self.code_to_run or self.module_to_run):
|
| 424 |
+
python_startup = os.environ['PYTHONSTARTUP']
|
| 425 |
+
self.log.debug("Running PYTHONSTARTUP file %s...", python_startup)
|
| 426 |
+
try:
|
| 427 |
+
self._exec_file(python_startup)
|
| 428 |
+
except:
|
| 429 |
+
self.log.warning("Unknown error in handling PYTHONSTARTUP file %s:", python_startup)
|
| 430 |
+
self.shell.showtraceback()
|
| 431 |
+
for startup_dir in startup_dirs[::-1]:
|
| 432 |
+
startup_files += glob.glob(os.path.join(startup_dir, '*.py'))
|
| 433 |
+
startup_files += glob.glob(os.path.join(startup_dir, '*.ipy'))
|
| 434 |
+
if not startup_files:
|
| 435 |
+
return
|
| 436 |
+
|
| 437 |
+
self.log.debug("Running startup files from %s...", startup_dir)
|
| 438 |
+
try:
|
| 439 |
+
for fname in sorted(startup_files):
|
| 440 |
+
self._exec_file(fname)
|
| 441 |
+
except:
|
| 442 |
+
self.log.warning("Unknown error in handling startup files:")
|
| 443 |
+
self.shell.showtraceback()
|
| 444 |
+
|
| 445 |
+
def _run_exec_files(self):
|
| 446 |
+
"""Run files from IPythonApp.exec_files"""
|
| 447 |
+
if not self.exec_files:
|
| 448 |
+
return
|
| 449 |
+
|
| 450 |
+
self.log.debug("Running files in IPythonApp.exec_files...")
|
| 451 |
+
try:
|
| 452 |
+
for fname in self.exec_files:
|
| 453 |
+
self._exec_file(fname)
|
| 454 |
+
except:
|
| 455 |
+
self.log.warning("Unknown error in handling IPythonApp.exec_files:")
|
| 456 |
+
self.shell.showtraceback()
|
| 457 |
+
|
| 458 |
+
def _run_cmd_line_code(self):
|
| 459 |
+
"""Run code or file specified at the command-line"""
|
| 460 |
+
if self.code_to_run:
|
| 461 |
+
line = self.code_to_run
|
| 462 |
+
try:
|
| 463 |
+
self.log.info("Running code given at command line (c=): %s" %
|
| 464 |
+
line)
|
| 465 |
+
self.shell.run_cell(line, store_history=False)
|
| 466 |
+
except:
|
| 467 |
+
self.log.warning("Error in executing line in user namespace: %s" %
|
| 468 |
+
line)
|
| 469 |
+
self.shell.showtraceback()
|
| 470 |
+
if not self.interact:
|
| 471 |
+
self.exit(1)
|
| 472 |
+
|
| 473 |
+
# Like Python itself, ignore the second if the first of these is present
|
| 474 |
+
elif self.file_to_run:
|
| 475 |
+
fname = self.file_to_run
|
| 476 |
+
if os.path.isdir(fname):
|
| 477 |
+
fname = os.path.join(fname, "__main__.py")
|
| 478 |
+
if not os.path.exists(fname):
|
| 479 |
+
self.log.warning("File '%s' doesn't exist", fname)
|
| 480 |
+
if not self.interact:
|
| 481 |
+
self.exit(2)
|
| 482 |
+
try:
|
| 483 |
+
self._exec_file(fname, shell_futures=True)
|
| 484 |
+
except:
|
| 485 |
+
self.shell.showtraceback(tb_offset=4)
|
| 486 |
+
if not self.interact:
|
| 487 |
+
self.exit(1)
|
| 488 |
+
|
| 489 |
+
def _run_module(self):
|
| 490 |
+
"""Run module specified at the command-line."""
|
| 491 |
+
if self.module_to_run:
|
| 492 |
+
# Make sure that the module gets a proper sys.argv as if it were
|
| 493 |
+
# run using `python -m`.
|
| 494 |
+
save_argv = sys.argv
|
| 495 |
+
sys.argv = [sys.executable] + self.extra_args
|
| 496 |
+
try:
|
| 497 |
+
self.shell.safe_run_module(self.module_to_run,
|
| 498 |
+
self.shell.user_ns)
|
| 499 |
+
finally:
|
| 500 |
+
sys.argv = save_argv
|
lib/python3.12/site-packages/IPython/core/splitinput.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Simple utility for splitting user input. This is used by both inputsplitter and
|
| 3 |
+
prefilter.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
# -----------------------------------------------------------------------------
|
| 7 |
+
# Imports
|
| 8 |
+
# -----------------------------------------------------------------------------
|
| 9 |
+
|
| 10 |
+
import re
|
| 11 |
+
import sys
|
| 12 |
+
import warnings
|
| 13 |
+
|
| 14 |
+
from IPython.core.oinspect import OInfo
|
| 15 |
+
|
| 16 |
+
# -----------------------------------------------------------------------------
|
| 17 |
+
# Main function
|
| 18 |
+
# -----------------------------------------------------------------------------
|
| 19 |
+
|
| 20 |
+
# RegExp for splitting line contents into pre-char//first word-method//rest.
|
| 21 |
+
# For clarity, each group in on one line.
|
| 22 |
+
|
| 23 |
+
# WARNING: update the regexp if the escapes in interactiveshell are changed, as
|
| 24 |
+
# they are hardwired in.
|
| 25 |
+
|
| 26 |
+
# Although it's not solely driven by the regex, note that:
|
| 27 |
+
# ,;/% only trigger if they are the first character on the line
|
| 28 |
+
# ! and !! trigger if they are first char(s) *or* follow an indent
|
| 29 |
+
# ? triggers as first or last char.
|
| 30 |
+
|
| 31 |
+
line_split = re.compile(
|
| 32 |
+
r"""
|
| 33 |
+
^(\s*) # any leading space
|
| 34 |
+
([,;/%]|!!?|\?\??)? # escape character or characters
|
| 35 |
+
\s*(%{0,2}[\w\.\*]*) # function/method, possibly with leading %
|
| 36 |
+
# to correctly treat things like '?%magic'
|
| 37 |
+
(.*?$|$) # rest of line
|
| 38 |
+
""",
|
| 39 |
+
re.VERBOSE,
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def split_user_input(
|
| 44 |
+
line: str, pattern: re.Pattern[str] | None = None
|
| 45 |
+
) -> tuple[str, str, str, str]:
|
| 46 |
+
"""Split user input into initial whitespace, escape character, function part
|
| 47 |
+
and the rest.
|
| 48 |
+
"""
|
| 49 |
+
assert isinstance(line, str)
|
| 50 |
+
|
| 51 |
+
if pattern is None:
|
| 52 |
+
pattern = line_split
|
| 53 |
+
match = pattern.match(line)
|
| 54 |
+
if not match:
|
| 55 |
+
# print("match failed for line '%s'" % line)
|
| 56 |
+
try:
|
| 57 |
+
ifun, the_rest = line.split(None, 1)
|
| 58 |
+
except ValueError:
|
| 59 |
+
# print("split failed for line '%s'" % line)
|
| 60 |
+
ifun, the_rest = line, ""
|
| 61 |
+
pre = re.match(r"^(\s*)(.*)", line).groups()[0]
|
| 62 |
+
esc = ""
|
| 63 |
+
else:
|
| 64 |
+
pre, esc, ifun, the_rest = match.groups()
|
| 65 |
+
|
| 66 |
+
# print('line:<%s>' % line) # dbg
|
| 67 |
+
# print('pre <%s> ifun <%s> rest <%s>' % (pre,ifun.strip(),the_rest)) # dbg
|
| 68 |
+
return pre, esc or "", ifun.strip(), the_rest
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class LineInfo:
|
| 72 |
+
"""A single line of input and associated info.
|
| 73 |
+
|
| 74 |
+
Includes the following as properties:
|
| 75 |
+
|
| 76 |
+
line
|
| 77 |
+
The original, raw line
|
| 78 |
+
|
| 79 |
+
continue_prompt
|
| 80 |
+
Is this line a continuation in a sequence of multiline input?
|
| 81 |
+
|
| 82 |
+
pre
|
| 83 |
+
Any leading whitespace.
|
| 84 |
+
|
| 85 |
+
esc
|
| 86 |
+
The escape character(s) in pre or the empty string if there isn't one.
|
| 87 |
+
Note that '!!' and '??' are possible values for esc. Otherwise it will
|
| 88 |
+
always be a single character.
|
| 89 |
+
|
| 90 |
+
ifun
|
| 91 |
+
The 'function part', which is basically the maximal initial sequence
|
| 92 |
+
of valid python identifiers and the '.' character. This is what is
|
| 93 |
+
checked for alias and magic transformations, used for auto-calling,
|
| 94 |
+
etc. In contrast to Python identifiers, it may start with "%" and contain
|
| 95 |
+
"*".
|
| 96 |
+
|
| 97 |
+
the_rest
|
| 98 |
+
Everything else on the line.
|
| 99 |
+
|
| 100 |
+
raw_the_rest
|
| 101 |
+
the_rest without whitespace stripped.
|
| 102 |
+
"""
|
| 103 |
+
|
| 104 |
+
line: str
|
| 105 |
+
continue_prompt: bool
|
| 106 |
+
pre: str
|
| 107 |
+
esc: str
|
| 108 |
+
ifun: str
|
| 109 |
+
raw_the_rest: str
|
| 110 |
+
the_rest: str
|
| 111 |
+
pre_char: str
|
| 112 |
+
pre_whitespace: str
|
| 113 |
+
|
| 114 |
+
def __init__(self, line: str, continue_prompt: bool = False) -> None:
|
| 115 |
+
assert isinstance(line, str)
|
| 116 |
+
self.line = line
|
| 117 |
+
self.continue_prompt = continue_prompt
|
| 118 |
+
self.pre, self.esc, self.ifun, self.raw_the_rest = split_user_input(line)
|
| 119 |
+
self.the_rest = self.raw_the_rest.lstrip()
|
| 120 |
+
|
| 121 |
+
self.pre_char = self.pre.strip()
|
| 122 |
+
if self.pre_char:
|
| 123 |
+
self.pre_whitespace = "" # No whitespace allowed before esc chars
|
| 124 |
+
else:
|
| 125 |
+
self.pre_whitespace = self.pre
|
| 126 |
+
|
| 127 |
+
def ofind(self, ip) -> OInfo:
|
| 128 |
+
"""Do a full, attribute-walking lookup of the ifun in the various
|
| 129 |
+
namespaces for the given IPython InteractiveShell instance.
|
| 130 |
+
|
| 131 |
+
Return a dict with keys: {found, obj, ospace, ismagic}
|
| 132 |
+
|
| 133 |
+
Note: can cause state changes because of calling getattr, but should
|
| 134 |
+
only be run if autocall is on and if the line hasn't matched any
|
| 135 |
+
other, less dangerous handlers.
|
| 136 |
+
|
| 137 |
+
Does cache the results of the call, so can be called multiple times
|
| 138 |
+
without worrying about *further* damaging state.
|
| 139 |
+
|
| 140 |
+
.. deprecated:: 9.8
|
| 141 |
+
Use ``shell._ofind(line_info.ifun)`` directly instead.
|
| 142 |
+
"""
|
| 143 |
+
warnings.warn(
|
| 144 |
+
"LineInfo.ofind() is deprecated since IPython 9.9. "
|
| 145 |
+
"Use shell._ofind(line_info.ifun) directly instead.",
|
| 146 |
+
DeprecationWarning,
|
| 147 |
+
stacklevel=2,
|
| 148 |
+
)
|
| 149 |
+
return ip._ofind(self.ifun)
|
| 150 |
+
|
| 151 |
+
def __str__(self) -> str:
|
| 152 |
+
return "LineInfo [%s|%s|%s|%s]" % (self.pre, self.esc, self.ifun, self.the_rest)
|
| 153 |
+
|
| 154 |
+
def __repr__(self) -> str:
|
| 155 |
+
return "<" + str(self) + ">"
|
lib/python3.12/site-packages/IPython/core/tips.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
import os
|
| 3 |
+
from random import choice
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
_tips: Any = {
|
| 7 |
+
# (month, day)
|
| 8 |
+
"every_year": {
|
| 9 |
+
(1, 1): "Happy new year!",
|
| 10 |
+
# European time:
|
| 11 |
+
# [2/8/25, 23:28:24] Fernando Perez: Hi! Yes, this was my first public
|
| 12 |
+
# announcement:
|
| 13 |
+
# [2/8/25, 23:28:25] Fernando Perez:
|
| 14 |
+
# https://mail.python.org/pipermail/python-list/2001-December/093408.html
|
| 15 |
+
# [2/8/25, 23:28:55] Fernando Perez: All that started two months earlier
|
| 16 |
+
# - in October 2001 I read this article:
|
| 17 |
+
# [2/8/25, 23:28:55] Fernando Perez:
|
| 18 |
+
# https://web.archive.org/web/20011202000624/http://www.onlamp.com/pub/a/python/2001/10/11/pythonnews.html
|
| 19 |
+
# [2/8/25, 23:29:05] Fernando Perez: Which is also archived here:
|
| 20 |
+
# [2/8/25, 23:29:05] Fernando Perez:
|
| 21 |
+
# https://docstore.mik.ua/orelly/weblinux2/orn/interactive_python.html
|
| 22 |
+
# [2/8/25, 23:29:48] Fernando Perez: That article put me on the trail of
|
| 23 |
+
# LazyPython, and I also found out (can’t remember where) about IPP
|
| 24 |
+
# (Interactive Python Prompt), another similar projecd by Janko Hauser.
|
| 25 |
+
# [2/8/25, 23:30:20] Fernando Perez: A also read an article around that
|
| 26 |
+
# time, about new features in Python 2.0, which spoke of how
|
| 27 |
+
# sys.displayhook could be programmed to call any object you wanted.
|
| 28 |
+
# [2/8/25, 23:31:01] Fernando Perez: Those things together gave me the
|
| 29 |
+
# idea of implementing a stateful object, the “IPython Prompt”, that
|
| 30 |
+
# could store a cache of old results, Mathematica-style, and that could
|
| 31 |
+
# have all kinds of other useful tricks up its sleeve.
|
| 32 |
+
# [2/8/25, 23:31:17] Fernando Perez: I can’t remember if I did the
|
| 33 |
+
# prompt stuff first and then read about LazyPython/IPP.
|
| 34 |
+
# [2/8/25, 23:31:41] Fernando Perez: I do know that, implementation
|
| 35 |
+
# wise, at first I just did the tiny IPython 0.0.1 that I posted much
|
| 36 |
+
# later on github as a gist:
|
| 37 |
+
# [2/8/25, 23:31:55] Fernando Perez:
|
| 38 |
+
# https://gist.github.com/fperez/1579699
|
| 39 |
+
# [2/8/25, 23:32:03] Fernando Perez: But I only shared that publicly
|
| 40 |
+
# much later.
|
| 41 |
+
# [2/8/25, 23:33:19] Fernando Perez: I did find out about IPP/LazyPython
|
| 42 |
+
# sometime in October, contacted Janko and Nathan who told me to use
|
| 43 |
+
# their code at will but said they were busy with other things, and got
|
| 44 |
+
# cranking for a few mad weeks on what became the IPython 0.2.0 that I
|
| 45 |
+
# posted about in that comp.lang.python thread of December 2001.
|
| 46 |
+
# [2/8/25, 23:33:52] Fernando Perez: That period from Oct 11 to Dec 9
|
| 47 |
+
# 2001 was maniacal coding, with very little sleep 🙂
|
| 48 |
+
(
|
| 49 |
+
10,
|
| 50 |
+
11,
|
| 51 |
+
): "IPython's first line of code was written {} years ago by Fernando Pérez".format(
|
| 52 |
+
datetime.now().year - 2001
|
| 53 |
+
),
|
| 54 |
+
(
|
| 55 |
+
12,
|
| 56 |
+
9,
|
| 57 |
+
): "IPython 0.0.2 was announced {} years ago: https://mail.python.org/pipermail/python-list/2001-December/093408.html".format(
|
| 58 |
+
datetime.now().year - 2001
|
| 59 |
+
),
|
| 60 |
+
(
|
| 61 |
+
3,
|
| 62 |
+
8,
|
| 63 |
+
): "Today is International Women's Day: https://www.internationalwomensday.com/",
|
| 64 |
+
(
|
| 65 |
+
3,
|
| 66 |
+
31,
|
| 67 |
+
): "Happy International Transgender Day of Visibility! You are valid. You matter. https://en.wikipedia.org/wiki/International_Transgender_Day_of_Visibility",
|
| 68 |
+
},
|
| 69 |
+
"random": [
|
| 70 |
+
"Use `F2` or %edit with no arguments to open an empty editor with a temporary file.",
|
| 71 |
+
"Run your doctests from within IPython for development and debugging. The special %doctest_mode command toggles a mode where the prompt, output and exceptions display matches as closely as possible that of the default Python interpreter.",
|
| 72 |
+
"You can use `files = !ls *.png`",
|
| 73 |
+
"Use the IPython.lib.demo.Demo class to load any Python script as an interactive demo.",
|
| 74 |
+
"Put a ';' at the end of a line to suppress the printing of output.",
|
| 75 |
+
"You can use Ctrl-O to force a new line in terminal IPython",
|
| 76 |
+
"Use `object?` to see the help on `object`, `object??` to view its source",
|
| 77 |
+
"`?` alone on a line will brings up IPython's help",
|
| 78 |
+
"You can use `%hist` to view history, see the options with `%history?`",
|
| 79 |
+
"You can change the editing mode of IPython to behave more like vi, or emacs.",
|
| 80 |
+
"IPython 9.0+ has hooks to integrate AI/LLM completions.",
|
| 81 |
+
"Use `%timeit` or `%%timeit`, and the `-r`, `-n`, and `-o` options to easily profile your code.",
|
| 82 |
+
"Use `ipython --help-all | less` to view all the IPython configuration options.",
|
| 83 |
+
"Use `--theme`, or the `%colors` magic to change IPython's themes and colors.",
|
| 84 |
+
"The `%timeit` magic has a `-o` flag, which returns the results, making it easy to plot. See `%timeit?`.",
|
| 85 |
+
],
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
if os.name == "nt":
|
| 89 |
+
_tips["random"].extend(
|
| 90 |
+
[
|
| 91 |
+
"We can't show you all tips on Windows as sometimes Unicode characters crash the Windows console, please help us debug it."
|
| 92 |
+
]
|
| 93 |
+
)
|
| 94 |
+
# unicode may crash windows console, so we filter out tips with non-ASCII characters.
|
| 95 |
+
_tips["every_year"] = {
|
| 96 |
+
k: v
|
| 97 |
+
for k, v in _tips["every_year"].items()
|
| 98 |
+
if all(ord(char) < 128 for char in v)
|
| 99 |
+
}
|
| 100 |
+
else:
|
| 101 |
+
_tips["random"].extend(
|
| 102 |
+
[
|
| 103 |
+
"You can use LaTeX or Unicode completion, `\\alpha<tab>` will insert the α symbol.",
|
| 104 |
+
"You can find how to type a LaTeX symbol by back-completing it, eg `\\θ<tab>` will expand to `\\theta`.",
|
| 105 |
+
"You can find how to type a Unicode symbol by back-completing it, eg `\\Ⅷ<tab>` will expand to `\\ROMAN NUMERAL EIGHT`.",
|
| 106 |
+
"IPython supports combining unicode identifiers, eg F\\vec<tab> will become F⃗, useful for physics equations. Play with \\dot \\ddot and others.",
|
| 107 |
+
]
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
# Check if argcomplete is installed and add tip
|
| 111 |
+
try:
|
| 112 |
+
import argcomplete
|
| 113 |
+
|
| 114 |
+
_tips["random"].append(
|
| 115 |
+
"Run `activate-global-python-argcomplete` from your shell to enable CLI completion for IPython"
|
| 116 |
+
)
|
| 117 |
+
except ModuleNotFoundError:
|
| 118 |
+
pass
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def pick_tip() -> str:
|
| 122 |
+
current_date = datetime.now()
|
| 123 |
+
month, day = current_date.month, current_date.day
|
| 124 |
+
|
| 125 |
+
if (month, day) in _tips["every_year"]:
|
| 126 |
+
return _tips["every_year"][(month, day)]
|
| 127 |
+
|
| 128 |
+
return choice(_tips["random"])
|
lib/python3.12/site-packages/IPython/core/ultratb.py
ADDED
|
@@ -0,0 +1,1263 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Verbose and colourful traceback formatting.
|
| 3 |
+
|
| 4 |
+
**ColorTB**
|
| 5 |
+
|
| 6 |
+
I've always found it a bit hard to visually parse tracebacks in Python. The
|
| 7 |
+
ColorTB class is a solution to that problem. It colors the different parts of a
|
| 8 |
+
traceback in a manner similar to what you would expect from a syntax-highlighting
|
| 9 |
+
text editor.
|
| 10 |
+
|
| 11 |
+
Installation instructions for ColorTB::
|
| 12 |
+
|
| 13 |
+
import sys,ultratb
|
| 14 |
+
sys.excepthook = ultratb.ColorTB()
|
| 15 |
+
|
| 16 |
+
**VerboseTB**
|
| 17 |
+
|
| 18 |
+
I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
|
| 19 |
+
of useful info when a traceback occurs. Ping originally had it spit out HTML
|
| 20 |
+
and intended it for CGI programmers, but why should they have all the fun? I
|
| 21 |
+
altered it to spit out colored text to the terminal. It's a bit overwhelming,
|
| 22 |
+
but kind of neat, and maybe useful for long-running programs that you believe
|
| 23 |
+
are bug-free. If a crash *does* occur in that type of program you want details.
|
| 24 |
+
Give it a shot--you'll love it or you'll hate it.
|
| 25 |
+
|
| 26 |
+
.. note::
|
| 27 |
+
|
| 28 |
+
The Verbose mode prints the variables currently visible where the exception
|
| 29 |
+
happened (shortening their strings if too long). This can potentially be
|
| 30 |
+
very slow, if you happen to have a huge data structure whose string
|
| 31 |
+
representation is complex to compute. Your computer may appear to freeze for
|
| 32 |
+
a while with cpu usage at 100%. If this occurs, you can cancel the traceback
|
| 33 |
+
with Ctrl-C (maybe hitting it more than once).
|
| 34 |
+
|
| 35 |
+
If you encounter this kind of situation often, you may want to use the
|
| 36 |
+
Verbose_novars mode instead of the regular Verbose, which avoids formatting
|
| 37 |
+
variables (but otherwise includes the information and context given by
|
| 38 |
+
Verbose).
|
| 39 |
+
|
| 40 |
+
.. note::
|
| 41 |
+
|
| 42 |
+
The verbose mode print all variables in the stack, which means it can
|
| 43 |
+
potentially leak sensitive information like access keys, or unencrypted
|
| 44 |
+
password.
|
| 45 |
+
|
| 46 |
+
Installation instructions for VerboseTB::
|
| 47 |
+
|
| 48 |
+
import sys,ultratb
|
| 49 |
+
sys.excepthook = ultratb.VerboseTB()
|
| 50 |
+
|
| 51 |
+
Note: Much of the code in this module was lifted verbatim from the standard
|
| 52 |
+
library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
Inheritance diagram:
|
| 56 |
+
|
| 57 |
+
.. inheritance-diagram:: IPython.core.ultratb
|
| 58 |
+
:parts: 3
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
# *****************************************************************************
|
| 62 |
+
# Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
|
| 63 |
+
# Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
|
| 64 |
+
#
|
| 65 |
+
# Distributed under the terms of the BSD License. The full license is in
|
| 66 |
+
# the file COPYING, distributed as part of this software.
|
| 67 |
+
# *****************************************************************************
|
| 68 |
+
|
| 69 |
+
import functools
|
| 70 |
+
import inspect
|
| 71 |
+
import linecache
|
| 72 |
+
import sys
|
| 73 |
+
import time
|
| 74 |
+
import traceback
|
| 75 |
+
import types
|
| 76 |
+
import warnings
|
| 77 |
+
from collections.abc import Sequence
|
| 78 |
+
from types import TracebackType
|
| 79 |
+
from typing import Any, List, Optional, Tuple
|
| 80 |
+
from collections.abc import Callable
|
| 81 |
+
|
| 82 |
+
import stack_data
|
| 83 |
+
from pygments.formatters.terminal256 import Terminal256Formatter
|
| 84 |
+
from pygments.token import Token
|
| 85 |
+
|
| 86 |
+
from IPython import get_ipython
|
| 87 |
+
from IPython.utils import path as util_path
|
| 88 |
+
from IPython.utils import py3compat
|
| 89 |
+
from IPython.utils.PyColorize import Parser, Theme, TokenStream, theme_table
|
| 90 |
+
from IPython.utils.terminal import get_terminal_size
|
| 91 |
+
|
| 92 |
+
from .display_trap import DisplayTrap
|
| 93 |
+
from .doctb import DocTB
|
| 94 |
+
from .tbtools import (
|
| 95 |
+
FrameInfo,
|
| 96 |
+
TBTools,
|
| 97 |
+
_format_traceback_lines,
|
| 98 |
+
_safe_string,
|
| 99 |
+
_simple_format_traceback_lines,
|
| 100 |
+
_tokens_filename,
|
| 101 |
+
eqrepr,
|
| 102 |
+
get_line_number_of_frame,
|
| 103 |
+
nullrepr,
|
| 104 |
+
text_repr,
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
# Globals
|
| 108 |
+
# amount of space to put line numbers before verbose tracebacks
|
| 109 |
+
INDENT_SIZE = 8
|
| 110 |
+
|
| 111 |
+
# When files are too long do not use stackdata to get frames.
|
| 112 |
+
# it is too long.
|
| 113 |
+
FAST_THRESHOLD = 10_000
|
| 114 |
+
|
| 115 |
+
# ---------------------------------------------------------------------------
|
| 116 |
+
class ListTB(TBTools):
|
| 117 |
+
"""Print traceback information from a traceback list, with optional color.
|
| 118 |
+
|
| 119 |
+
Calling requires 3 arguments: (etype, evalue, elist)
|
| 120 |
+
as would be obtained by::
|
| 121 |
+
|
| 122 |
+
etype, evalue, tb = sys.exc_info()
|
| 123 |
+
if tb:
|
| 124 |
+
elist = traceback.extract_tb(tb)
|
| 125 |
+
else:
|
| 126 |
+
elist = None
|
| 127 |
+
|
| 128 |
+
It can thus be used by programs which need to process the traceback before
|
| 129 |
+
printing (such as console replacements based on the code module from the
|
| 130 |
+
standard library).
|
| 131 |
+
|
| 132 |
+
Because they are meant to be called without a full traceback (only a
|
| 133 |
+
list), instances of this class can't call the interactive pdb debugger."""
|
| 134 |
+
|
| 135 |
+
def __call__(
|
| 136 |
+
self,
|
| 137 |
+
etype: type[BaseException],
|
| 138 |
+
evalue: BaseException | None,
|
| 139 |
+
etb: TracebackType | None,
|
| 140 |
+
) -> None:
|
| 141 |
+
self.ostream.flush()
|
| 142 |
+
self.ostream.write(self.text(etype, evalue, etb))
|
| 143 |
+
self.ostream.write("\n")
|
| 144 |
+
|
| 145 |
+
def _extract_tb(self, tb: TracebackType | None) -> traceback.StackSummary | None:
|
| 146 |
+
if tb:
|
| 147 |
+
return traceback.extract_tb(tb)
|
| 148 |
+
else:
|
| 149 |
+
return None
|
| 150 |
+
|
| 151 |
+
def structured_traceback(
|
| 152 |
+
self,
|
| 153 |
+
etype: type,
|
| 154 |
+
evalue: Optional[BaseException],
|
| 155 |
+
etb: Optional[TracebackType] = None,
|
| 156 |
+
tb_offset: Optional[int] = None,
|
| 157 |
+
context: int = 5,
|
| 158 |
+
) -> list[str]:
|
| 159 |
+
"""Return a color formatted string with the traceback info.
|
| 160 |
+
|
| 161 |
+
Parameters
|
| 162 |
+
----------
|
| 163 |
+
etype : exception type
|
| 164 |
+
Type of the exception raised.
|
| 165 |
+
evalue : object
|
| 166 |
+
Data stored in the exception
|
| 167 |
+
etb : list | TracebackType | None
|
| 168 |
+
If list: List of frames, see class docstring for details.
|
| 169 |
+
If Traceback: Traceback of the exception.
|
| 170 |
+
tb_offset : int, optional
|
| 171 |
+
Number of frames in the traceback to skip. If not given, the
|
| 172 |
+
instance evalue is used (set in constructor).
|
| 173 |
+
context : int, optional
|
| 174 |
+
Number of lines of context information to print.
|
| 175 |
+
|
| 176 |
+
Returns
|
| 177 |
+
-------
|
| 178 |
+
String with formatted exception.
|
| 179 |
+
"""
|
| 180 |
+
# This is a workaround to get chained_exc_ids in recursive calls
|
| 181 |
+
# etb should not be a tuple if structured_traceback is not recursive
|
| 182 |
+
if isinstance(etb, tuple):
|
| 183 |
+
etb, chained_exc_ids = etb
|
| 184 |
+
else:
|
| 185 |
+
chained_exc_ids = set()
|
| 186 |
+
elist: list[Any]
|
| 187 |
+
if isinstance(etb, list):
|
| 188 |
+
elist = etb
|
| 189 |
+
elif etb is not None:
|
| 190 |
+
elist = self._extract_tb(etb) # type: ignore[assignment]
|
| 191 |
+
else:
|
| 192 |
+
elist = []
|
| 193 |
+
tb_offset = self.tb_offset if tb_offset is None else tb_offset
|
| 194 |
+
assert isinstance(tb_offset, int)
|
| 195 |
+
out_list: list[str] = []
|
| 196 |
+
if elist:
|
| 197 |
+
if tb_offset and len(elist) > tb_offset:
|
| 198 |
+
elist = elist[tb_offset:]
|
| 199 |
+
|
| 200 |
+
out_list.append(
|
| 201 |
+
theme_table[self._theme_name].format(
|
| 202 |
+
[
|
| 203 |
+
(Token, "Traceback"),
|
| 204 |
+
(Token, " "),
|
| 205 |
+
(Token.NormalEm, "(most recent call last)"),
|
| 206 |
+
(Token, ":"),
|
| 207 |
+
(Token, "\n"),
|
| 208 |
+
]
|
| 209 |
+
),
|
| 210 |
+
)
|
| 211 |
+
out_list.extend(self._format_list(elist))
|
| 212 |
+
# The exception info should be a single entry in the list.
|
| 213 |
+
lines = "".join(self._format_exception_only(etype, evalue))
|
| 214 |
+
out_list.append(lines)
|
| 215 |
+
|
| 216 |
+
# Find chained exceptions if we have a traceback (not for exception-only mode)
|
| 217 |
+
if etb is not None:
|
| 218 |
+
exception = self.get_parts_of_chained_exception(evalue)
|
| 219 |
+
|
| 220 |
+
if exception and (id(exception[1]) not in chained_exc_ids):
|
| 221 |
+
chained_exception_message: list[str] = (
|
| 222 |
+
self.prepare_chained_exception_message(evalue.__cause__)[0]
|
| 223 |
+
if evalue is not None
|
| 224 |
+
else [""]
|
| 225 |
+
)
|
| 226 |
+
etype, evalue, etb = exception
|
| 227 |
+
# Trace exception to avoid infinite 'cause' loop
|
| 228 |
+
chained_exc_ids.add(id(exception[1]))
|
| 229 |
+
chained_exceptions_tb_offset = 0
|
| 230 |
+
ol1 = self.structured_traceback(
|
| 231 |
+
etype,
|
| 232 |
+
evalue,
|
| 233 |
+
(etb, chained_exc_ids), # type: ignore[arg-type]
|
| 234 |
+
chained_exceptions_tb_offset,
|
| 235 |
+
context,
|
| 236 |
+
)
|
| 237 |
+
ol2 = chained_exception_message
|
| 238 |
+
|
| 239 |
+
out_list = ol1 + ol2 + out_list
|
| 240 |
+
|
| 241 |
+
return out_list
|
| 242 |
+
|
| 243 |
+
def _format_list(self, extracted_list: list[Any]) -> list[str]:
|
| 244 |
+
"""Format a list of traceback entry tuples for printing.
|
| 245 |
+
|
| 246 |
+
Given a list of tuples as returned by extract_tb() or
|
| 247 |
+
extract_stack(), return a list of strings ready for printing.
|
| 248 |
+
Each string in the resulting list corresponds to the item with the
|
| 249 |
+
same index in the argument list. Each string ends in a newline;
|
| 250 |
+
the strings may contain internal newlines as well, for those items
|
| 251 |
+
whose source text line is not None.
|
| 252 |
+
|
| 253 |
+
Lifted almost verbatim from traceback.py
|
| 254 |
+
"""
|
| 255 |
+
|
| 256 |
+
output_list = []
|
| 257 |
+
for ind, (filename, lineno, name, line) in enumerate(extracted_list):
|
| 258 |
+
# Will emphasize the last entry
|
| 259 |
+
em = True if ind == len(extracted_list) - 1 else False
|
| 260 |
+
|
| 261 |
+
item = theme_table[self._theme_name].format(
|
| 262 |
+
[(Token.NormalEm if em else Token.Normal, " ")]
|
| 263 |
+
+ _tokens_filename(em, filename, lineno=lineno)
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
# This seem to be only in xmode plain (%run sinpleer), investigate why not share with verbose.
|
| 267 |
+
# look at _tokens_filename in forma_record.
|
| 268 |
+
if name != "<module>":
|
| 269 |
+
item += theme_table[self._theme_name].format(
|
| 270 |
+
[
|
| 271 |
+
(Token.NormalEm if em else Token.Normal, " in "),
|
| 272 |
+
(Token.TB.NameEm if em else Token.TB.Name, name),
|
| 273 |
+
]
|
| 274 |
+
)
|
| 275 |
+
item += theme_table[self._theme_name].format(
|
| 276 |
+
[(Token.NormalEm if em else Token, "\n")]
|
| 277 |
+
)
|
| 278 |
+
if line:
|
| 279 |
+
item += theme_table[self._theme_name].format(
|
| 280 |
+
[
|
| 281 |
+
(Token.Line if em else Token, " "),
|
| 282 |
+
(Token.Line if em else Token, line.strip()),
|
| 283 |
+
(Token, "\n"),
|
| 284 |
+
]
|
| 285 |
+
)
|
| 286 |
+
output_list.append(item)
|
| 287 |
+
|
| 288 |
+
return output_list
|
| 289 |
+
|
| 290 |
+
def _format_exception_only(
|
| 291 |
+
self, etype: type[BaseException], value: BaseException | None
|
| 292 |
+
) -> list[str]:
|
| 293 |
+
"""Format the exception part of a traceback.
|
| 294 |
+
|
| 295 |
+
The arguments are the exception type and value such as given by
|
| 296 |
+
sys.exc_info()[:2]. The return value is a list of strings, each ending
|
| 297 |
+
in a newline. Normally, the list contains a single string; however,
|
| 298 |
+
for SyntaxError exceptions, it contains several lines that (when
|
| 299 |
+
printed) display detailed information about where the syntax error
|
| 300 |
+
occurred. The message indicating which exception occurred is the
|
| 301 |
+
always last string in the list.
|
| 302 |
+
|
| 303 |
+
Also lifted nearly verbatim from traceback.py
|
| 304 |
+
"""
|
| 305 |
+
have_filedata = False
|
| 306 |
+
output_list = []
|
| 307 |
+
stype_tokens = [(Token.ExcName, etype.__name__)]
|
| 308 |
+
stype: str = theme_table[self._theme_name].format(stype_tokens)
|
| 309 |
+
if value is None:
|
| 310 |
+
# Not sure if this can still happen in Python 2.6 and above
|
| 311 |
+
output_list.append(stype + "\n")
|
| 312 |
+
else:
|
| 313 |
+
if issubclass(etype, SyntaxError):
|
| 314 |
+
assert hasattr(value, "filename")
|
| 315 |
+
assert hasattr(value, "lineno")
|
| 316 |
+
assert hasattr(value, "text")
|
| 317 |
+
assert hasattr(value, "offset")
|
| 318 |
+
assert hasattr(value, "msg")
|
| 319 |
+
have_filedata = True
|
| 320 |
+
if not value.filename:
|
| 321 |
+
value.filename = "<string>"
|
| 322 |
+
if value.lineno:
|
| 323 |
+
lineno = value.lineno
|
| 324 |
+
textline = linecache.getline(value.filename, value.lineno)
|
| 325 |
+
else:
|
| 326 |
+
lineno = "unknown"
|
| 327 |
+
textline = ""
|
| 328 |
+
output_list.append(
|
| 329 |
+
theme_table[self._theme_name].format(
|
| 330 |
+
[(Token, " ")]
|
| 331 |
+
+ _tokens_filename(
|
| 332 |
+
True,
|
| 333 |
+
value.filename,
|
| 334 |
+
lineno=(None if lineno == "unknown" else lineno),
|
| 335 |
+
)
|
| 336 |
+
+ [(Token, "\n")]
|
| 337 |
+
)
|
| 338 |
+
)
|
| 339 |
+
if textline == "":
|
| 340 |
+
# sep 2025:
|
| 341 |
+
# textline = py3compat.cast_unicode(value.text, "utf-8")
|
| 342 |
+
if value.text is None:
|
| 343 |
+
textline = ""
|
| 344 |
+
else:
|
| 345 |
+
assert isinstance(value.text, str)
|
| 346 |
+
textline = value.text
|
| 347 |
+
|
| 348 |
+
if textline is not None:
|
| 349 |
+
i = 0
|
| 350 |
+
while i < len(textline) and textline[i].isspace():
|
| 351 |
+
i += 1
|
| 352 |
+
output_list.append(
|
| 353 |
+
theme_table[self._theme_name].format(
|
| 354 |
+
[
|
| 355 |
+
(Token.Line, " "),
|
| 356 |
+
(Token.Line, textline.strip()),
|
| 357 |
+
(Token, "\n"),
|
| 358 |
+
]
|
| 359 |
+
)
|
| 360 |
+
)
|
| 361 |
+
if value.offset is not None:
|
| 362 |
+
s = " "
|
| 363 |
+
for c in textline[i : value.offset - 1]:
|
| 364 |
+
if c.isspace():
|
| 365 |
+
s += c
|
| 366 |
+
else:
|
| 367 |
+
s += " "
|
| 368 |
+
output_list.append(
|
| 369 |
+
theme_table[self._theme_name].format(
|
| 370 |
+
[(Token.Caret, s + "^"), (Token, "\n")]
|
| 371 |
+
)
|
| 372 |
+
)
|
| 373 |
+
s = value.msg
|
| 374 |
+
else:
|
| 375 |
+
s = self._some_str(value)
|
| 376 |
+
if s:
|
| 377 |
+
output_list.append(
|
| 378 |
+
theme_table[self._theme_name].format(
|
| 379 |
+
stype_tokens
|
| 380 |
+
+ [
|
| 381 |
+
(Token.ExcName, ":"),
|
| 382 |
+
(Token, " "),
|
| 383 |
+
(Token, s),
|
| 384 |
+
(Token, "\n"),
|
| 385 |
+
]
|
| 386 |
+
)
|
| 387 |
+
)
|
| 388 |
+
else:
|
| 389 |
+
output_list.append("%s\n" % stype)
|
| 390 |
+
|
| 391 |
+
# PEP-678 notes
|
| 392 |
+
output_list.extend(f"{x}\n" for x in getattr(value, "__notes__", []))
|
| 393 |
+
|
| 394 |
+
# sync with user hooks
|
| 395 |
+
if have_filedata:
|
| 396 |
+
ipinst = get_ipython()
|
| 397 |
+
if ipinst is not None:
|
| 398 |
+
assert value is not None
|
| 399 |
+
assert hasattr(value, "lineno")
|
| 400 |
+
assert hasattr(value, "filename")
|
| 401 |
+
ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
|
| 402 |
+
|
| 403 |
+
return output_list
|
| 404 |
+
|
| 405 |
+
def get_exception_only(self, etype, value):
|
| 406 |
+
"""Only print the exception type and message, without a traceback.
|
| 407 |
+
|
| 408 |
+
Parameters
|
| 409 |
+
----------
|
| 410 |
+
etype : exception type
|
| 411 |
+
value : exception value
|
| 412 |
+
"""
|
| 413 |
+
return ListTB.structured_traceback(self, etype, value)
|
| 414 |
+
|
| 415 |
+
def show_exception_only(
|
| 416 |
+
self, etype: BaseException | None, evalue: TracebackType | None
|
| 417 |
+
) -> None:
|
| 418 |
+
"""Only print the exception type and message, without a traceback.
|
| 419 |
+
|
| 420 |
+
Parameters
|
| 421 |
+
----------
|
| 422 |
+
etype : exception type
|
| 423 |
+
evalue : exception value
|
| 424 |
+
"""
|
| 425 |
+
# This method needs to use __call__ from *this* class, not the one from
|
| 426 |
+
# a subclass whose signature or behavior may be different
|
| 427 |
+
ostream = self.ostream
|
| 428 |
+
ostream.flush()
|
| 429 |
+
ostream.write("\n".join(self.get_exception_only(etype, evalue)))
|
| 430 |
+
ostream.flush()
|
| 431 |
+
|
| 432 |
+
def _some_str(self, value: Any) -> str:
|
| 433 |
+
# Lifted from traceback.py
|
| 434 |
+
try:
|
| 435 |
+
return str(value)
|
| 436 |
+
except:
|
| 437 |
+
return "<unprintable %s object>" % type(value).__name__
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
_sentinel = object()
|
| 441 |
+
_default = "default"
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
# ----------------------------------------------------------------------------
|
| 445 |
+
class VerboseTB(TBTools):
|
| 446 |
+
"""A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
|
| 447 |
+
of HTML. Requires inspect and pydoc. Crazy, man.
|
| 448 |
+
|
| 449 |
+
Modified version which optionally strips the topmost entries from the
|
| 450 |
+
traceback, to be used with alternate interpreters (because their own code
|
| 451 |
+
would appear in the traceback)."""
|
| 452 |
+
|
| 453 |
+
tb_highlight = "bg:ansiyellow"
|
| 454 |
+
tb_highlight_style = "default"
|
| 455 |
+
|
| 456 |
+
_mode: str
|
| 457 |
+
|
| 458 |
+
def __init__(
|
| 459 |
+
self,
|
| 460 |
+
# TODO: no default ?
|
| 461 |
+
theme_name: str = _default,
|
| 462 |
+
call_pdb: bool = False,
|
| 463 |
+
ostream: Any = None,
|
| 464 |
+
tb_offset: int = 0,
|
| 465 |
+
long_header: bool = False,
|
| 466 |
+
include_vars: bool = True,
|
| 467 |
+
check_cache: Callable[[], None] | None = None,
|
| 468 |
+
debugger_cls: type | None = None,
|
| 469 |
+
*,
|
| 470 |
+
color_scheme: Any = _sentinel,
|
| 471 |
+
):
|
| 472 |
+
"""Specify traceback offset, headers and color scheme.
|
| 473 |
+
|
| 474 |
+
Define how many frames to drop from the tracebacks. Calling it with
|
| 475 |
+
tb_offset=1 allows use of this handler in interpreters which will have
|
| 476 |
+
their own code at the top of the traceback (VerboseTB will first
|
| 477 |
+
remove that frame before printing the traceback info)."""
|
| 478 |
+
if color_scheme is not _sentinel:
|
| 479 |
+
assert isinstance(color_scheme, str)
|
| 480 |
+
theme_name = color_scheme.lower()
|
| 481 |
+
|
| 482 |
+
warnings.warn(
|
| 483 |
+
"color_scheme is deprecated as of IPython 9.0 and replaced by "
|
| 484 |
+
"theme_name (which should be lowercase). As you passed a "
|
| 485 |
+
"color_scheme value I will try to see if I have corresponding "
|
| 486 |
+
"theme.",
|
| 487 |
+
stacklevel=2,
|
| 488 |
+
category=DeprecationWarning,
|
| 489 |
+
)
|
| 490 |
+
|
| 491 |
+
if theme_name != _default:
|
| 492 |
+
warnings.warn(
|
| 493 |
+
"You passed both `theme_name` and `color_scheme` "
|
| 494 |
+
"(deprecated) to VerboseTB constructor. `theme_name` will "
|
| 495 |
+
"be ignored for the time being.",
|
| 496 |
+
stacklevel=2,
|
| 497 |
+
category=DeprecationWarning,
|
| 498 |
+
)
|
| 499 |
+
|
| 500 |
+
if theme_name == _default:
|
| 501 |
+
theme_name = "linux"
|
| 502 |
+
|
| 503 |
+
assert isinstance(theme_name, str)
|
| 504 |
+
super().__init__(
|
| 505 |
+
theme_name=theme_name,
|
| 506 |
+
call_pdb=call_pdb,
|
| 507 |
+
ostream=ostream,
|
| 508 |
+
debugger_cls=debugger_cls,
|
| 509 |
+
)
|
| 510 |
+
self.tb_offset = tb_offset
|
| 511 |
+
self.long_header = long_header
|
| 512 |
+
self.include_vars = include_vars
|
| 513 |
+
# By default we use linecache.checkcache, but the user can provide a
|
| 514 |
+
# different check_cache implementation. This was formerly used by the
|
| 515 |
+
# IPython kernel for interactive code, but is no longer necessary.
|
| 516 |
+
if check_cache is None:
|
| 517 |
+
check_cache = linecache.checkcache
|
| 518 |
+
self.check_cache = check_cache
|
| 519 |
+
|
| 520 |
+
self.skip_hidden = True
|
| 521 |
+
|
| 522 |
+
def format_record(self, frame_info: FrameInfo) -> str:
|
| 523 |
+
"""Format a single stack frame"""
|
| 524 |
+
assert isinstance(frame_info, FrameInfo)
|
| 525 |
+
|
| 526 |
+
if isinstance(frame_info._sd, stack_data.RepeatedFrames):
|
| 527 |
+
return theme_table[self._theme_name].format(
|
| 528 |
+
[
|
| 529 |
+
(Token, " "),
|
| 530 |
+
(
|
| 531 |
+
Token.ExcName,
|
| 532 |
+
"[... skipping similar frames: %s]" % frame_info.description,
|
| 533 |
+
),
|
| 534 |
+
(Token, "\n"),
|
| 535 |
+
]
|
| 536 |
+
)
|
| 537 |
+
|
| 538 |
+
indent: str = " " * INDENT_SIZE
|
| 539 |
+
|
| 540 |
+
assert isinstance(frame_info.lineno, int)
|
| 541 |
+
args, varargs, varkw, locals_ = inspect.getargvalues(frame_info.frame)
|
| 542 |
+
if frame_info.executing is not None:
|
| 543 |
+
func = frame_info.executing.code_qualname()
|
| 544 |
+
else:
|
| 545 |
+
func = "?"
|
| 546 |
+
if func == "<module>":
|
| 547 |
+
call = ""
|
| 548 |
+
else:
|
| 549 |
+
# Decide whether to include variable details or not
|
| 550 |
+
var_repr = eqrepr if self.include_vars else nullrepr
|
| 551 |
+
try:
|
| 552 |
+
scope = inspect.formatargvalues(
|
| 553 |
+
args, varargs, varkw, locals_, formatvalue=var_repr
|
| 554 |
+
)
|
| 555 |
+
assert isinstance(scope, str)
|
| 556 |
+
call = theme_table[self._theme_name].format(
|
| 557 |
+
[(Token, "in "), (Token.VName, func), (Token.ValEm, scope)]
|
| 558 |
+
)
|
| 559 |
+
except KeyError:
|
| 560 |
+
# This happens in situations like errors inside generator
|
| 561 |
+
# expressions, where local variables are listed in the
|
| 562 |
+
# line, but can't be extracted from the frame. I'm not
|
| 563 |
+
# 100% sure this isn't actually a bug in inspect itself,
|
| 564 |
+
# but since there's no info for us to compute with, the
|
| 565 |
+
# best we can do is report the failure and move on. Here
|
| 566 |
+
# we must *not* call any traceback construction again,
|
| 567 |
+
# because that would mess up use of %debug later on. So we
|
| 568 |
+
# simply report the failure and move on. The only
|
| 569 |
+
# limitation will be that this frame won't have locals
|
| 570 |
+
# listed in the call signature. Quite subtle problem...
|
| 571 |
+
# I can't think of a good way to validate this in a unit
|
| 572 |
+
# test, but running a script consisting of:
|
| 573 |
+
# dict( (k,v.strip()) for (k,v) in range(10) )
|
| 574 |
+
# will illustrate the error, if this exception catch is
|
| 575 |
+
# disabled.
|
| 576 |
+
call = theme_table[self._theme_name].format(
|
| 577 |
+
[
|
| 578 |
+
(Token, "in "),
|
| 579 |
+
(Token.VName, func),
|
| 580 |
+
(Token.ValEm, "(***failed resolving arguments***)"),
|
| 581 |
+
]
|
| 582 |
+
)
|
| 583 |
+
|
| 584 |
+
lvals_toks: list[TokenStream] = []
|
| 585 |
+
if self.include_vars:
|
| 586 |
+
try:
|
| 587 |
+
# we likely want to fix stackdata at some point, but
|
| 588 |
+
# still need a workaround.
|
| 589 |
+
fibp = frame_info.variables_in_executing_piece
|
| 590 |
+
for var in fibp:
|
| 591 |
+
lvals_toks.append(
|
| 592 |
+
[
|
| 593 |
+
(Token, var.name),
|
| 594 |
+
(Token, " "),
|
| 595 |
+
(Token.ValEm, "= "),
|
| 596 |
+
(Token.ValEm, repr(var.value)),
|
| 597 |
+
]
|
| 598 |
+
)
|
| 599 |
+
except Exception:
|
| 600 |
+
lvals_toks.append(
|
| 601 |
+
[
|
| 602 |
+
(
|
| 603 |
+
Token,
|
| 604 |
+
"Exception trying to inspect frame. No more locals available.",
|
| 605 |
+
),
|
| 606 |
+
]
|
| 607 |
+
)
|
| 608 |
+
|
| 609 |
+
if frame_info._sd is None:
|
| 610 |
+
# fast fallback if file is too long
|
| 611 |
+
assert frame_info.filename is not None
|
| 612 |
+
level_tokens = [
|
| 613 |
+
(Token.FilenameEm, util_path.compress_user(frame_info.filename)),
|
| 614 |
+
(Token, " "),
|
| 615 |
+
(Token, call),
|
| 616 |
+
(Token, "\n"),
|
| 617 |
+
]
|
| 618 |
+
|
| 619 |
+
_line_format = Parser(theme_name=self._theme_name).format2
|
| 620 |
+
assert isinstance(frame_info.code, types.CodeType)
|
| 621 |
+
first_line: int = frame_info.code.co_firstlineno
|
| 622 |
+
current_line: int = frame_info.lineno
|
| 623 |
+
raw_lines: list[str] = frame_info.raw_lines
|
| 624 |
+
index: int = current_line - first_line
|
| 625 |
+
assert frame_info.context is not None
|
| 626 |
+
if index >= frame_info.context:
|
| 627 |
+
start = max(index - frame_info.context, 0)
|
| 628 |
+
stop = index + frame_info.context
|
| 629 |
+
index = frame_info.context
|
| 630 |
+
else:
|
| 631 |
+
start = 0
|
| 632 |
+
stop = index + frame_info.context
|
| 633 |
+
raw_lines = raw_lines[start:stop]
|
| 634 |
+
|
| 635 |
+
# Jan 2025: may need _line_format(py3ompat.cast_unicode(s))
|
| 636 |
+
raw_color_err = []
|
| 637 |
+
for s in raw_lines:
|
| 638 |
+
formatted, is_error = _line_format(s, "str")
|
| 639 |
+
assert formatted is not None, "format2 should return str when out='str'"
|
| 640 |
+
raw_color_err.append((s, (formatted, is_error)))
|
| 641 |
+
|
| 642 |
+
tb_tokens = _simple_format_traceback_lines(
|
| 643 |
+
current_line,
|
| 644 |
+
index,
|
| 645 |
+
raw_color_err,
|
| 646 |
+
lvals_toks,
|
| 647 |
+
theme=theme_table[self._theme_name],
|
| 648 |
+
)
|
| 649 |
+
_tb_lines: str = theme_table[self._theme_name].format(tb_tokens)
|
| 650 |
+
|
| 651 |
+
return theme_table[self._theme_name].format(level_tokens + tb_tokens)
|
| 652 |
+
else:
|
| 653 |
+
result = theme_table[self._theme_name].format(
|
| 654 |
+
_tokens_filename(True, frame_info.filename, lineno=frame_info.lineno)
|
| 655 |
+
)
|
| 656 |
+
result += ", " if call else ""
|
| 657 |
+
result += f"{call}\n"
|
| 658 |
+
result += theme_table[self._theme_name].format(
|
| 659 |
+
_format_traceback_lines(
|
| 660 |
+
frame_info.lines,
|
| 661 |
+
theme_table[self._theme_name],
|
| 662 |
+
self.has_colors,
|
| 663 |
+
lvals_toks,
|
| 664 |
+
)
|
| 665 |
+
)
|
| 666 |
+
return result
|
| 667 |
+
|
| 668 |
+
def prepare_header(self, etype: str, long_version: bool = False) -> str:
|
| 669 |
+
width = min(75, get_terminal_size()[0])
|
| 670 |
+
if long_version:
|
| 671 |
+
# Header with the exception type, python version, and date
|
| 672 |
+
pyver = "Python " + sys.version.split()[0] + ": " + sys.executable
|
| 673 |
+
date = time.ctime(time.time())
|
| 674 |
+
theme = theme_table[self._theme_name]
|
| 675 |
+
head = theme.format(
|
| 676 |
+
[
|
| 677 |
+
(Token.Topline, theme.symbols["top_line"] * width),
|
| 678 |
+
(Token, "\n"),
|
| 679 |
+
(Token.ExcName, etype),
|
| 680 |
+
(Token, " " * (width - len(etype) - len(pyver))),
|
| 681 |
+
(Token, pyver),
|
| 682 |
+
(Token, "\n"),
|
| 683 |
+
(Token, date.rjust(width)),
|
| 684 |
+
]
|
| 685 |
+
)
|
| 686 |
+
head += (
|
| 687 |
+
"\nA problem occurred executing Python code. Here is the sequence of function"
|
| 688 |
+
"\ncalls leading up to the error, with the most recent (innermost) call last."
|
| 689 |
+
)
|
| 690 |
+
else:
|
| 691 |
+
# Simplified header
|
| 692 |
+
head = theme_table[self._theme_name].format(
|
| 693 |
+
[
|
| 694 |
+
(Token.ExcName, etype),
|
| 695 |
+
(
|
| 696 |
+
Token,
|
| 697 |
+
"Traceback (most recent call last)".rjust(width - len(etype)),
|
| 698 |
+
),
|
| 699 |
+
]
|
| 700 |
+
)
|
| 701 |
+
|
| 702 |
+
return head
|
| 703 |
+
|
| 704 |
+
def format_exception(self, etype, evalue):
|
| 705 |
+
# Get (safely) a string form of the exception info
|
| 706 |
+
try:
|
| 707 |
+
etype_str, evalue_str = map(str, (etype, evalue))
|
| 708 |
+
except:
|
| 709 |
+
# User exception is improperly defined.
|
| 710 |
+
etype, evalue = str, sys.exc_info()[:2]
|
| 711 |
+
etype_str, evalue_str = map(str, (etype, evalue))
|
| 712 |
+
|
| 713 |
+
# PEP-678 notes
|
| 714 |
+
notes = getattr(evalue, "__notes__", [])
|
| 715 |
+
if not isinstance(notes, Sequence) or isinstance(notes, (str, bytes)):
|
| 716 |
+
notes = [_safe_string(notes, "__notes__", func=repr)]
|
| 717 |
+
|
| 718 |
+
for note in notes:
|
| 719 |
+
assert isinstance(note, str)
|
| 720 |
+
|
| 721 |
+
str_notes: Sequence[str] = notes
|
| 722 |
+
|
| 723 |
+
# ... and format it
|
| 724 |
+
return [
|
| 725 |
+
theme_table[self._theme_name].format(
|
| 726 |
+
[(Token.ExcName, etype_str), (Token, ": "), (Token, evalue_str)]
|
| 727 |
+
),
|
| 728 |
+
*(
|
| 729 |
+
theme_table[self._theme_name].format([(Token, note)])
|
| 730 |
+
for note in str_notes
|
| 731 |
+
),
|
| 732 |
+
]
|
| 733 |
+
|
| 734 |
+
def format_exception_as_a_whole(
|
| 735 |
+
self,
|
| 736 |
+
etype: type,
|
| 737 |
+
evalue: Optional[BaseException],
|
| 738 |
+
etb: Optional[TracebackType],
|
| 739 |
+
context: int,
|
| 740 |
+
tb_offset: Optional[int],
|
| 741 |
+
) -> list[list[str]]:
|
| 742 |
+
"""Formats the header, traceback and exception message for a single exception.
|
| 743 |
+
|
| 744 |
+
This may be called multiple times by Python 3 exception chaining
|
| 745 |
+
(PEP 3134).
|
| 746 |
+
"""
|
| 747 |
+
# some locals
|
| 748 |
+
orig_etype = etype
|
| 749 |
+
try:
|
| 750 |
+
etype = etype.__name__ # type: ignore[assignment]
|
| 751 |
+
except AttributeError:
|
| 752 |
+
pass
|
| 753 |
+
|
| 754 |
+
tb_offset = self.tb_offset if tb_offset is None else tb_offset
|
| 755 |
+
assert isinstance(tb_offset, int)
|
| 756 |
+
head = self.prepare_header(str(etype), self.long_header)
|
| 757 |
+
records = self.get_records(etb, context, tb_offset) if etb else []
|
| 758 |
+
|
| 759 |
+
frames = []
|
| 760 |
+
skipped = 0
|
| 761 |
+
lastrecord = len(records) - 1
|
| 762 |
+
for i, record in enumerate(records):
|
| 763 |
+
if (
|
| 764 |
+
not isinstance(record._sd, stack_data.RepeatedFrames)
|
| 765 |
+
and self.skip_hidden
|
| 766 |
+
):
|
| 767 |
+
if (
|
| 768 |
+
record.frame.f_locals.get("__tracebackhide__", 0)
|
| 769 |
+
and i != lastrecord
|
| 770 |
+
):
|
| 771 |
+
skipped += 1
|
| 772 |
+
continue
|
| 773 |
+
if skipped:
|
| 774 |
+
frames.append(
|
| 775 |
+
theme_table[self._theme_name].format(
|
| 776 |
+
[
|
| 777 |
+
(Token, " "),
|
| 778 |
+
(Token.ExcName, "[... skipping hidden %s frame]" % skipped),
|
| 779 |
+
(Token, "\n"),
|
| 780 |
+
]
|
| 781 |
+
)
|
| 782 |
+
)
|
| 783 |
+
skipped = 0
|
| 784 |
+
frames.append(self.format_record(record))
|
| 785 |
+
if skipped:
|
| 786 |
+
frames.append(
|
| 787 |
+
theme_table[self._theme_name].format(
|
| 788 |
+
[
|
| 789 |
+
(Token, " "),
|
| 790 |
+
(Token.ExcName, "[... skipping hidden %s frame]" % skipped),
|
| 791 |
+
(Token, "\n"),
|
| 792 |
+
]
|
| 793 |
+
)
|
| 794 |
+
)
|
| 795 |
+
|
| 796 |
+
formatted_exception = self.format_exception(etype, evalue)
|
| 797 |
+
if records:
|
| 798 |
+
frame_info = records[-1]
|
| 799 |
+
ipinst = get_ipython()
|
| 800 |
+
if ipinst is not None:
|
| 801 |
+
ipinst.hooks.synchronize_with_editor(
|
| 802 |
+
frame_info.filename, frame_info.lineno, 0
|
| 803 |
+
)
|
| 804 |
+
|
| 805 |
+
return [[head] + frames + formatted_exception]
|
| 806 |
+
|
| 807 |
+
def get_records(self, etb: TracebackType, context: int, tb_offset: int) -> Any:
|
| 808 |
+
assert etb is not None
|
| 809 |
+
context = context - 1
|
| 810 |
+
after = context // 2
|
| 811 |
+
before = context - after
|
| 812 |
+
if self.has_colors:
|
| 813 |
+
base_style = theme_table[self._theme_name].as_pygments_style()
|
| 814 |
+
style = stack_data.style_with_executing_node(base_style, self.tb_highlight)
|
| 815 |
+
formatter = Terminal256Formatter(style=style)
|
| 816 |
+
else:
|
| 817 |
+
formatter = None
|
| 818 |
+
options = stack_data.Options(
|
| 819 |
+
before=before,
|
| 820 |
+
after=after,
|
| 821 |
+
pygments_formatter=formatter,
|
| 822 |
+
)
|
| 823 |
+
|
| 824 |
+
# Let's estimate the amount of code we will have to parse/highlight.
|
| 825 |
+
cf: Optional[TracebackType] = etb
|
| 826 |
+
max_len = 0
|
| 827 |
+
tbs = []
|
| 828 |
+
while cf is not None:
|
| 829 |
+
try:
|
| 830 |
+
mod = inspect.getmodule(cf.tb_frame)
|
| 831 |
+
if mod is not None:
|
| 832 |
+
mod_name = mod.__name__
|
| 833 |
+
root_name, *_ = mod_name.split(".")
|
| 834 |
+
if root_name == "IPython":
|
| 835 |
+
cf = cf.tb_next
|
| 836 |
+
continue
|
| 837 |
+
max_len = get_line_number_of_frame(cf.tb_frame)
|
| 838 |
+
|
| 839 |
+
except OSError:
|
| 840 |
+
max_len = 0
|
| 841 |
+
max_len = max(max_len, max_len)
|
| 842 |
+
tbs.append(cf)
|
| 843 |
+
cf = getattr(cf, "tb_next", None)
|
| 844 |
+
|
| 845 |
+
if max_len > FAST_THRESHOLD:
|
| 846 |
+
FIs: list[FrameInfo] = []
|
| 847 |
+
for tb in tbs:
|
| 848 |
+
frame = tb.tb_frame # type: ignore[union-attr]
|
| 849 |
+
lineno = frame.f_lineno
|
| 850 |
+
code = frame.f_code
|
| 851 |
+
filename = code.co_filename
|
| 852 |
+
# TODO: Here we need to use before/after/
|
| 853 |
+
FIs.append(
|
| 854 |
+
FrameInfo(
|
| 855 |
+
"Raw frame", filename, lineno, frame, code, context=context
|
| 856 |
+
)
|
| 857 |
+
)
|
| 858 |
+
return FIs
|
| 859 |
+
res = list(stack_data.FrameInfo.stack_data(etb, options=options))[tb_offset:]
|
| 860 |
+
res2 = [FrameInfo._from_stack_data_FrameInfo(r) for r in res]
|
| 861 |
+
return res2
|
| 862 |
+
|
| 863 |
+
def structured_traceback(
|
| 864 |
+
self,
|
| 865 |
+
etype: type,
|
| 866 |
+
evalue: Optional[BaseException],
|
| 867 |
+
etb: Optional[TracebackType] = None,
|
| 868 |
+
tb_offset: Optional[int] = None,
|
| 869 |
+
context: int = 5,
|
| 870 |
+
) -> list[str]:
|
| 871 |
+
"""Return a nice text document describing the traceback."""
|
| 872 |
+
formatted_exceptions: list[list[str]] = self.format_exception_as_a_whole(
|
| 873 |
+
etype, evalue, etb, context, tb_offset
|
| 874 |
+
)
|
| 875 |
+
|
| 876 |
+
termsize = min(75, get_terminal_size()[0])
|
| 877 |
+
theme = theme_table[self._theme_name]
|
| 878 |
+
head: str = theme.format(
|
| 879 |
+
[
|
| 880 |
+
(
|
| 881 |
+
Token.Topline,
|
| 882 |
+
theme.symbols["top_line"] * termsize,
|
| 883 |
+
),
|
| 884 |
+
]
|
| 885 |
+
)
|
| 886 |
+
structured_traceback_parts: list[str] = [head]
|
| 887 |
+
chained_exceptions_tb_offset = 0
|
| 888 |
+
lines_of_context = 3
|
| 889 |
+
exception = self.get_parts_of_chained_exception(evalue)
|
| 890 |
+
if exception:
|
| 891 |
+
assert evalue is not None
|
| 892 |
+
formatted_exceptions += self.prepare_chained_exception_message(
|
| 893 |
+
evalue.__cause__
|
| 894 |
+
)
|
| 895 |
+
etype, evalue, etb = exception
|
| 896 |
+
else:
|
| 897 |
+
evalue = None
|
| 898 |
+
chained_exc_ids = set()
|
| 899 |
+
while evalue:
|
| 900 |
+
formatted_exceptions += self.format_exception_as_a_whole(
|
| 901 |
+
etype, evalue, etb, lines_of_context, chained_exceptions_tb_offset
|
| 902 |
+
)
|
| 903 |
+
exception = self.get_parts_of_chained_exception(evalue)
|
| 904 |
+
|
| 905 |
+
if exception and id(exception[1]) not in chained_exc_ids:
|
| 906 |
+
chained_exc_ids.add(
|
| 907 |
+
id(exception[1])
|
| 908 |
+
) # trace exception to avoid infinite 'cause' loop
|
| 909 |
+
formatted_exceptions += self.prepare_chained_exception_message(
|
| 910 |
+
evalue.__cause__
|
| 911 |
+
)
|
| 912 |
+
etype, evalue, etb = exception
|
| 913 |
+
else:
|
| 914 |
+
evalue = None
|
| 915 |
+
|
| 916 |
+
# we want to see exceptions in a reversed order:
|
| 917 |
+
# the first exception should be on top
|
| 918 |
+
for fx in reversed(formatted_exceptions):
|
| 919 |
+
structured_traceback_parts += fx
|
| 920 |
+
|
| 921 |
+
return structured_traceback_parts
|
| 922 |
+
|
| 923 |
+
def debugger(self, force: bool = False) -> None:
|
| 924 |
+
"""Call up the pdb debugger if desired, always clean up the tb
|
| 925 |
+
reference.
|
| 926 |
+
|
| 927 |
+
Keywords:
|
| 928 |
+
|
| 929 |
+
- force(False): by default, this routine checks the instance call_pdb
|
| 930 |
+
flag and does not actually invoke the debugger if the flag is false.
|
| 931 |
+
The 'force' option forces the debugger to activate even if the flag
|
| 932 |
+
is false.
|
| 933 |
+
|
| 934 |
+
If the call_pdb flag is set, the pdb interactive debugger is
|
| 935 |
+
invoked. In all cases, the self.tb reference to the current traceback
|
| 936 |
+
is deleted to prevent lingering references which hamper memory
|
| 937 |
+
management.
|
| 938 |
+
|
| 939 |
+
Note that each call to pdb() does an 'import readline', so if your app
|
| 940 |
+
requires a special setup for the readline completers, you'll have to
|
| 941 |
+
fix that by hand after invoking the exception handler."""
|
| 942 |
+
|
| 943 |
+
if force or self.call_pdb:
|
| 944 |
+
if self.pdb is None:
|
| 945 |
+
self.pdb = self.debugger_cls()
|
| 946 |
+
# the system displayhook may have changed, restore the original
|
| 947 |
+
# for pdb
|
| 948 |
+
display_trap = DisplayTrap(hook=sys.__displayhook__)
|
| 949 |
+
with display_trap:
|
| 950 |
+
self.pdb.reset()
|
| 951 |
+
# Find the right frame so we don't pop up inside ipython itself
|
| 952 |
+
if hasattr(self, "tb") and self.tb is not None: # type: ignore[has-type]
|
| 953 |
+
etb = self.tb # type: ignore[has-type]
|
| 954 |
+
else:
|
| 955 |
+
etb = self.tb = sys.last_traceback
|
| 956 |
+
while self.tb is not None and self.tb.tb_next is not None:
|
| 957 |
+
assert self.tb.tb_next is not None
|
| 958 |
+
self.tb = self.tb.tb_next
|
| 959 |
+
if etb and etb.tb_next:
|
| 960 |
+
etb = etb.tb_next
|
| 961 |
+
self.pdb.botframe = etb.tb_frame
|
| 962 |
+
# last_value should be deprecated, but last-exc sometimme not set
|
| 963 |
+
# please check why later and remove the getattr.
|
| 964 |
+
exc = (
|
| 965 |
+
sys.last_value
|
| 966 |
+
if sys.version_info < (3, 12)
|
| 967 |
+
else getattr(sys, "last_exc", sys.last_value)
|
| 968 |
+
) # type: ignore[attr-defined]
|
| 969 |
+
if exc:
|
| 970 |
+
self.pdb.interaction(None, exc)
|
| 971 |
+
else:
|
| 972 |
+
self.pdb.interaction(None, etb)
|
| 973 |
+
|
| 974 |
+
if hasattr(self, "tb"):
|
| 975 |
+
del self.tb
|
| 976 |
+
|
| 977 |
+
def handler(self, info=None):
|
| 978 |
+
(etype, evalue, etb) = info or sys.exc_info()
|
| 979 |
+
self.tb = etb
|
| 980 |
+
ostream = self.ostream
|
| 981 |
+
ostream.flush()
|
| 982 |
+
ostream.write(self.text(etype, evalue, etb)) # type:ignore[arg-type]
|
| 983 |
+
ostream.write("\n")
|
| 984 |
+
ostream.flush()
|
| 985 |
+
|
| 986 |
+
# Changed so an instance can just be called as VerboseTB_inst() and print
|
| 987 |
+
# out the right info on its own.
|
| 988 |
+
def __call__(self, etype=None, evalue=None, etb=None):
|
| 989 |
+
"""This hook can replace sys.excepthook (for Python 2.1 or higher)."""
|
| 990 |
+
if etb is None:
|
| 991 |
+
self.handler()
|
| 992 |
+
else:
|
| 993 |
+
self.handler((etype, evalue, etb))
|
| 994 |
+
try:
|
| 995 |
+
self.debugger()
|
| 996 |
+
except KeyboardInterrupt:
|
| 997 |
+
print("\nKeyboardInterrupt")
|
| 998 |
+
|
| 999 |
+
|
| 1000 |
+
# ----------------------------------------------------------------------------
|
| 1001 |
+
class FormattedTB(VerboseTB, ListTB):
|
| 1002 |
+
"""Subclass ListTB but allow calling with a traceback.
|
| 1003 |
+
|
| 1004 |
+
It can thus be used as a sys.excepthook for Python > 2.1.
|
| 1005 |
+
|
| 1006 |
+
Also adds 'Context' and 'Verbose' modes, not available in ListTB.
|
| 1007 |
+
|
| 1008 |
+
Allows a tb_offset to be specified. This is useful for situations where
|
| 1009 |
+
one needs to remove a number of topmost frames from the traceback (such as
|
| 1010 |
+
occurs with python programs that themselves execute other python code,
|
| 1011 |
+
like Python shells)."""
|
| 1012 |
+
|
| 1013 |
+
mode: str
|
| 1014 |
+
|
| 1015 |
+
def __init__(
|
| 1016 |
+
self,
|
| 1017 |
+
mode="Plain",
|
| 1018 |
+
# TODO: no default
|
| 1019 |
+
theme_name="linux",
|
| 1020 |
+
call_pdb=False,
|
| 1021 |
+
ostream=None,
|
| 1022 |
+
tb_offset=0,
|
| 1023 |
+
long_header=False,
|
| 1024 |
+
include_vars=False,
|
| 1025 |
+
check_cache=None,
|
| 1026 |
+
debugger_cls=None,
|
| 1027 |
+
):
|
| 1028 |
+
# NEVER change the order of this list. Put new modes at the end:
|
| 1029 |
+
self.valid_modes = ["Plain", "Context", "Verbose", "Minimal", "Docs"]
|
| 1030 |
+
self.verbose_modes = self.valid_modes[1:3]
|
| 1031 |
+
|
| 1032 |
+
VerboseTB.__init__(
|
| 1033 |
+
self,
|
| 1034 |
+
theme_name=theme_name,
|
| 1035 |
+
call_pdb=call_pdb,
|
| 1036 |
+
ostream=ostream,
|
| 1037 |
+
tb_offset=tb_offset,
|
| 1038 |
+
long_header=long_header,
|
| 1039 |
+
include_vars=include_vars,
|
| 1040 |
+
check_cache=check_cache,
|
| 1041 |
+
debugger_cls=debugger_cls,
|
| 1042 |
+
)
|
| 1043 |
+
|
| 1044 |
+
# Different types of tracebacks are joined with different separators to
|
| 1045 |
+
# form a single string. They are taken from this dict
|
| 1046 |
+
self._join_chars = dict(
|
| 1047 |
+
Plain="", Context="\n", Verbose="\n", Minimal="", Docs=""
|
| 1048 |
+
)
|
| 1049 |
+
# set_mode also sets the tb_join_char attribute
|
| 1050 |
+
self.set_mode(mode)
|
| 1051 |
+
|
| 1052 |
+
def structured_traceback(
|
| 1053 |
+
self,
|
| 1054 |
+
etype: type,
|
| 1055 |
+
evalue: BaseException | None,
|
| 1056 |
+
etb: TracebackType | None = None,
|
| 1057 |
+
tb_offset: int | None = None,
|
| 1058 |
+
context: int = 5,
|
| 1059 |
+
) -> list[str]:
|
| 1060 |
+
tb_offset = self.tb_offset if tb_offset is None else tb_offset
|
| 1061 |
+
mode = self.mode
|
| 1062 |
+
if mode in self.verbose_modes:
|
| 1063 |
+
# Verbose modes need a full traceback
|
| 1064 |
+
return VerboseTB.structured_traceback(
|
| 1065 |
+
self, etype, evalue, etb, tb_offset, context
|
| 1066 |
+
)
|
| 1067 |
+
elif mode == "Docs":
|
| 1068 |
+
# return DocTB
|
| 1069 |
+
return DocTB(
|
| 1070 |
+
theme_name=self._theme_name,
|
| 1071 |
+
call_pdb=self.call_pdb,
|
| 1072 |
+
ostream=self.ostream,
|
| 1073 |
+
tb_offset=tb_offset,
|
| 1074 |
+
long_header=self.long_header,
|
| 1075 |
+
include_vars=self.include_vars,
|
| 1076 |
+
check_cache=self.check_cache,
|
| 1077 |
+
debugger_cls=self.debugger_cls,
|
| 1078 |
+
).structured_traceback(
|
| 1079 |
+
etype, evalue, etb, tb_offset, 1
|
| 1080 |
+
) # type: ignore[arg-type]
|
| 1081 |
+
|
| 1082 |
+
elif mode == "Minimal":
|
| 1083 |
+
return ListTB.get_exception_only(self, etype, evalue)
|
| 1084 |
+
else:
|
| 1085 |
+
# We must check the source cache because otherwise we can print
|
| 1086 |
+
# out-of-date source code.
|
| 1087 |
+
self.check_cache()
|
| 1088 |
+
# Now we can extract and format the exception
|
| 1089 |
+
return ListTB.structured_traceback(
|
| 1090 |
+
self, etype, evalue, etb, tb_offset, context
|
| 1091 |
+
)
|
| 1092 |
+
|
| 1093 |
+
def stb2text(self, stb: list[str]) -> str:
|
| 1094 |
+
"""Convert a structured traceback (a list) to a string."""
|
| 1095 |
+
return self.tb_join_char.join(stb)
|
| 1096 |
+
|
| 1097 |
+
def set_mode(self, mode: Optional[str] = None) -> None:
|
| 1098 |
+
"""Switch to the desired mode.
|
| 1099 |
+
|
| 1100 |
+
If mode is not specified, cycles through the available modes."""
|
| 1101 |
+
|
| 1102 |
+
if not mode:
|
| 1103 |
+
new_idx = (self.valid_modes.index(self.mode) + 1) % len(self.valid_modes)
|
| 1104 |
+
self.mode = self.valid_modes[new_idx]
|
| 1105 |
+
elif mode not in self.valid_modes:
|
| 1106 |
+
raise ValueError(
|
| 1107 |
+
"Unrecognized mode in FormattedTB: <" + mode + ">\n"
|
| 1108 |
+
"Valid modes: " + str(self.valid_modes)
|
| 1109 |
+
)
|
| 1110 |
+
else:
|
| 1111 |
+
assert isinstance(mode, str)
|
| 1112 |
+
self.mode = mode
|
| 1113 |
+
# include variable details only in 'Verbose' mode
|
| 1114 |
+
self.include_vars = self.mode == self.valid_modes[2]
|
| 1115 |
+
# Set the join character for generating text tracebacks
|
| 1116 |
+
self.tb_join_char = self._join_chars[self.mode]
|
| 1117 |
+
|
| 1118 |
+
# some convenient shortcuts
|
| 1119 |
+
def plain(self) -> None:
|
| 1120 |
+
self.set_mode(self.valid_modes[0])
|
| 1121 |
+
|
| 1122 |
+
def context(self) -> None:
|
| 1123 |
+
self.set_mode(self.valid_modes[1])
|
| 1124 |
+
|
| 1125 |
+
def verbose(self) -> None:
|
| 1126 |
+
self.set_mode(self.valid_modes[2])
|
| 1127 |
+
|
| 1128 |
+
def minimal(self) -> None:
|
| 1129 |
+
self.set_mode(self.valid_modes[3])
|
| 1130 |
+
|
| 1131 |
+
|
| 1132 |
+
# ----------------------------------------------------------------------------
|
| 1133 |
+
class AutoFormattedTB(FormattedTB):
|
| 1134 |
+
"""A traceback printer which can be called on the fly.
|
| 1135 |
+
|
| 1136 |
+
It will find out about exceptions by itself.
|
| 1137 |
+
|
| 1138 |
+
A brief example::
|
| 1139 |
+
|
| 1140 |
+
AutoTB = AutoFormattedTB(mode = 'Verbose', theme_name='linux')
|
| 1141 |
+
try:
|
| 1142 |
+
...
|
| 1143 |
+
except:
|
| 1144 |
+
AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
|
| 1145 |
+
"""
|
| 1146 |
+
|
| 1147 |
+
def __call__(
|
| 1148 |
+
self,
|
| 1149 |
+
etype: type | None = None,
|
| 1150 |
+
evalue: BaseException | None = None,
|
| 1151 |
+
etb: TracebackType | None = None,
|
| 1152 |
+
out: Any = None,
|
| 1153 |
+
tb_offset: int | None = None,
|
| 1154 |
+
) -> None:
|
| 1155 |
+
"""Print out a formatted exception traceback.
|
| 1156 |
+
|
| 1157 |
+
Optional arguments:
|
| 1158 |
+
- out: an open file-like object to direct output to.
|
| 1159 |
+
|
| 1160 |
+
- tb_offset: the number of frames to skip over in the stack, on a
|
| 1161 |
+
per-call basis (this overrides temporarily the instance's tb_offset
|
| 1162 |
+
given at initialization time."""
|
| 1163 |
+
|
| 1164 |
+
if out is None:
|
| 1165 |
+
out = self.ostream
|
| 1166 |
+
out.flush()
|
| 1167 |
+
out.write(self.text(etype, evalue, etb, tb_offset)) # type:ignore[arg-type]
|
| 1168 |
+
out.write("\n")
|
| 1169 |
+
out.flush()
|
| 1170 |
+
# FIXME: we should remove the auto pdb behavior from here and leave
|
| 1171 |
+
# that to the clients.
|
| 1172 |
+
try:
|
| 1173 |
+
self.debugger()
|
| 1174 |
+
except KeyboardInterrupt:
|
| 1175 |
+
print("\nKeyboardInterrupt")
|
| 1176 |
+
|
| 1177 |
+
def structured_traceback(
|
| 1178 |
+
self,
|
| 1179 |
+
etype: type,
|
| 1180 |
+
evalue: Optional[BaseException],
|
| 1181 |
+
etb: Optional[TracebackType] = None,
|
| 1182 |
+
tb_offset: Optional[int] = None,
|
| 1183 |
+
context: int = 5,
|
| 1184 |
+
) -> list[str]:
|
| 1185 |
+
# tb: TracebackType or tupleof tb types ?
|
| 1186 |
+
if etype is None:
|
| 1187 |
+
etype, evalue, etb = sys.exc_info()
|
| 1188 |
+
if isinstance(etb, tuple):
|
| 1189 |
+
# tb is a tuple if this is a chained exception.
|
| 1190 |
+
self.tb = etb[0]
|
| 1191 |
+
else:
|
| 1192 |
+
self.tb = etb
|
| 1193 |
+
return FormattedTB.structured_traceback(
|
| 1194 |
+
self, etype, evalue, etb, tb_offset, context
|
| 1195 |
+
)
|
| 1196 |
+
|
| 1197 |
+
|
| 1198 |
+
# ---------------------------------------------------------------------------
|
| 1199 |
+
|
| 1200 |
+
|
| 1201 |
+
# A simple class to preserve Nathan's original functionality.
|
| 1202 |
+
class ColorTB(FormattedTB):
|
| 1203 |
+
"""Deprecated since IPython 9.0."""
|
| 1204 |
+
|
| 1205 |
+
def __init__(self, *args, **kwargs):
|
| 1206 |
+
warnings.warn(
|
| 1207 |
+
"Deprecated since IPython 9.0 use FormattedTB directly ColorTB is just an alias",
|
| 1208 |
+
DeprecationWarning,
|
| 1209 |
+
stacklevel=2,
|
| 1210 |
+
)
|
| 1211 |
+
|
| 1212 |
+
super().__init__(*args, **kwargs)
|
| 1213 |
+
|
| 1214 |
+
|
| 1215 |
+
class SyntaxTB(ListTB):
|
| 1216 |
+
"""Extension which holds some state: the last exception value"""
|
| 1217 |
+
|
| 1218 |
+
last_syntax_error: BaseException | None
|
| 1219 |
+
|
| 1220 |
+
def __init__(self, *, theme_name):
|
| 1221 |
+
super().__init__(theme_name=theme_name)
|
| 1222 |
+
self.last_syntax_error = None
|
| 1223 |
+
|
| 1224 |
+
def __call__(self, etype, value, elist):
|
| 1225 |
+
self.last_syntax_error = value
|
| 1226 |
+
|
| 1227 |
+
super().__call__(etype, value, elist)
|
| 1228 |
+
|
| 1229 |
+
def structured_traceback(
|
| 1230 |
+
self,
|
| 1231 |
+
etype: type,
|
| 1232 |
+
evalue: BaseException | None,
|
| 1233 |
+
etb: TracebackType | None = None,
|
| 1234 |
+
tb_offset: int | None = None,
|
| 1235 |
+
context: int = 5,
|
| 1236 |
+
) -> list[str]:
|
| 1237 |
+
value = evalue
|
| 1238 |
+
# If the source file has been edited, the line in the syntax error can
|
| 1239 |
+
# be wrong (retrieved from an outdated cache). This replaces it with
|
| 1240 |
+
# the current value.
|
| 1241 |
+
if (
|
| 1242 |
+
isinstance(value, SyntaxError)
|
| 1243 |
+
and isinstance(value.filename, str)
|
| 1244 |
+
and isinstance(value.lineno, int)
|
| 1245 |
+
):
|
| 1246 |
+
linecache.checkcache(value.filename)
|
| 1247 |
+
newtext = linecache.getline(value.filename, value.lineno)
|
| 1248 |
+
if newtext:
|
| 1249 |
+
value.text = newtext
|
| 1250 |
+
self.last_syntax_error = value
|
| 1251 |
+
return super(SyntaxTB, self).structured_traceback(
|
| 1252 |
+
etype, value, etb, tb_offset=tb_offset, context=context
|
| 1253 |
+
)
|
| 1254 |
+
|
| 1255 |
+
def clear_err_state(self) -> Any | None:
|
| 1256 |
+
"""Return the current error state and clear it"""
|
| 1257 |
+
e = self.last_syntax_error
|
| 1258 |
+
self.last_syntax_error = None
|
| 1259 |
+
return e
|
| 1260 |
+
|
| 1261 |
+
def stb2text(self, stb: list[str]) -> str:
|
| 1262 |
+
"""Convert a structured traceback (a list) to a string."""
|
| 1263 |
+
return "".join(stb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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""Usage information for the main IPython applications.
|
| 3 |
+
"""
|
| 4 |
+
#-----------------------------------------------------------------------------
|
| 5 |
+
# Copyright (C) 2008-2011 The IPython Development Team
|
| 6 |
+
# Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
|
| 7 |
+
#
|
| 8 |
+
# Distributed under the terms of the BSD License. The full license is in
|
| 9 |
+
# the file COPYING, distributed as part of this software.
|
| 10 |
+
#-----------------------------------------------------------------------------
|
| 11 |
+
|
| 12 |
+
import sys
|
| 13 |
+
from IPython.core import release
|
| 14 |
+
|
| 15 |
+
cl_usage = """\
|
| 16 |
+
=========
|
| 17 |
+
IPython
|
| 18 |
+
=========
|
| 19 |
+
|
| 20 |
+
Tools for Interactive Computing in Python
|
| 21 |
+
=========================================
|
| 22 |
+
|
| 23 |
+
A Python shell with automatic history (input and output), dynamic object
|
| 24 |
+
introspection, easier configuration, command completion, access to the
|
| 25 |
+
system shell and more. IPython can also be embedded in running programs.
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
Usage
|
| 29 |
+
|
| 30 |
+
ipython [subcommand] [options] [-c cmd | -m mod | file] [--] [arg] ...
|
| 31 |
+
|
| 32 |
+
If invoked with no options, it executes the file and exits, passing the
|
| 33 |
+
remaining arguments to the script, just as if you had specified the same
|
| 34 |
+
command with python. You may need to specify `--` before args to be passed
|
| 35 |
+
to the script, to prevent IPython from attempting to parse them. If you
|
| 36 |
+
specify the option `-i` before the filename, it will enter an interactive
|
| 37 |
+
IPython session after running the script, rather than exiting. Files ending
|
| 38 |
+
in .py will be treated as normal Python, but files ending in .ipy can
|
| 39 |
+
contain special IPython syntax (magic commands, shell expansions, etc.).
|
| 40 |
+
|
| 41 |
+
Almost all configuration in IPython is available via the command-line. Do
|
| 42 |
+
`ipython --help-all` to see all available options. For persistent
|
| 43 |
+
configuration, look into your `ipython_config.py` configuration file for
|
| 44 |
+
details.
|
| 45 |
+
|
| 46 |
+
This file is typically installed in the `IPYTHONDIR` directory, and there
|
| 47 |
+
is a separate configuration directory for each profile. The default profile
|
| 48 |
+
directory will be located in $IPYTHONDIR/profile_default. IPYTHONDIR
|
| 49 |
+
defaults to to `$HOME/.ipython`. For Windows users, $HOME resolves to
|
| 50 |
+
C:\\Users\\YourUserName in most instances.
|
| 51 |
+
|
| 52 |
+
To initialize a profile with the default configuration file, do::
|
| 53 |
+
|
| 54 |
+
$> ipython profile create
|
| 55 |
+
|
| 56 |
+
and start editing `IPYTHONDIR/profile_default/ipython_config.py`
|
| 57 |
+
|
| 58 |
+
In IPython's documentation, we will refer to this directory as
|
| 59 |
+
`IPYTHONDIR`, you can change its default location by creating an
|
| 60 |
+
environment variable with this name and setting it to the desired path.
|
| 61 |
+
|
| 62 |
+
For more information, see the manual available in HTML and PDF in your
|
| 63 |
+
installation, or online at https://ipython.org/documentation.html.
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
interactive_usage = """
|
| 67 |
+
IPython -- An enhanced Interactive Python
|
| 68 |
+
=========================================
|
| 69 |
+
|
| 70 |
+
IPython offers a fully compatible replacement for the standard Python
|
| 71 |
+
interpreter, with convenient shell features, special commands, command
|
| 72 |
+
history mechanism and output results caching.
|
| 73 |
+
|
| 74 |
+
At your system command line, type 'ipython -h' to see the command line
|
| 75 |
+
options available. This document only describes interactive features.
|
| 76 |
+
|
| 77 |
+
GETTING HELP
|
| 78 |
+
------------
|
| 79 |
+
|
| 80 |
+
Within IPython you have various way to access help:
|
| 81 |
+
|
| 82 |
+
? -> Introduction and overview of IPython's features (this screen).
|
| 83 |
+
object? -> Details about 'object'.
|
| 84 |
+
object?? -> More detailed, verbose information about 'object'.
|
| 85 |
+
%quickref -> Quick reference of all IPython specific syntax and magics.
|
| 86 |
+
help -> Access Python's own help system.
|
| 87 |
+
|
| 88 |
+
If you are in terminal IPython you can quit this screen by pressing `q`.
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
MAIN FEATURES
|
| 92 |
+
-------------
|
| 93 |
+
|
| 94 |
+
* Access to the standard Python help with object docstrings and the Python
|
| 95 |
+
manuals. Simply type 'help' (no quotes) to invoke it.
|
| 96 |
+
|
| 97 |
+
* Magic commands: type %magic for information on the magic subsystem.
|
| 98 |
+
|
| 99 |
+
* System command aliases, via the %alias command or the configuration file(s).
|
| 100 |
+
|
| 101 |
+
* Dynamic object information:
|
| 102 |
+
|
| 103 |
+
Typing ?word or word? prints detailed information about an object. Certain
|
| 104 |
+
long strings (code, etc.) get snipped in the center for brevity.
|
| 105 |
+
|
| 106 |
+
Typing ??word or word?? gives access to the full information without
|
| 107 |
+
snipping long strings. Strings that are longer than the screen are printed
|
| 108 |
+
through the less pager.
|
| 109 |
+
|
| 110 |
+
The ?/?? system gives access to the full source code for any object (if
|
| 111 |
+
available), shows function prototypes and other useful information.
|
| 112 |
+
|
| 113 |
+
If you just want to see an object's docstring, type '%pdoc object' (without
|
| 114 |
+
quotes, and without % if you have automagic on).
|
| 115 |
+
|
| 116 |
+
* Tab completion in the local namespace:
|
| 117 |
+
|
| 118 |
+
At any time, hitting tab will complete any available python commands or
|
| 119 |
+
variable names, and show you a list of the possible completions if there's
|
| 120 |
+
no unambiguous one. It will also complete filenames in the current directory.
|
| 121 |
+
|
| 122 |
+
* Search previous command history in multiple ways:
|
| 123 |
+
|
| 124 |
+
- Start typing, and then use arrow keys up/down or (Ctrl-p/Ctrl-n) to search
|
| 125 |
+
through the history items that match what you've typed so far.
|
| 126 |
+
|
| 127 |
+
- Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
|
| 128 |
+
your history for lines that match what you've typed so far, completing as
|
| 129 |
+
much as it can.
|
| 130 |
+
|
| 131 |
+
- %hist: search history by index.
|
| 132 |
+
|
| 133 |
+
* Persistent command history across sessions.
|
| 134 |
+
|
| 135 |
+
* Logging of input with the ability to save and restore a working session.
|
| 136 |
+
|
| 137 |
+
* System shell with !. Typing !ls will run 'ls' in the current directory.
|
| 138 |
+
|
| 139 |
+
* The reload command does a 'deep' reload of a module: changes made to the
|
| 140 |
+
module since you imported will actually be available without having to exit.
|
| 141 |
+
|
| 142 |
+
* Verbose and colored exception traceback printouts. See the magic xmode and
|
| 143 |
+
xcolor functions for details (just type %magic).
|
| 144 |
+
|
| 145 |
+
* Input caching system:
|
| 146 |
+
|
| 147 |
+
IPython offers numbered prompts (In/Out) with input and output caching. All
|
| 148 |
+
input is saved and can be retrieved as variables (besides the usual arrow
|
| 149 |
+
key recall).
|
| 150 |
+
|
| 151 |
+
The following GLOBAL variables always exist (so don't overwrite them!):
|
| 152 |
+
_i: stores previous input.
|
| 153 |
+
_ii: next previous.
|
| 154 |
+
_iii: next-next previous.
|
| 155 |
+
_ih : a list of all input _ih[n] is the input from line n.
|
| 156 |
+
|
| 157 |
+
Additionally, global variables named _i<n> are dynamically created (<n>
|
| 158 |
+
being the prompt counter), such that _i<n> == _ih[<n>]
|
| 159 |
+
|
| 160 |
+
For example, what you typed at prompt 14 is available as _i14 and _ih[14].
|
| 161 |
+
|
| 162 |
+
You can create macros which contain multiple input lines from this history,
|
| 163 |
+
for later re-execution, with the %macro function.
|
| 164 |
+
|
| 165 |
+
The history function %hist allows you to see any part of your input history
|
| 166 |
+
by printing a range of the _i variables. Note that inputs which contain
|
| 167 |
+
magic functions (%) appear in the history with a prepended comment. This is
|
| 168 |
+
because they aren't really valid Python code, so you can't exec them.
|
| 169 |
+
|
| 170 |
+
* Output caching system:
|
| 171 |
+
|
| 172 |
+
For output that is returned from actions, a system similar to the input
|
| 173 |
+
cache exists but using _ instead of _i. Only actions that produce a result
|
| 174 |
+
(NOT assignments, for example) are cached. If you are familiar with
|
| 175 |
+
Mathematica, IPython's _ variables behave exactly like Mathematica's %
|
| 176 |
+
variables.
|
| 177 |
+
|
| 178 |
+
The following GLOBAL variables always exist (so don't overwrite them!):
|
| 179 |
+
_ (one underscore): previous output.
|
| 180 |
+
__ (two underscores): next previous.
|
| 181 |
+
___ (three underscores): next-next previous.
|
| 182 |
+
|
| 183 |
+
Global variables named _<n> are dynamically created (<n> being the prompt
|
| 184 |
+
counter), such that the result of output <n> is always available as _<n>.
|
| 185 |
+
|
| 186 |
+
Finally, a global dictionary named _oh exists with entries for all lines
|
| 187 |
+
which generated output.
|
| 188 |
+
|
| 189 |
+
* Directory history:
|
| 190 |
+
|
| 191 |
+
Your history of visited directories is kept in the global list _dh, and the
|
| 192 |
+
magic %cd command can be used to go to any entry in that list.
|
| 193 |
+
|
| 194 |
+
* Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
|
| 195 |
+
|
| 196 |
+
1. Auto-parentheses
|
| 197 |
+
|
| 198 |
+
Callable objects (i.e. functions, methods, etc) can be invoked like
|
| 199 |
+
this (notice the commas between the arguments)::
|
| 200 |
+
|
| 201 |
+
In [1]: callable_ob arg1, arg2, arg3
|
| 202 |
+
|
| 203 |
+
and the input will be translated to this::
|
| 204 |
+
|
| 205 |
+
callable_ob(arg1, arg2, arg3)
|
| 206 |
+
|
| 207 |
+
This feature is off by default (in rare cases it can produce
|
| 208 |
+
undesirable side-effects), but you can activate it at the command-line
|
| 209 |
+
by starting IPython with `--autocall 1`, set it permanently in your
|
| 210 |
+
configuration file, or turn on at runtime with `%autocall 1`.
|
| 211 |
+
|
| 212 |
+
You can force auto-parentheses by using '/' as the first character
|
| 213 |
+
of a line. For example::
|
| 214 |
+
|
| 215 |
+
In [1]: /globals # becomes 'globals()'
|
| 216 |
+
|
| 217 |
+
Note that the '/' MUST be the first character on the line! This
|
| 218 |
+
won't work::
|
| 219 |
+
|
| 220 |
+
In [2]: print /globals # syntax error
|
| 221 |
+
|
| 222 |
+
In most cases the automatic algorithm should work, so you should
|
| 223 |
+
rarely need to explicitly invoke /. One notable exception is if you
|
| 224 |
+
are trying to call a function with a list of tuples as arguments (the
|
| 225 |
+
parenthesis will confuse IPython)::
|
| 226 |
+
|
| 227 |
+
In [1]: zip (1,2,3),(4,5,6) # won't work
|
| 228 |
+
|
| 229 |
+
but this will work::
|
| 230 |
+
|
| 231 |
+
In [2]: /zip (1,2,3),(4,5,6)
|
| 232 |
+
------> zip ((1,2,3),(4,5,6))
|
| 233 |
+
Out[2]= [(1, 4), (2, 5), (3, 6)]
|
| 234 |
+
|
| 235 |
+
IPython tells you that it has altered your command line by
|
| 236 |
+
displaying the new command line preceded by -->. e.g.::
|
| 237 |
+
|
| 238 |
+
In [18]: callable list
|
| 239 |
+
-------> callable (list)
|
| 240 |
+
|
| 241 |
+
2. Auto-Quoting
|
| 242 |
+
|
| 243 |
+
You can force auto-quoting of a function's arguments by using ',' as
|
| 244 |
+
the first character of a line. For example::
|
| 245 |
+
|
| 246 |
+
In [1]: ,my_function /home/me # becomes my_function("/home/me")
|
| 247 |
+
|
| 248 |
+
If you use ';' instead, the whole argument is quoted as a single
|
| 249 |
+
string (while ',' splits on whitespace)::
|
| 250 |
+
|
| 251 |
+
In [2]: ,my_function a b c # becomes my_function("a","b","c")
|
| 252 |
+
In [3]: ;my_function a b c # becomes my_function("a b c")
|
| 253 |
+
|
| 254 |
+
Note that the ',' MUST be the first character on the line! This
|
| 255 |
+
won't work::
|
| 256 |
+
|
| 257 |
+
In [4]: x = ,my_function /home/me # syntax error
|
| 258 |
+
"""
|
| 259 |
+
|
| 260 |
+
interactive_usage_min = """\
|
| 261 |
+
An enhanced console for Python.
|
| 262 |
+
Some of its features are:
|
| 263 |
+
- Tab completion in the local namespace.
|
| 264 |
+
- Logging of input, see command-line options.
|
| 265 |
+
- System shell escape via ! , eg !ls.
|
| 266 |
+
- Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
|
| 267 |
+
- Keeps track of locally defined variables via %who, %whos.
|
| 268 |
+
- Show object information with a ? eg ?x or x? (use ?? for more info).
|
| 269 |
+
"""
|
| 270 |
+
|
| 271 |
+
quick_reference = r"""
|
| 272 |
+
IPython -- An enhanced Interactive Python - Quick Reference Card
|
| 273 |
+
================================================================
|
| 274 |
+
|
| 275 |
+
obj?, obj?? : Get help, or more help for object (also works as
|
| 276 |
+
?obj, ??obj).
|
| 277 |
+
?foo.*abc* : List names in 'foo' containing 'abc' in them.
|
| 278 |
+
%magic : Information about IPython's 'magic' % functions.
|
| 279 |
+
|
| 280 |
+
Magic functions are prefixed by % or %%, and typically take their arguments
|
| 281 |
+
without parentheses, quotes or even commas for convenience. Line magics take a
|
| 282 |
+
single % and cell magics are prefixed with two %%.
|
| 283 |
+
|
| 284 |
+
Example magic function calls:
|
| 285 |
+
|
| 286 |
+
%alias d ls -F : 'd' is now an alias for 'ls -F'
|
| 287 |
+
alias d ls -F : Works if 'alias' not a python name
|
| 288 |
+
alist = %alias : Get list of aliases to 'alist'
|
| 289 |
+
cd /usr/share : Obvious. cd -<tab> to choose from visited dirs.
|
| 290 |
+
%cd?? : See help AND source for magic %cd
|
| 291 |
+
%timeit x=10 : time the 'x=10' statement with high precision.
|
| 292 |
+
%%timeit x=2**100
|
| 293 |
+
x**100 : time 'x**100' with a setup of 'x=2**100'; setup code is not
|
| 294 |
+
counted. This is an example of a cell magic.
|
| 295 |
+
|
| 296 |
+
System commands:
|
| 297 |
+
|
| 298 |
+
!cp a.txt b/ : System command escape, calls os.system()
|
| 299 |
+
cp a.txt b/ : after %rehashx, most system commands work without !
|
| 300 |
+
cp ${f}.txt $bar : Variable expansion in magics and system commands
|
| 301 |
+
files = !ls /usr : Capture system command output
|
| 302 |
+
files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
|
| 303 |
+
|
| 304 |
+
History:
|
| 305 |
+
|
| 306 |
+
_i, _ii, _iii : Previous, next previous, next next previous input
|
| 307 |
+
_i4, _ih[2:5] : Input history line 4, lines 2-4
|
| 308 |
+
exec(_i81) : Execute input history line #81 again
|
| 309 |
+
%rep 81 : Edit input history line #81
|
| 310 |
+
_, __, ___ : previous, next previous, next next previous output
|
| 311 |
+
_dh : Directory history
|
| 312 |
+
_oh : Output history
|
| 313 |
+
%hist : Command history of current session.
|
| 314 |
+
%hist -g foo : Search command history of (almost) all sessions for 'foo'.
|
| 315 |
+
%hist -g : Command history of (almost) all sessions.
|
| 316 |
+
%hist 1/2-8 : Command history containing lines 2-8 of session 1.
|
| 317 |
+
%hist 1/ ~2/ : Command history of session 1 and 2 sessions before current.
|
| 318 |
+
%hist ~8/1-~6/5 : Command history from line 1 of 8 sessions ago to
|
| 319 |
+
line 5 of 6 sessions ago.
|
| 320 |
+
%edit 0/ : Open editor to execute code with history of current session.
|
| 321 |
+
|
| 322 |
+
Autocall:
|
| 323 |
+
|
| 324 |
+
f 1,2 : f(1,2) # Off by default, enable with %autocall magic.
|
| 325 |
+
/f 1,2 : f(1,2) (forced autoparen)
|
| 326 |
+
,f 1 2 : f("1","2")
|
| 327 |
+
;f 1 2 : f("1 2")
|
| 328 |
+
|
| 329 |
+
Remember: TAB completion works in many contexts, not just file names
|
| 330 |
+
or python names.
|
| 331 |
+
|
| 332 |
+
The following magic functions are currently available:
|
| 333 |
+
|
| 334 |
+
"""
|
| 335 |
+
|
| 336 |
+
default_banner_parts = ["Python %s\n"%sys.version.split("\n")[0],
|
| 337 |
+
"Type 'copyright', 'credits' or 'license' for more information\n" ,
|
| 338 |
+
"IPython {version} -- An enhanced Interactive Python. Type '?' for help.\n".format(version=release.version),
|
| 339 |
+
]
|
| 340 |
+
|
| 341 |
+
default_banner = ''.join(default_banner_parts)
|
lib/python3.12/site-packages/IPython/lib/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# encoding: utf-8
|
| 2 |
+
"""
|
| 3 |
+
Extra capabilities for IPython
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
# -----------------------------------------------------------------------------
|
| 7 |
+
# Copyright (C) 2008-2011 The IPython Development Team
|
| 8 |
+
#
|
| 9 |
+
# Distributed under the terms of the BSD License. The full license is in
|
| 10 |
+
# the file COPYING, distributed as part of this software.
|
| 11 |
+
# -----------------------------------------------------------------------------
|
lib/python3.12/site-packages/IPython/lib/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (239 Bytes). View file
|
|
|
lib/python3.12/site-packages/IPython/lib/__pycache__/backgroundjobs.cpython-312.pyc
ADDED
|
Binary file (21.4 kB). View file
|
|
|
lib/python3.12/site-packages/IPython/lib/__pycache__/clipboard.cpython-312.pyc
ADDED
|
Binary file (4.96 kB). View file
|
|
|
lib/python3.12/site-packages/IPython/lib/__pycache__/deepreload.cpython-312.pyc
ADDED
|
Binary file (9.14 kB). View file
|
|
|
lib/python3.12/site-packages/IPython/lib/__pycache__/demo.cpython-312.pyc
ADDED
|
Binary file (29.1 kB). View file
|
|
|
lib/python3.12/site-packages/IPython/lib/__pycache__/display.cpython-312.pyc
ADDED
|
Binary file (29.3 kB). View file
|
|
|
lib/python3.12/site-packages/IPython/lib/__pycache__/editorhooks.cpython-312.pyc
ADDED
|
Binary file (4.98 kB). View file
|
|
|
lib/python3.12/site-packages/IPython/lib/__pycache__/guisupport.cpython-312.pyc
ADDED
|
Binary file (5.91 kB). View file
|
|
|
lib/python3.12/site-packages/IPython/lib/__pycache__/latextools.cpython-312.pyc
ADDED
|
Binary file (10.4 kB). View file
|
|
|
lib/python3.12/site-packages/IPython/lib/__pycache__/lexers.cpython-312.pyc
ADDED
|
Binary file (615 Bytes). View file
|
|
|
lib/python3.12/site-packages/IPython/lib/__pycache__/pretty.cpython-312.pyc
ADDED
|
Binary file (44 kB). View file
|
|
|
lib/python3.12/site-packages/IPython/lib/backgroundjobs.py
ADDED
|
@@ -0,0 +1,491 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""Manage background (threaded) jobs conveniently from an interactive shell.
|
| 3 |
+
|
| 4 |
+
This module provides a BackgroundJobManager class. This is the main class
|
| 5 |
+
meant for public usage, it implements an object which can create and manage
|
| 6 |
+
new background jobs.
|
| 7 |
+
|
| 8 |
+
It also provides the actual job classes managed by these BackgroundJobManager
|
| 9 |
+
objects, see their docstrings below.
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
This system was inspired by discussions with B. Granger and the
|
| 13 |
+
BackgroundCommand class described in the book Python Scripting for
|
| 14 |
+
Computational Science, by H. P. Langtangen:
|
| 15 |
+
|
| 16 |
+
http://folk.uio.no/hpl/scripting
|
| 17 |
+
|
| 18 |
+
(although ultimately no code from this text was used, as IPython's system is a
|
| 19 |
+
separate implementation).
|
| 20 |
+
|
| 21 |
+
An example notebook is provided in our documentation illustrating interactive
|
| 22 |
+
use of the system.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
#*****************************************************************************
|
| 26 |
+
# Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu>
|
| 27 |
+
#
|
| 28 |
+
# Distributed under the terms of the BSD License. The full license is in
|
| 29 |
+
# the file COPYING, distributed as part of this software.
|
| 30 |
+
#*****************************************************************************
|
| 31 |
+
|
| 32 |
+
# Code begins
|
| 33 |
+
import sys
|
| 34 |
+
import threading
|
| 35 |
+
|
| 36 |
+
from IPython import get_ipython
|
| 37 |
+
from IPython.core.ultratb import AutoFormattedTB
|
| 38 |
+
from logging import error, debug
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class BackgroundJobManager:
|
| 42 |
+
"""Class to manage a pool of backgrounded threaded jobs.
|
| 43 |
+
|
| 44 |
+
Below, we assume that 'jobs' is a BackgroundJobManager instance.
|
| 45 |
+
|
| 46 |
+
Usage summary (see the method docstrings for details):
|
| 47 |
+
|
| 48 |
+
jobs.new(...) -> start a new job
|
| 49 |
+
|
| 50 |
+
jobs() or jobs.status() -> print status summary of all jobs
|
| 51 |
+
|
| 52 |
+
jobs[N] -> returns job number N.
|
| 53 |
+
|
| 54 |
+
foo = jobs[N].result -> assign to variable foo the result of job N
|
| 55 |
+
|
| 56 |
+
jobs[N].traceback() -> print the traceback of dead job N
|
| 57 |
+
|
| 58 |
+
jobs.remove(N) -> remove (finished) job N
|
| 59 |
+
|
| 60 |
+
jobs.flush() -> remove all finished jobs
|
| 61 |
+
|
| 62 |
+
As a convenience feature, BackgroundJobManager instances provide the
|
| 63 |
+
utility result and traceback methods which retrieve the corresponding
|
| 64 |
+
information from the jobs list:
|
| 65 |
+
|
| 66 |
+
jobs.result(N) <--> jobs[N].result
|
| 67 |
+
jobs.traceback(N) <--> jobs[N].traceback()
|
| 68 |
+
|
| 69 |
+
While this appears minor, it allows you to use tab completion
|
| 70 |
+
interactively on the job manager instance.
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
def __init__(self):
|
| 74 |
+
# Lists for job management, accessed via a property to ensure they're
|
| 75 |
+
# up to date.x
|
| 76 |
+
self._running = []
|
| 77 |
+
self._completed = []
|
| 78 |
+
self._dead = []
|
| 79 |
+
# A dict of all jobs, so users can easily access any of them
|
| 80 |
+
self.all = {}
|
| 81 |
+
# For reporting
|
| 82 |
+
self._comp_report = []
|
| 83 |
+
self._dead_report = []
|
| 84 |
+
# Store status codes locally for fast lookups
|
| 85 |
+
self._s_created = BackgroundJobBase.stat_created_c
|
| 86 |
+
self._s_running = BackgroundJobBase.stat_running_c
|
| 87 |
+
self._s_completed = BackgroundJobBase.stat_completed_c
|
| 88 |
+
self._s_dead = BackgroundJobBase.stat_dead_c
|
| 89 |
+
self._current_job_id = 0
|
| 90 |
+
|
| 91 |
+
@property
|
| 92 |
+
def running(self):
|
| 93 |
+
self._update_status()
|
| 94 |
+
return self._running
|
| 95 |
+
|
| 96 |
+
@property
|
| 97 |
+
def dead(self):
|
| 98 |
+
self._update_status()
|
| 99 |
+
return self._dead
|
| 100 |
+
|
| 101 |
+
@property
|
| 102 |
+
def completed(self):
|
| 103 |
+
self._update_status()
|
| 104 |
+
return self._completed
|
| 105 |
+
|
| 106 |
+
def new(self, func_or_exp, *args, **kwargs):
|
| 107 |
+
"""Add a new background job and start it in a separate thread.
|
| 108 |
+
|
| 109 |
+
There are two types of jobs which can be created:
|
| 110 |
+
|
| 111 |
+
1. Jobs based on expressions which can be passed to an eval() call.
|
| 112 |
+
The expression must be given as a string. For example:
|
| 113 |
+
|
| 114 |
+
job_manager.new('myfunc(x,y,z=1)'[,glob[,loc]])
|
| 115 |
+
|
| 116 |
+
The given expression is passed to eval(), along with the optional
|
| 117 |
+
global/local dicts provided. If no dicts are given, they are
|
| 118 |
+
extracted automatically from the caller's frame.
|
| 119 |
+
|
| 120 |
+
A Python statement is NOT a valid eval() expression. Basically, you
|
| 121 |
+
can only use as an eval() argument something which can go on the right
|
| 122 |
+
of an '=' sign and be assigned to a variable.
|
| 123 |
+
|
| 124 |
+
For example,"print 'hello'" is not valid, but '2+3' is.
|
| 125 |
+
|
| 126 |
+
2. Jobs given a function object, optionally passing additional
|
| 127 |
+
positional arguments:
|
| 128 |
+
|
| 129 |
+
job_manager.new(myfunc, x, y)
|
| 130 |
+
|
| 131 |
+
The function is called with the given arguments.
|
| 132 |
+
|
| 133 |
+
If you need to pass keyword arguments to your function, you must
|
| 134 |
+
supply them as a dict named kw:
|
| 135 |
+
|
| 136 |
+
job_manager.new(myfunc, x, y, kw=dict(z=1))
|
| 137 |
+
|
| 138 |
+
The reason for this asymmetry is that the new() method needs to
|
| 139 |
+
maintain access to its own keywords, and this prevents name collisions
|
| 140 |
+
between arguments to new() and arguments to your own functions.
|
| 141 |
+
|
| 142 |
+
In both cases, the result is stored in the job.result field of the
|
| 143 |
+
background job object.
|
| 144 |
+
|
| 145 |
+
You can set `daemon` attribute of the thread by giving the keyword
|
| 146 |
+
argument `daemon`.
|
| 147 |
+
|
| 148 |
+
Notes and caveats:
|
| 149 |
+
|
| 150 |
+
1. All threads running share the same standard output. Thus, if your
|
| 151 |
+
background jobs generate output, it will come out on top of whatever
|
| 152 |
+
you are currently writing. For this reason, background jobs are best
|
| 153 |
+
used with silent functions which simply return their output.
|
| 154 |
+
|
| 155 |
+
2. Threads also all work within the same global namespace, and this
|
| 156 |
+
system does not lock interactive variables. So if you send job to the
|
| 157 |
+
background which operates on a mutable object for a long time, and
|
| 158 |
+
start modifying that same mutable object interactively (or in another
|
| 159 |
+
backgrounded job), all sorts of bizarre behaviour will occur.
|
| 160 |
+
|
| 161 |
+
3. If a background job is spending a lot of time inside a C extension
|
| 162 |
+
module which does not release the Python Global Interpreter Lock
|
| 163 |
+
(GIL), this will block the IPython prompt. This is simply because the
|
| 164 |
+
Python interpreter can only switch between threads at Python
|
| 165 |
+
bytecodes. While the execution is inside C code, the interpreter must
|
| 166 |
+
simply wait unless the extension module releases the GIL.
|
| 167 |
+
|
| 168 |
+
4. There is no way, due to limitations in the Python threads library,
|
| 169 |
+
to kill a thread once it has started."""
|
| 170 |
+
|
| 171 |
+
if callable(func_or_exp):
|
| 172 |
+
kw = kwargs.get('kw',{})
|
| 173 |
+
job = BackgroundJobFunc(func_or_exp,*args,**kw)
|
| 174 |
+
elif isinstance(func_or_exp, str):
|
| 175 |
+
if not args:
|
| 176 |
+
frame = sys._getframe(1)
|
| 177 |
+
glob, loc = frame.f_globals, frame.f_locals
|
| 178 |
+
elif len(args)==1:
|
| 179 |
+
glob = loc = args[0]
|
| 180 |
+
elif len(args)==2:
|
| 181 |
+
glob,loc = args
|
| 182 |
+
else:
|
| 183 |
+
raise ValueError(
|
| 184 |
+
'Expression jobs take at most 2 args (globals,locals)')
|
| 185 |
+
job = BackgroundJobExpr(func_or_exp, glob, loc)
|
| 186 |
+
else:
|
| 187 |
+
raise TypeError('invalid args for new job')
|
| 188 |
+
|
| 189 |
+
if kwargs.get('daemon', False):
|
| 190 |
+
job.daemon = True
|
| 191 |
+
job.num = self._current_job_id
|
| 192 |
+
self._current_job_id += 1
|
| 193 |
+
self.running.append(job)
|
| 194 |
+
self.all[job.num] = job
|
| 195 |
+
debug('Starting job # %s in a separate thread.' % job.num)
|
| 196 |
+
job.start()
|
| 197 |
+
return job
|
| 198 |
+
|
| 199 |
+
def __getitem__(self, job_key):
|
| 200 |
+
num = job_key if isinstance(job_key, int) else job_key.num
|
| 201 |
+
return self.all[num]
|
| 202 |
+
|
| 203 |
+
def __call__(self):
|
| 204 |
+
"""An alias to self.status(),
|
| 205 |
+
|
| 206 |
+
This allows you to simply call a job manager instance much like the
|
| 207 |
+
Unix `jobs` shell command."""
|
| 208 |
+
|
| 209 |
+
return self.status()
|
| 210 |
+
|
| 211 |
+
def _update_status(self):
|
| 212 |
+
"""Update the status of the job lists.
|
| 213 |
+
|
| 214 |
+
This method moves finished jobs to one of two lists:
|
| 215 |
+
- self.completed: jobs which completed successfully
|
| 216 |
+
- self.dead: jobs which finished but died.
|
| 217 |
+
|
| 218 |
+
It also copies those jobs to corresponding _report lists. These lists
|
| 219 |
+
are used to report jobs completed/dead since the last update, and are
|
| 220 |
+
then cleared by the reporting function after each call."""
|
| 221 |
+
|
| 222 |
+
# Status codes
|
| 223 |
+
srun, scomp, sdead = self._s_running, self._s_completed, self._s_dead
|
| 224 |
+
# State lists, use the actual lists b/c the public names are properties
|
| 225 |
+
# that call this very function on access
|
| 226 |
+
running, completed, dead = self._running, self._completed, self._dead
|
| 227 |
+
|
| 228 |
+
# Now, update all state lists
|
| 229 |
+
for num, job in enumerate(running):
|
| 230 |
+
stat = job.stat_code
|
| 231 |
+
if stat == srun:
|
| 232 |
+
continue
|
| 233 |
+
elif stat == scomp:
|
| 234 |
+
completed.append(job)
|
| 235 |
+
self._comp_report.append(job)
|
| 236 |
+
running[num] = False
|
| 237 |
+
elif stat == sdead:
|
| 238 |
+
dead.append(job)
|
| 239 |
+
self._dead_report.append(job)
|
| 240 |
+
running[num] = False
|
| 241 |
+
# Remove dead/completed jobs from running list
|
| 242 |
+
running[:] = filter(None, running)
|
| 243 |
+
|
| 244 |
+
def _group_report(self,group,name):
|
| 245 |
+
"""Report summary for a given job group.
|
| 246 |
+
|
| 247 |
+
Return True if the group had any elements."""
|
| 248 |
+
|
| 249 |
+
if group:
|
| 250 |
+
print('%s jobs:' % name)
|
| 251 |
+
for job in group:
|
| 252 |
+
print('%s : %s' % (job.num,job))
|
| 253 |
+
print()
|
| 254 |
+
return True
|
| 255 |
+
|
| 256 |
+
def _group_flush(self,group,name):
|
| 257 |
+
"""Flush a given job group
|
| 258 |
+
|
| 259 |
+
Return True if the group had any elements."""
|
| 260 |
+
|
| 261 |
+
njobs = len(group)
|
| 262 |
+
if njobs:
|
| 263 |
+
plural = {1:''}.setdefault(njobs,'s')
|
| 264 |
+
print('Flushing %s %s job%s.' % (njobs,name,plural))
|
| 265 |
+
group[:] = []
|
| 266 |
+
return True
|
| 267 |
+
|
| 268 |
+
def _status_new(self):
|
| 269 |
+
"""Print the status of newly finished jobs.
|
| 270 |
+
|
| 271 |
+
Return True if any new jobs are reported.
|
| 272 |
+
|
| 273 |
+
This call resets its own state every time, so it only reports jobs
|
| 274 |
+
which have finished since the last time it was called."""
|
| 275 |
+
|
| 276 |
+
self._update_status()
|
| 277 |
+
new_comp = self._group_report(self._comp_report, 'Completed')
|
| 278 |
+
new_dead = self._group_report(self._dead_report,
|
| 279 |
+
'Dead, call jobs.traceback() for details')
|
| 280 |
+
self._comp_report[:] = []
|
| 281 |
+
self._dead_report[:] = []
|
| 282 |
+
return new_comp or new_dead
|
| 283 |
+
|
| 284 |
+
def status(self,verbose=0):
|
| 285 |
+
"""Print a status of all jobs currently being managed."""
|
| 286 |
+
|
| 287 |
+
self._update_status()
|
| 288 |
+
self._group_report(self.running,'Running')
|
| 289 |
+
self._group_report(self.completed,'Completed')
|
| 290 |
+
self._group_report(self.dead,'Dead')
|
| 291 |
+
# Also flush the report queues
|
| 292 |
+
self._comp_report[:] = []
|
| 293 |
+
self._dead_report[:] = []
|
| 294 |
+
|
| 295 |
+
def remove(self,num):
|
| 296 |
+
"""Remove a finished (completed or dead) job."""
|
| 297 |
+
|
| 298 |
+
try:
|
| 299 |
+
job = self.all[num]
|
| 300 |
+
except KeyError:
|
| 301 |
+
error('Job #%s not found' % num)
|
| 302 |
+
else:
|
| 303 |
+
stat_code = job.stat_code
|
| 304 |
+
if stat_code == self._s_running:
|
| 305 |
+
error('Job #%s is still running, it can not be removed.' % num)
|
| 306 |
+
return
|
| 307 |
+
elif stat_code == self._s_completed:
|
| 308 |
+
self.completed.remove(job)
|
| 309 |
+
elif stat_code == self._s_dead:
|
| 310 |
+
self.dead.remove(job)
|
| 311 |
+
|
| 312 |
+
def flush(self):
|
| 313 |
+
"""Flush all finished jobs (completed and dead) from lists.
|
| 314 |
+
|
| 315 |
+
Running jobs are never flushed.
|
| 316 |
+
|
| 317 |
+
It first calls _status_new(), to update info. If any jobs have
|
| 318 |
+
completed since the last _status_new() call, the flush operation
|
| 319 |
+
aborts."""
|
| 320 |
+
|
| 321 |
+
# Remove the finished jobs from the master dict
|
| 322 |
+
alljobs = self.all
|
| 323 |
+
for job in self.completed+self.dead:
|
| 324 |
+
del(alljobs[job.num])
|
| 325 |
+
|
| 326 |
+
# Now flush these lists completely
|
| 327 |
+
fl_comp = self._group_flush(self.completed, 'Completed')
|
| 328 |
+
fl_dead = self._group_flush(self.dead, 'Dead')
|
| 329 |
+
if not (fl_comp or fl_dead):
|
| 330 |
+
print('No jobs to flush.')
|
| 331 |
+
|
| 332 |
+
def result(self,num):
|
| 333 |
+
"""result(N) -> return the result of job N."""
|
| 334 |
+
try:
|
| 335 |
+
return self.all[num].result
|
| 336 |
+
except KeyError:
|
| 337 |
+
error('Job #%s not found' % num)
|
| 338 |
+
|
| 339 |
+
def _traceback(self, job):
|
| 340 |
+
num = job if isinstance(job, int) else job.num
|
| 341 |
+
try:
|
| 342 |
+
self.all[num].traceback()
|
| 343 |
+
except KeyError:
|
| 344 |
+
error('Job #%s not found' % num)
|
| 345 |
+
|
| 346 |
+
def traceback(self, job=None):
|
| 347 |
+
if job is None:
|
| 348 |
+
self._update_status()
|
| 349 |
+
for deadjob in self.dead:
|
| 350 |
+
print("Traceback for: %r" % deadjob)
|
| 351 |
+
self._traceback(deadjob)
|
| 352 |
+
print()
|
| 353 |
+
else:
|
| 354 |
+
self._traceback(job)
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
class BackgroundJobBase(threading.Thread):
|
| 358 |
+
"""Base class to build BackgroundJob classes.
|
| 359 |
+
|
| 360 |
+
The derived classes must implement:
|
| 361 |
+
|
| 362 |
+
- Their own __init__, since the one here raises NotImplementedError. The
|
| 363 |
+
derived constructor must call self._init() at the end, to provide common
|
| 364 |
+
initialization.
|
| 365 |
+
|
| 366 |
+
- A strform attribute used in calls to __str__.
|
| 367 |
+
|
| 368 |
+
- A call() method, which will make the actual execution call and must
|
| 369 |
+
return a value to be held in the 'result' field of the job object.
|
| 370 |
+
"""
|
| 371 |
+
|
| 372 |
+
# Class constants for status, in string and as numerical codes (when
|
| 373 |
+
# updating jobs lists, we don't want to do string comparisons). This will
|
| 374 |
+
# be done at every user prompt, so it has to be as fast as possible
|
| 375 |
+
stat_created = 'Created'; stat_created_c = 0
|
| 376 |
+
stat_running = 'Running'; stat_running_c = 1
|
| 377 |
+
stat_completed = 'Completed'; stat_completed_c = 2
|
| 378 |
+
stat_dead = 'Dead (Exception), call jobs.traceback() for details'
|
| 379 |
+
stat_dead_c = -1
|
| 380 |
+
|
| 381 |
+
def __init__(self):
|
| 382 |
+
"""Must be implemented in subclasses.
|
| 383 |
+
|
| 384 |
+
Subclasses must call :meth:`_init` for standard initialisation.
|
| 385 |
+
"""
|
| 386 |
+
raise NotImplementedError("This class can not be instantiated directly.")
|
| 387 |
+
|
| 388 |
+
def _init(self):
|
| 389 |
+
"""Common initialization for all BackgroundJob objects"""
|
| 390 |
+
|
| 391 |
+
for attr in ['call','strform']:
|
| 392 |
+
assert hasattr(self,attr), "Missing attribute <%s>" % attr
|
| 393 |
+
|
| 394 |
+
# The num tag can be set by an external job manager
|
| 395 |
+
self.num = None
|
| 396 |
+
|
| 397 |
+
self.status = BackgroundJobBase.stat_created
|
| 398 |
+
self.stat_code = BackgroundJobBase.stat_created_c
|
| 399 |
+
self.finished = False
|
| 400 |
+
self.result = '<BackgroundJob has not completed>'
|
| 401 |
+
|
| 402 |
+
# reuse the ipython traceback handler if we can get to it, otherwise
|
| 403 |
+
# make a new one
|
| 404 |
+
try:
|
| 405 |
+
make_tb = get_ipython().InteractiveTB.text
|
| 406 |
+
except:
|
| 407 |
+
make_tb = AutoFormattedTB(
|
| 408 |
+
mode="Context", color_scheme="nocolor", tb_offset=1
|
| 409 |
+
).text
|
| 410 |
+
# Note that the actual API for text() requires the three args to be
|
| 411 |
+
# passed in, so we wrap it in a simple lambda.
|
| 412 |
+
self._make_tb = lambda : make_tb(None, None, None)
|
| 413 |
+
|
| 414 |
+
# Hold a formatted traceback if one is generated.
|
| 415 |
+
self._tb = None
|
| 416 |
+
|
| 417 |
+
threading.Thread.__init__(self)
|
| 418 |
+
|
| 419 |
+
def __str__(self):
|
| 420 |
+
return self.strform
|
| 421 |
+
|
| 422 |
+
def __repr__(self):
|
| 423 |
+
return '<BackgroundJob #%d: %s>' % (self.num, self.strform)
|
| 424 |
+
|
| 425 |
+
def traceback(self):
|
| 426 |
+
print(self._tb)
|
| 427 |
+
|
| 428 |
+
def run(self):
|
| 429 |
+
try:
|
| 430 |
+
self.status = BackgroundJobBase.stat_running
|
| 431 |
+
self.stat_code = BackgroundJobBase.stat_running_c
|
| 432 |
+
self.result = self.call()
|
| 433 |
+
except:
|
| 434 |
+
self.status = BackgroundJobBase.stat_dead
|
| 435 |
+
self.stat_code = BackgroundJobBase.stat_dead_c
|
| 436 |
+
self.finished = None
|
| 437 |
+
self.result = ('<BackgroundJob died, call jobs.traceback() for details>')
|
| 438 |
+
self._tb = self._make_tb()
|
| 439 |
+
else:
|
| 440 |
+
self.status = BackgroundJobBase.stat_completed
|
| 441 |
+
self.stat_code = BackgroundJobBase.stat_completed_c
|
| 442 |
+
self.finished = True
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
class BackgroundJobExpr(BackgroundJobBase):
|
| 446 |
+
"""Evaluate an expression as a background job (uses a separate thread)."""
|
| 447 |
+
|
| 448 |
+
def __init__(self, expression, glob=None, loc=None):
|
| 449 |
+
"""Create a new job from a string which can be fed to eval().
|
| 450 |
+
|
| 451 |
+
global/locals dicts can be provided, which will be passed to the eval
|
| 452 |
+
call."""
|
| 453 |
+
|
| 454 |
+
# fail immediately if the given expression can't be compiled
|
| 455 |
+
self.code = compile(expression,'<BackgroundJob compilation>','eval')
|
| 456 |
+
|
| 457 |
+
glob = {} if glob is None else glob
|
| 458 |
+
loc = {} if loc is None else loc
|
| 459 |
+
self.expression = self.strform = expression
|
| 460 |
+
self.glob = glob
|
| 461 |
+
self.loc = loc
|
| 462 |
+
self._init()
|
| 463 |
+
|
| 464 |
+
def call(self):
|
| 465 |
+
return eval(self.code,self.glob,self.loc)
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
class BackgroundJobFunc(BackgroundJobBase):
|
| 469 |
+
"""Run a function call as a background job (uses a separate thread)."""
|
| 470 |
+
|
| 471 |
+
def __init__(self, func, *args, **kwargs):
|
| 472 |
+
"""Create a new job from a callable object.
|
| 473 |
+
|
| 474 |
+
Any positional arguments and keyword args given to this constructor
|
| 475 |
+
after the initial callable are passed directly to it."""
|
| 476 |
+
|
| 477 |
+
if not callable(func):
|
| 478 |
+
raise TypeError(
|
| 479 |
+
'first argument to BackgroundJobFunc must be callable')
|
| 480 |
+
|
| 481 |
+
self.func = func
|
| 482 |
+
self.args = args
|
| 483 |
+
self.kwargs = kwargs
|
| 484 |
+
# The string form will only include the function passed, because
|
| 485 |
+
# generating string representations of the arguments is a potentially
|
| 486 |
+
# _very_ expensive operation (e.g. with large arrays).
|
| 487 |
+
self.strform = str(func)
|
| 488 |
+
self._init()
|
| 489 |
+
|
| 490 |
+
def call(self):
|
| 491 |
+
return self.func(*self.args, **self.kwargs)
|
lib/python3.12/site-packages/IPython/lib/clipboard.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" Utilities for accessing the platform's clipboard.
|
| 2 |
+
"""
|
| 3 |
+
|
| 4 |
+
import os
|
| 5 |
+
import subprocess
|
| 6 |
+
|
| 7 |
+
from IPython.core.error import TryNext
|
| 8 |
+
import IPython.utils.py3compat as py3compat
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class ClipboardEmpty(ValueError):
|
| 12 |
+
pass
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def win32_clipboard_get():
|
| 16 |
+
""" Get the current clipboard's text on Windows.
|
| 17 |
+
|
| 18 |
+
Requires Mark Hammond's pywin32 extensions.
|
| 19 |
+
"""
|
| 20 |
+
try:
|
| 21 |
+
import win32clipboard
|
| 22 |
+
except ImportError as e:
|
| 23 |
+
raise TryNext("Getting text from the clipboard requires the pywin32 "
|
| 24 |
+
"extensions: http://sourceforge.net/projects/pywin32/") from e
|
| 25 |
+
win32clipboard.OpenClipboard()
|
| 26 |
+
try:
|
| 27 |
+
text = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT)
|
| 28 |
+
except (TypeError, win32clipboard.error):
|
| 29 |
+
try:
|
| 30 |
+
text = win32clipboard.GetClipboardData(win32clipboard.CF_TEXT)
|
| 31 |
+
text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING)
|
| 32 |
+
except (TypeError, win32clipboard.error) as e:
|
| 33 |
+
raise ClipboardEmpty from e
|
| 34 |
+
finally:
|
| 35 |
+
win32clipboard.CloseClipboard()
|
| 36 |
+
return text
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def osx_clipboard_get() -> str:
|
| 40 |
+
""" Get the clipboard's text on OS X.
|
| 41 |
+
"""
|
| 42 |
+
p = subprocess.Popen(['pbpaste', '-Prefer', 'ascii'],
|
| 43 |
+
stdout=subprocess.PIPE)
|
| 44 |
+
bytes_, stderr = p.communicate()
|
| 45 |
+
# Text comes in with old Mac \r line endings. Change them to \n.
|
| 46 |
+
bytes_ = bytes_.replace(b'\r', b'\n')
|
| 47 |
+
text = py3compat.decode(bytes_)
|
| 48 |
+
return text
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def tkinter_clipboard_get():
|
| 52 |
+
""" Get the clipboard's text using Tkinter.
|
| 53 |
+
|
| 54 |
+
This is the default on systems that are not Windows or OS X. It may
|
| 55 |
+
interfere with other UI toolkits and should be replaced with an
|
| 56 |
+
implementation that uses that toolkit.
|
| 57 |
+
"""
|
| 58 |
+
try:
|
| 59 |
+
from tkinter import Tk, TclError
|
| 60 |
+
except ImportError as e:
|
| 61 |
+
raise TryNext("Getting text from the clipboard on this platform requires tkinter.") from e
|
| 62 |
+
|
| 63 |
+
root = Tk()
|
| 64 |
+
root.withdraw()
|
| 65 |
+
try:
|
| 66 |
+
text = root.clipboard_get()
|
| 67 |
+
except TclError as e:
|
| 68 |
+
raise ClipboardEmpty from e
|
| 69 |
+
finally:
|
| 70 |
+
root.destroy()
|
| 71 |
+
text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING)
|
| 72 |
+
return text
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def wayland_clipboard_get():
|
| 76 |
+
"""Get the clipboard's text under Wayland using wl-paste command.
|
| 77 |
+
|
| 78 |
+
This requires Wayland and wl-clipboard installed and running.
|
| 79 |
+
"""
|
| 80 |
+
if os.environ.get("XDG_SESSION_TYPE") != "wayland":
|
| 81 |
+
raise TryNext("wayland is not detected")
|
| 82 |
+
|
| 83 |
+
try:
|
| 84 |
+
with subprocess.Popen(["wl-paste"], stdout=subprocess.PIPE) as p:
|
| 85 |
+
raw, err = p.communicate()
|
| 86 |
+
if p.wait():
|
| 87 |
+
raise TryNext(err)
|
| 88 |
+
except FileNotFoundError as e:
|
| 89 |
+
raise TryNext(
|
| 90 |
+
"Getting text from the clipboard under Wayland requires the wl-clipboard "
|
| 91 |
+
"extension: https://github.com/bugaevc/wl-clipboard"
|
| 92 |
+
) from e
|
| 93 |
+
|
| 94 |
+
if not raw:
|
| 95 |
+
raise ClipboardEmpty
|
| 96 |
+
|
| 97 |
+
try:
|
| 98 |
+
text = py3compat.decode(raw)
|
| 99 |
+
except UnicodeDecodeError as e:
|
| 100 |
+
raise ClipboardEmpty from e
|
| 101 |
+
|
| 102 |
+
return text
|
lib/python3.12/site-packages/IPython/lib/deepreload.py
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
Provides a reload() function that acts recursively.
|
| 4 |
+
|
| 5 |
+
Python's normal :func:`python:reload` function only reloads the module that it's
|
| 6 |
+
passed. The :func:`reload` function in this module also reloads everything
|
| 7 |
+
imported from that module, which is useful when you're changing files deep
|
| 8 |
+
inside a package.
|
| 9 |
+
|
| 10 |
+
To use this as your default reload function, type this::
|
| 11 |
+
|
| 12 |
+
import builtins
|
| 13 |
+
from IPython.lib import deepreload
|
| 14 |
+
builtins.reload = deepreload.reload
|
| 15 |
+
|
| 16 |
+
A reference to the original :func:`python:reload` is stored in this module as
|
| 17 |
+
:data:`original_reload`, so you can restore it later.
|
| 18 |
+
|
| 19 |
+
This code is almost entirely based on knee.py, which is a Python
|
| 20 |
+
re-implementation of hierarchical module import.
|
| 21 |
+
"""
|
| 22 |
+
#*****************************************************************************
|
| 23 |
+
# Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
|
| 24 |
+
#
|
| 25 |
+
# Distributed under the terms of the BSD License. The full license is in
|
| 26 |
+
# the file COPYING, distributed as part of this software.
|
| 27 |
+
#*****************************************************************************
|
| 28 |
+
|
| 29 |
+
import builtins as builtin_mod
|
| 30 |
+
from contextlib import contextmanager
|
| 31 |
+
import importlib
|
| 32 |
+
import sys
|
| 33 |
+
|
| 34 |
+
from types import ModuleType
|
| 35 |
+
from warnings import warn
|
| 36 |
+
import types
|
| 37 |
+
|
| 38 |
+
original_import = builtin_mod.__import__
|
| 39 |
+
|
| 40 |
+
@contextmanager
|
| 41 |
+
def replace_import_hook(new_import):
|
| 42 |
+
saved_import = builtin_mod.__import__
|
| 43 |
+
builtin_mod.__import__ = new_import
|
| 44 |
+
try:
|
| 45 |
+
yield
|
| 46 |
+
finally:
|
| 47 |
+
builtin_mod.__import__ = saved_import
|
| 48 |
+
|
| 49 |
+
def get_parent(globals, level):
|
| 50 |
+
"""
|
| 51 |
+
parent, name = get_parent(globals, level)
|
| 52 |
+
|
| 53 |
+
Return the package that an import is being performed in. If globals comes
|
| 54 |
+
from the module foo.bar.bat (not itself a package), this returns the
|
| 55 |
+
sys.modules entry for foo.bar. If globals is from a package's __init__.py,
|
| 56 |
+
the package's entry in sys.modules is returned.
|
| 57 |
+
|
| 58 |
+
If globals doesn't come from a package or a module in a package, or a
|
| 59 |
+
corresponding entry is not found in sys.modules, None is returned.
|
| 60 |
+
"""
|
| 61 |
+
orig_level = level
|
| 62 |
+
|
| 63 |
+
if not level or not isinstance(globals, dict):
|
| 64 |
+
return None, ''
|
| 65 |
+
|
| 66 |
+
pkgname = globals.get('__package__', None)
|
| 67 |
+
|
| 68 |
+
if pkgname is not None:
|
| 69 |
+
# __package__ is set, so use it
|
| 70 |
+
if not hasattr(pkgname, 'rindex'):
|
| 71 |
+
raise ValueError('__package__ set to non-string')
|
| 72 |
+
if len(pkgname) == 0:
|
| 73 |
+
if level > 0:
|
| 74 |
+
raise ValueError('Attempted relative import in non-package')
|
| 75 |
+
return None, ''
|
| 76 |
+
name = pkgname
|
| 77 |
+
else:
|
| 78 |
+
# __package__ not set, so figure it out and set it
|
| 79 |
+
if '__name__' not in globals:
|
| 80 |
+
return None, ''
|
| 81 |
+
modname = globals['__name__']
|
| 82 |
+
|
| 83 |
+
if '__path__' in globals:
|
| 84 |
+
# __path__ is set, so modname is already the package name
|
| 85 |
+
globals['__package__'] = name = modname
|
| 86 |
+
else:
|
| 87 |
+
# Normal module, so work out the package name if any
|
| 88 |
+
lastdot = modname.rfind('.')
|
| 89 |
+
if lastdot < 0 < level:
|
| 90 |
+
raise ValueError("Attempted relative import in non-package")
|
| 91 |
+
if lastdot < 0:
|
| 92 |
+
globals['__package__'] = None
|
| 93 |
+
return None, ''
|
| 94 |
+
globals['__package__'] = name = modname[:lastdot]
|
| 95 |
+
|
| 96 |
+
dot = len(name)
|
| 97 |
+
for x in range(level, 1, -1):
|
| 98 |
+
try:
|
| 99 |
+
dot = name.rindex('.', 0, dot)
|
| 100 |
+
except ValueError as e:
|
| 101 |
+
raise ValueError("attempted relative import beyond top-level "
|
| 102 |
+
"package") from e
|
| 103 |
+
name = name[:dot]
|
| 104 |
+
|
| 105 |
+
try:
|
| 106 |
+
parent = sys.modules[name]
|
| 107 |
+
except BaseException as e:
|
| 108 |
+
if orig_level < 1:
|
| 109 |
+
warn("Parent module '%.200s' not found while handling absolute "
|
| 110 |
+
"import" % name)
|
| 111 |
+
parent = None
|
| 112 |
+
else:
|
| 113 |
+
raise SystemError("Parent module '%.200s' not loaded, cannot "
|
| 114 |
+
"perform relative import" % name) from e
|
| 115 |
+
|
| 116 |
+
# We expect, but can't guarantee, if parent != None, that:
|
| 117 |
+
# - parent.__name__ == name
|
| 118 |
+
# - parent.__dict__ is globals
|
| 119 |
+
# If this is violated... Who cares?
|
| 120 |
+
return parent, name
|
| 121 |
+
|
| 122 |
+
def load_next(mod, altmod, name, buf):
|
| 123 |
+
"""
|
| 124 |
+
mod, name, buf = load_next(mod, altmod, name, buf)
|
| 125 |
+
|
| 126 |
+
altmod is either None or same as mod
|
| 127 |
+
"""
|
| 128 |
+
|
| 129 |
+
if len(name) == 0:
|
| 130 |
+
# completely empty module name should only happen in
|
| 131 |
+
# 'from . import' (or '__import__("")')
|
| 132 |
+
return mod, None, buf
|
| 133 |
+
|
| 134 |
+
dot = name.find('.')
|
| 135 |
+
if dot == 0:
|
| 136 |
+
raise ValueError('Empty module name')
|
| 137 |
+
|
| 138 |
+
if dot < 0:
|
| 139 |
+
subname = name
|
| 140 |
+
next = None
|
| 141 |
+
else:
|
| 142 |
+
subname = name[:dot]
|
| 143 |
+
next = name[dot+1:]
|
| 144 |
+
|
| 145 |
+
if buf != '':
|
| 146 |
+
buf += '.'
|
| 147 |
+
buf += subname
|
| 148 |
+
|
| 149 |
+
result = import_submodule(mod, subname, buf)
|
| 150 |
+
if result is None and mod != altmod:
|
| 151 |
+
result = import_submodule(altmod, subname, subname)
|
| 152 |
+
if result is not None:
|
| 153 |
+
buf = subname
|
| 154 |
+
|
| 155 |
+
if result is None:
|
| 156 |
+
raise ImportError("No module named %.200s" % name)
|
| 157 |
+
|
| 158 |
+
return result, next, buf
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
# Need to keep track of what we've already reloaded to prevent cyclic evil
|
| 162 |
+
found_now = {}
|
| 163 |
+
|
| 164 |
+
def import_submodule(mod, subname, fullname):
|
| 165 |
+
"""m = import_submodule(mod, subname, fullname)"""
|
| 166 |
+
# Require:
|
| 167 |
+
# if mod == None: subname == fullname
|
| 168 |
+
# else: mod.__name__ + "." + subname == fullname
|
| 169 |
+
|
| 170 |
+
global found_now
|
| 171 |
+
if fullname in found_now and fullname in sys.modules:
|
| 172 |
+
m = sys.modules[fullname]
|
| 173 |
+
else:
|
| 174 |
+
print('Reloading', fullname)
|
| 175 |
+
found_now[fullname] = 1
|
| 176 |
+
oldm = sys.modules.get(fullname, None)
|
| 177 |
+
try:
|
| 178 |
+
if oldm is not None:
|
| 179 |
+
m = importlib.reload(oldm)
|
| 180 |
+
else:
|
| 181 |
+
m = importlib.import_module(subname, mod)
|
| 182 |
+
except:
|
| 183 |
+
# load_module probably removed name from modules because of
|
| 184 |
+
# the error. Put back the original module object.
|
| 185 |
+
if oldm:
|
| 186 |
+
sys.modules[fullname] = oldm
|
| 187 |
+
raise
|
| 188 |
+
|
| 189 |
+
add_submodule(mod, m, fullname, subname)
|
| 190 |
+
|
| 191 |
+
return m
|
| 192 |
+
|
| 193 |
+
def add_submodule(mod, submod, fullname, subname):
|
| 194 |
+
"""mod.{subname} = submod"""
|
| 195 |
+
if mod is None:
|
| 196 |
+
return #Nothing to do here.
|
| 197 |
+
|
| 198 |
+
if submod is None:
|
| 199 |
+
submod = sys.modules[fullname]
|
| 200 |
+
|
| 201 |
+
setattr(mod, subname, submod)
|
| 202 |
+
|
| 203 |
+
return
|
| 204 |
+
|
| 205 |
+
def ensure_fromlist(mod, fromlist, buf, recursive):
|
| 206 |
+
"""Handle 'from module import a, b, c' imports."""
|
| 207 |
+
if not hasattr(mod, '__path__'):
|
| 208 |
+
return
|
| 209 |
+
for item in fromlist:
|
| 210 |
+
if not hasattr(item, 'rindex'):
|
| 211 |
+
raise TypeError("Item in ``from list'' not a string")
|
| 212 |
+
if item == '*':
|
| 213 |
+
if recursive:
|
| 214 |
+
continue # avoid endless recursion
|
| 215 |
+
try:
|
| 216 |
+
all = mod.__all__
|
| 217 |
+
except AttributeError:
|
| 218 |
+
pass
|
| 219 |
+
else:
|
| 220 |
+
ret = ensure_fromlist(mod, all, buf, 1)
|
| 221 |
+
if not ret:
|
| 222 |
+
return 0
|
| 223 |
+
elif not hasattr(mod, item):
|
| 224 |
+
import_submodule(mod, item, buf + '.' + item)
|
| 225 |
+
|
| 226 |
+
def deep_import_hook(name, globals=None, locals=None, fromlist=None, level=-1):
|
| 227 |
+
"""Replacement for __import__()"""
|
| 228 |
+
parent, buf = get_parent(globals, level)
|
| 229 |
+
|
| 230 |
+
head, name, buf = load_next(parent, None if level < 0 else parent, name, buf)
|
| 231 |
+
|
| 232 |
+
tail = head
|
| 233 |
+
while name:
|
| 234 |
+
tail, name, buf = load_next(tail, tail, name, buf)
|
| 235 |
+
|
| 236 |
+
# If tail is None, both get_parent and load_next found
|
| 237 |
+
# an empty module name: someone called __import__("") or
|
| 238 |
+
# doctored faulty bytecode
|
| 239 |
+
if tail is None:
|
| 240 |
+
raise ValueError('Empty module name')
|
| 241 |
+
|
| 242 |
+
if not fromlist:
|
| 243 |
+
return head
|
| 244 |
+
|
| 245 |
+
ensure_fromlist(tail, fromlist, buf, 0)
|
| 246 |
+
return tail
|
| 247 |
+
|
| 248 |
+
modules_reloading = {}
|
| 249 |
+
|
| 250 |
+
def deep_reload_hook(m):
|
| 251 |
+
"""Replacement for reload()."""
|
| 252 |
+
# Hardcode this one as it would raise a NotImplementedError from the
|
| 253 |
+
# bowels of Python and screw up the import machinery after.
|
| 254 |
+
# unlike other imports the `exclude` list already in place is not enough.
|
| 255 |
+
|
| 256 |
+
if m is types:
|
| 257 |
+
return m
|
| 258 |
+
if not isinstance(m, ModuleType):
|
| 259 |
+
raise TypeError("reload() argument must be module")
|
| 260 |
+
|
| 261 |
+
name = m.__name__
|
| 262 |
+
|
| 263 |
+
if name not in sys.modules:
|
| 264 |
+
raise ImportError("reload(): module %.200s not in sys.modules" % name)
|
| 265 |
+
|
| 266 |
+
global modules_reloading
|
| 267 |
+
try:
|
| 268 |
+
return modules_reloading[name]
|
| 269 |
+
except:
|
| 270 |
+
modules_reloading[name] = m
|
| 271 |
+
|
| 272 |
+
try:
|
| 273 |
+
newm = importlib.reload(m)
|
| 274 |
+
except:
|
| 275 |
+
sys.modules[name] = m
|
| 276 |
+
raise
|
| 277 |
+
finally:
|
| 278 |
+
modules_reloading.clear()
|
| 279 |
+
return newm
|
| 280 |
+
|
| 281 |
+
# Save the original hooks
|
| 282 |
+
original_reload = importlib.reload
|
| 283 |
+
|
| 284 |
+
# Replacement for reload()
|
| 285 |
+
def reload(
|
| 286 |
+
module,
|
| 287 |
+
exclude=(
|
| 288 |
+
*sys.builtin_module_names,
|
| 289 |
+
"sys",
|
| 290 |
+
"os.path",
|
| 291 |
+
"builtins",
|
| 292 |
+
"__main__",
|
| 293 |
+
"numpy",
|
| 294 |
+
"numpy._globals",
|
| 295 |
+
),
|
| 296 |
+
):
|
| 297 |
+
"""Recursively reload all modules used in the given module. Optionally
|
| 298 |
+
takes a list of modules to exclude from reloading. The default exclude
|
| 299 |
+
list contains modules listed in sys.builtin_module_names with additional
|
| 300 |
+
sys, os.path, builtins and __main__, to prevent, e.g., resetting
|
| 301 |
+
display, exception, and io hooks.
|
| 302 |
+
"""
|
| 303 |
+
global found_now
|
| 304 |
+
for i in exclude:
|
| 305 |
+
found_now[i] = 1
|
| 306 |
+
try:
|
| 307 |
+
with replace_import_hook(deep_import_hook):
|
| 308 |
+
return deep_reload_hook(module)
|
| 309 |
+
finally:
|
| 310 |
+
found_now = {}
|
lib/python3.12/site-packages/IPython/lib/demo.py
ADDED
|
@@ -0,0 +1,672 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Module for interactive demos using IPython.
|
| 2 |
+
|
| 3 |
+
This module implements a few classes for running Python scripts interactively
|
| 4 |
+
in IPython for demonstrations. With very simple markup (a few tags in
|
| 5 |
+
comments), you can control points where the script stops executing and returns
|
| 6 |
+
control to IPython.
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
Provided classes
|
| 10 |
+
----------------
|
| 11 |
+
|
| 12 |
+
The classes are (see their docstrings for further details):
|
| 13 |
+
|
| 14 |
+
- Demo: pure python demos
|
| 15 |
+
|
| 16 |
+
- IPythonDemo: demos with input to be processed by IPython as if it had been
|
| 17 |
+
typed interactively (so magics work, as well as any other special syntax you
|
| 18 |
+
may have added via input prefilters).
|
| 19 |
+
|
| 20 |
+
- LineDemo: single-line version of the Demo class. These demos are executed
|
| 21 |
+
one line at a time, and require no markup.
|
| 22 |
+
|
| 23 |
+
- IPythonLineDemo: IPython version of the LineDemo class (the demo is
|
| 24 |
+
executed a line at a time, but processed via IPython).
|
| 25 |
+
|
| 26 |
+
- ClearMixin: mixin to make Demo classes with less visual clutter. It
|
| 27 |
+
declares an empty marquee and a pre_cmd that clears the screen before each
|
| 28 |
+
block (see Subclassing below).
|
| 29 |
+
|
| 30 |
+
- ClearDemo, ClearIPDemo: mixin-enabled versions of the Demo and IPythonDemo
|
| 31 |
+
classes.
|
| 32 |
+
|
| 33 |
+
Inheritance diagram:
|
| 34 |
+
|
| 35 |
+
.. inheritance-diagram:: IPython.lib.demo
|
| 36 |
+
:parts: 3
|
| 37 |
+
|
| 38 |
+
Subclassing
|
| 39 |
+
-----------
|
| 40 |
+
|
| 41 |
+
The classes here all include a few methods meant to make customization by
|
| 42 |
+
subclassing more convenient. Their docstrings below have some more details:
|
| 43 |
+
|
| 44 |
+
- highlight(): format every block and optionally highlight comments and
|
| 45 |
+
docstring content.
|
| 46 |
+
|
| 47 |
+
- marquee(): generates a marquee to provide visible on-screen markers at each
|
| 48 |
+
block start and end.
|
| 49 |
+
|
| 50 |
+
- pre_cmd(): run right before the execution of each block.
|
| 51 |
+
|
| 52 |
+
- post_cmd(): run right after the execution of each block. If the block
|
| 53 |
+
raises an exception, this is NOT called.
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
Operation
|
| 57 |
+
---------
|
| 58 |
+
|
| 59 |
+
The file is run in its own empty namespace (though you can pass it a string of
|
| 60 |
+
arguments as if in a command line environment, and it will see those as
|
| 61 |
+
sys.argv). But at each stop, the global IPython namespace is updated with the
|
| 62 |
+
current internal demo namespace, so you can work interactively with the data
|
| 63 |
+
accumulated so far.
|
| 64 |
+
|
| 65 |
+
By default, each block of code is printed (with syntax highlighting) before
|
| 66 |
+
executing it and you have to confirm execution. This is intended to show the
|
| 67 |
+
code to an audience first so you can discuss it, and only proceed with
|
| 68 |
+
execution once you agree. There are a few tags which allow you to modify this
|
| 69 |
+
behavior.
|
| 70 |
+
|
| 71 |
+
The supported tags are:
|
| 72 |
+
|
| 73 |
+
# <demo> stop
|
| 74 |
+
|
| 75 |
+
Defines block boundaries, the points where IPython stops execution of the
|
| 76 |
+
file and returns to the interactive prompt.
|
| 77 |
+
|
| 78 |
+
You can optionally mark the stop tag with extra dashes before and after the
|
| 79 |
+
word 'stop', to help visually distinguish the blocks in a text editor:
|
| 80 |
+
|
| 81 |
+
# <demo> --- stop ---
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
# <demo> silent
|
| 85 |
+
|
| 86 |
+
Make a block execute silently (and hence automatically). Typically used in
|
| 87 |
+
cases where you have some boilerplate or initialization code which you need
|
| 88 |
+
executed but do not want to be seen in the demo.
|
| 89 |
+
|
| 90 |
+
# <demo> auto
|
| 91 |
+
|
| 92 |
+
Make a block execute automatically, but still being printed. Useful for
|
| 93 |
+
simple code which does not warrant discussion, since it avoids the extra
|
| 94 |
+
manual confirmation.
|
| 95 |
+
|
| 96 |
+
# <demo> auto_all
|
| 97 |
+
|
| 98 |
+
This tag can _only_ be in the first block, and if given it overrides the
|
| 99 |
+
individual auto tags to make the whole demo fully automatic (no block asks
|
| 100 |
+
for confirmation). It can also be given at creation time (or the attribute
|
| 101 |
+
set later) to override what's in the file.
|
| 102 |
+
|
| 103 |
+
While _any_ python file can be run as a Demo instance, if there are no stop
|
| 104 |
+
tags the whole file will run in a single block (no different that calling
|
| 105 |
+
first %pycat and then %run). The minimal markup to make this useful is to
|
| 106 |
+
place a set of stop tags; the other tags are only there to let you fine-tune
|
| 107 |
+
the execution.
|
| 108 |
+
|
| 109 |
+
This is probably best explained with the simple example file below. You can
|
| 110 |
+
copy this into a file named ex_demo.py, and try running it via::
|
| 111 |
+
|
| 112 |
+
from IPython.lib.demo import Demo
|
| 113 |
+
d = Demo('ex_demo.py')
|
| 114 |
+
d()
|
| 115 |
+
|
| 116 |
+
Each time you call the demo object, it runs the next block. The demo object
|
| 117 |
+
has a few useful methods for navigation, like again(), edit(), jump(), seek()
|
| 118 |
+
and back(). It can be reset for a new run via reset() or reloaded from disk
|
| 119 |
+
(in case you've edited the source) via reload(). See their docstrings below.
|
| 120 |
+
|
| 121 |
+
Note: To make this simpler to explore, a file called "demo-exercizer.py" has
|
| 122 |
+
been added to the "docs/examples/core" directory. Just cd to this directory in
|
| 123 |
+
an IPython session, and type::
|
| 124 |
+
|
| 125 |
+
%run demo-exercizer.py
|
| 126 |
+
|
| 127 |
+
and then follow the directions.
|
| 128 |
+
|
| 129 |
+
Example
|
| 130 |
+
-------
|
| 131 |
+
|
| 132 |
+
The following is a very simple example of a valid demo file.
|
| 133 |
+
|
| 134 |
+
::
|
| 135 |
+
|
| 136 |
+
#################### EXAMPLE DEMO <ex_demo.py> ###############################
|
| 137 |
+
'''A simple interactive demo to illustrate the use of IPython's Demo class.'''
|
| 138 |
+
|
| 139 |
+
print('Hello, welcome to an interactive IPython demo.')
|
| 140 |
+
|
| 141 |
+
# The mark below defines a block boundary, which is a point where IPython will
|
| 142 |
+
# stop execution and return to the interactive prompt. The dashes are actually
|
| 143 |
+
# optional and used only as a visual aid to clearly separate blocks while
|
| 144 |
+
# editing the demo code.
|
| 145 |
+
# <demo> stop
|
| 146 |
+
|
| 147 |
+
x = 1
|
| 148 |
+
y = 2
|
| 149 |
+
|
| 150 |
+
# <demo> stop
|
| 151 |
+
|
| 152 |
+
# the mark below makes this block as silent
|
| 153 |
+
# <demo> silent
|
| 154 |
+
|
| 155 |
+
print('This is a silent block, which gets executed but not printed.')
|
| 156 |
+
|
| 157 |
+
# <demo> stop
|
| 158 |
+
# <demo> auto
|
| 159 |
+
print('This is an automatic block.')
|
| 160 |
+
print('It is executed without asking for confirmation, but printed.')
|
| 161 |
+
z = x + y
|
| 162 |
+
|
| 163 |
+
print('z =', x)
|
| 164 |
+
|
| 165 |
+
# <demo> stop
|
| 166 |
+
# This is just another normal block.
|
| 167 |
+
print('z is now:', z)
|
| 168 |
+
|
| 169 |
+
print('bye!')
|
| 170 |
+
################### END EXAMPLE DEMO <ex_demo.py> ############################
|
| 171 |
+
"""
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
#*****************************************************************************
|
| 175 |
+
# Copyright (C) 2005-2006 Fernando Perez. <Fernando.Perez@colorado.edu>
|
| 176 |
+
#
|
| 177 |
+
# Distributed under the terms of the BSD License. The full license is in
|
| 178 |
+
# the file COPYING, distributed as part of this software.
|
| 179 |
+
#
|
| 180 |
+
#*****************************************************************************
|
| 181 |
+
|
| 182 |
+
import os
|
| 183 |
+
import re
|
| 184 |
+
import shlex
|
| 185 |
+
import sys
|
| 186 |
+
import pygments
|
| 187 |
+
from pathlib import Path
|
| 188 |
+
|
| 189 |
+
from IPython.utils.text import marquee
|
| 190 |
+
from IPython.utils import openpy
|
| 191 |
+
from IPython.utils import py3compat
|
| 192 |
+
__all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError']
|
| 193 |
+
|
| 194 |
+
class DemoError(Exception): pass
|
| 195 |
+
|
| 196 |
+
def re_mark(mark):
|
| 197 |
+
return re.compile(r'^\s*#\s+<demo>\s+%s\s*$' % mark,re.MULTILINE)
|
| 198 |
+
|
| 199 |
+
class Demo:
|
| 200 |
+
|
| 201 |
+
re_stop = re_mark(r'-*\s?stop\s?-*')
|
| 202 |
+
re_silent = re_mark('silent')
|
| 203 |
+
re_auto = re_mark('auto')
|
| 204 |
+
re_auto_all = re_mark('auto_all')
|
| 205 |
+
|
| 206 |
+
def __init__(self,src,title='',arg_str='',auto_all=None, format_rst=False,
|
| 207 |
+
formatter='terminal', style='default'):
|
| 208 |
+
"""Make a new demo object. To run the demo, simply call the object.
|
| 209 |
+
|
| 210 |
+
See the module docstring for full details and an example (you can use
|
| 211 |
+
IPython.Demo? in IPython to see it).
|
| 212 |
+
|
| 213 |
+
Inputs:
|
| 214 |
+
|
| 215 |
+
- src is either a file, or file-like object, or a
|
| 216 |
+
string that can be resolved to a filename.
|
| 217 |
+
|
| 218 |
+
Optional inputs:
|
| 219 |
+
|
| 220 |
+
- title: a string to use as the demo name. Of most use when the demo
|
| 221 |
+
you are making comes from an object that has no filename, or if you
|
| 222 |
+
want an alternate denotation distinct from the filename.
|
| 223 |
+
|
| 224 |
+
- arg_str(''): a string of arguments, internally converted to a list
|
| 225 |
+
just like sys.argv, so the demo script can see a similar
|
| 226 |
+
environment.
|
| 227 |
+
|
| 228 |
+
- auto_all(None): global flag to run all blocks automatically without
|
| 229 |
+
confirmation. This attribute overrides the block-level tags and
|
| 230 |
+
applies to the whole demo. It is an attribute of the object, and
|
| 231 |
+
can be changed at runtime simply by reassigning it to a boolean
|
| 232 |
+
value.
|
| 233 |
+
|
| 234 |
+
- format_rst(False): a bool to enable comments and doc strings
|
| 235 |
+
formatting with pygments rst lexer
|
| 236 |
+
|
| 237 |
+
- formatter('terminal'): a string of pygments formatter name to be
|
| 238 |
+
used. Useful values for terminals: terminal, terminal256,
|
| 239 |
+
terminal16m
|
| 240 |
+
|
| 241 |
+
- style('default'): a string of pygments style name to be used.
|
| 242 |
+
"""
|
| 243 |
+
if hasattr(src, "read"):
|
| 244 |
+
# It seems to be a file or a file-like object
|
| 245 |
+
self.fname = "from a file-like object"
|
| 246 |
+
if title == '':
|
| 247 |
+
self.title = "from a file-like object"
|
| 248 |
+
else:
|
| 249 |
+
self.title = title
|
| 250 |
+
else:
|
| 251 |
+
# Assume it's a string or something that can be converted to one
|
| 252 |
+
self.fname = src
|
| 253 |
+
if title == '':
|
| 254 |
+
(filepath, filename) = os.path.split(src)
|
| 255 |
+
self.title = filename
|
| 256 |
+
else:
|
| 257 |
+
self.title = title
|
| 258 |
+
self.sys_argv = [src] + shlex.split(arg_str)
|
| 259 |
+
self.auto_all = auto_all
|
| 260 |
+
self.src = src
|
| 261 |
+
|
| 262 |
+
try:
|
| 263 |
+
ip = get_ipython() # this is in builtins whenever IPython is running
|
| 264 |
+
self.inside_ipython = True
|
| 265 |
+
except NameError:
|
| 266 |
+
self.inside_ipython = False
|
| 267 |
+
|
| 268 |
+
if self.inside_ipython:
|
| 269 |
+
# get a few things from ipython. While it's a bit ugly design-wise,
|
| 270 |
+
# it ensures that things like color scheme and the like are always in
|
| 271 |
+
# sync with the ipython mode being used. This class is only meant to
|
| 272 |
+
# be used inside ipython anyways, so it's OK.
|
| 273 |
+
self.ip_ns = ip.user_ns
|
| 274 |
+
self.ip_colorize = ip.pycolorize
|
| 275 |
+
self.ip_showtb = ip.showtraceback
|
| 276 |
+
self.ip_run_cell = ip.run_cell
|
| 277 |
+
self.shell = ip
|
| 278 |
+
|
| 279 |
+
self.formatter = pygments.formatters.get_formatter_by_name(formatter,
|
| 280 |
+
style=style)
|
| 281 |
+
self.python_lexer = pygments.lexers.get_lexer_by_name("py3")
|
| 282 |
+
self.format_rst = format_rst
|
| 283 |
+
if format_rst:
|
| 284 |
+
self.rst_lexer = pygments.lexers.get_lexer_by_name("rst")
|
| 285 |
+
|
| 286 |
+
# load user data and initialize data structures
|
| 287 |
+
self.reload()
|
| 288 |
+
|
| 289 |
+
def fload(self):
|
| 290 |
+
"""Load file object."""
|
| 291 |
+
# read data and parse into blocks
|
| 292 |
+
if hasattr(self, 'fobj') and self.fobj is not None:
|
| 293 |
+
self.fobj.close()
|
| 294 |
+
if hasattr(self.src, "read"):
|
| 295 |
+
# It seems to be a file or a file-like object
|
| 296 |
+
self.fobj = self.src
|
| 297 |
+
else:
|
| 298 |
+
# Assume it's a string or something that can be converted to one
|
| 299 |
+
self.fobj = openpy.open(self.fname)
|
| 300 |
+
|
| 301 |
+
def reload(self):
|
| 302 |
+
"""Reload source from disk and initialize state."""
|
| 303 |
+
self.fload()
|
| 304 |
+
|
| 305 |
+
self.src = "".join(openpy.strip_encoding_cookie(self.fobj))
|
| 306 |
+
src_b = [b.strip() for b in self.re_stop.split(self.src) if b]
|
| 307 |
+
self._silent = [bool(self.re_silent.findall(b)) for b in src_b]
|
| 308 |
+
self._auto = [bool(self.re_auto.findall(b)) for b in src_b]
|
| 309 |
+
|
| 310 |
+
# if auto_all is not given (def. None), we read it from the file
|
| 311 |
+
if self.auto_all is None:
|
| 312 |
+
self.auto_all = bool(self.re_auto_all.findall(src_b[0]))
|
| 313 |
+
else:
|
| 314 |
+
self.auto_all = bool(self.auto_all)
|
| 315 |
+
|
| 316 |
+
# Clean the sources from all markup so it doesn't get displayed when
|
| 317 |
+
# running the demo
|
| 318 |
+
src_blocks = []
|
| 319 |
+
auto_strip = lambda s: self.re_auto.sub('',s)
|
| 320 |
+
for i,b in enumerate(src_b):
|
| 321 |
+
if self._auto[i]:
|
| 322 |
+
src_blocks.append(auto_strip(b))
|
| 323 |
+
else:
|
| 324 |
+
src_blocks.append(b)
|
| 325 |
+
# remove the auto_all marker
|
| 326 |
+
src_blocks[0] = self.re_auto_all.sub('',src_blocks[0])
|
| 327 |
+
|
| 328 |
+
self.nblocks = len(src_blocks)
|
| 329 |
+
self.src_blocks = src_blocks
|
| 330 |
+
|
| 331 |
+
# also build syntax-highlighted source
|
| 332 |
+
self.src_blocks_colored = list(map(self.highlight,self.src_blocks))
|
| 333 |
+
|
| 334 |
+
# ensure clean namespace and seek offset
|
| 335 |
+
self.reset()
|
| 336 |
+
|
| 337 |
+
def reset(self):
|
| 338 |
+
"""Reset the namespace and seek pointer to restart the demo"""
|
| 339 |
+
self.user_ns = {}
|
| 340 |
+
self.finished = False
|
| 341 |
+
self.block_index = 0
|
| 342 |
+
|
| 343 |
+
def _validate_index(self,index):
|
| 344 |
+
if index<0 or index>=self.nblocks:
|
| 345 |
+
raise ValueError('invalid block index %s' % index)
|
| 346 |
+
|
| 347 |
+
def _get_index(self,index):
|
| 348 |
+
"""Get the current block index, validating and checking status.
|
| 349 |
+
|
| 350 |
+
Returns None if the demo is finished"""
|
| 351 |
+
|
| 352 |
+
if index is None:
|
| 353 |
+
if self.finished:
|
| 354 |
+
print('Demo finished. Use <demo_name>.reset() if you want to rerun it.')
|
| 355 |
+
return None
|
| 356 |
+
index = self.block_index
|
| 357 |
+
else:
|
| 358 |
+
self._validate_index(index)
|
| 359 |
+
return index
|
| 360 |
+
|
| 361 |
+
def seek(self,index):
|
| 362 |
+
"""Move the current seek pointer to the given block.
|
| 363 |
+
|
| 364 |
+
You can use negative indices to seek from the end, with identical
|
| 365 |
+
semantics to those of Python lists."""
|
| 366 |
+
if index<0:
|
| 367 |
+
index = self.nblocks + index
|
| 368 |
+
self._validate_index(index)
|
| 369 |
+
self.block_index = index
|
| 370 |
+
self.finished = False
|
| 371 |
+
|
| 372 |
+
def back(self,num=1):
|
| 373 |
+
"""Move the seek pointer back num blocks (default is 1)."""
|
| 374 |
+
self.seek(self.block_index-num)
|
| 375 |
+
|
| 376 |
+
def jump(self,num=1):
|
| 377 |
+
"""Jump a given number of blocks relative to the current one.
|
| 378 |
+
|
| 379 |
+
The offset can be positive or negative, defaults to 1."""
|
| 380 |
+
self.seek(self.block_index+num)
|
| 381 |
+
|
| 382 |
+
def again(self):
|
| 383 |
+
"""Move the seek pointer back one block and re-execute."""
|
| 384 |
+
self.back(1)
|
| 385 |
+
self()
|
| 386 |
+
|
| 387 |
+
def edit(self,index=None):
|
| 388 |
+
"""Edit a block.
|
| 389 |
+
|
| 390 |
+
If no number is given, use the last block executed.
|
| 391 |
+
|
| 392 |
+
This edits the in-memory copy of the demo, it does NOT modify the
|
| 393 |
+
original source file. If you want to do that, simply open the file in
|
| 394 |
+
an editor and use reload() when you make changes to the file. This
|
| 395 |
+
method is meant to let you change a block during a demonstration for
|
| 396 |
+
explanatory purposes, without damaging your original script."""
|
| 397 |
+
|
| 398 |
+
index = self._get_index(index)
|
| 399 |
+
if index is None:
|
| 400 |
+
return
|
| 401 |
+
# decrease the index by one (unless we're at the very beginning), so
|
| 402 |
+
# that the default demo.edit() call opens up the sblock we've last run
|
| 403 |
+
if index>0:
|
| 404 |
+
index -= 1
|
| 405 |
+
|
| 406 |
+
filename = self.shell.mktempfile(self.src_blocks[index])
|
| 407 |
+
self.shell.hooks.editor(filename, 1)
|
| 408 |
+
with open(Path(filename), "r", encoding="utf-8") as f:
|
| 409 |
+
new_block = f.read()
|
| 410 |
+
# update the source and colored block
|
| 411 |
+
self.src_blocks[index] = new_block
|
| 412 |
+
self.src_blocks_colored[index] = self.highlight(new_block)
|
| 413 |
+
self.block_index = index
|
| 414 |
+
# call to run with the newly edited index
|
| 415 |
+
self()
|
| 416 |
+
|
| 417 |
+
def show(self,index=None):
|
| 418 |
+
"""Show a single block on screen"""
|
| 419 |
+
|
| 420 |
+
index = self._get_index(index)
|
| 421 |
+
if index is None:
|
| 422 |
+
return
|
| 423 |
+
|
| 424 |
+
print(self.marquee('<%s> block # %s (%s remaining)' %
|
| 425 |
+
(self.title,index,self.nblocks-index-1)))
|
| 426 |
+
print(self.src_blocks_colored[index])
|
| 427 |
+
sys.stdout.flush()
|
| 428 |
+
|
| 429 |
+
def show_all(self):
|
| 430 |
+
"""Show entire demo on screen, block by block"""
|
| 431 |
+
|
| 432 |
+
fname = self.title
|
| 433 |
+
title = self.title
|
| 434 |
+
nblocks = self.nblocks
|
| 435 |
+
silent = self._silent
|
| 436 |
+
marquee = self.marquee
|
| 437 |
+
for index,block in enumerate(self.src_blocks_colored):
|
| 438 |
+
if silent[index]:
|
| 439 |
+
print(marquee('<%s> SILENT block # %s (%s remaining)' %
|
| 440 |
+
(title,index,nblocks-index-1)))
|
| 441 |
+
else:
|
| 442 |
+
print(marquee('<%s> block # %s (%s remaining)' %
|
| 443 |
+
(title,index,nblocks-index-1)))
|
| 444 |
+
print(block, end=' ')
|
| 445 |
+
sys.stdout.flush()
|
| 446 |
+
|
| 447 |
+
def run_cell(self,source):
|
| 448 |
+
"""Execute a string with one or more lines of code"""
|
| 449 |
+
|
| 450 |
+
exec(source, self.user_ns)
|
| 451 |
+
|
| 452 |
+
def __call__(self,index=None):
|
| 453 |
+
"""run a block of the demo.
|
| 454 |
+
|
| 455 |
+
If index is given, it should be an integer >=1 and <= nblocks. This
|
| 456 |
+
means that the calling convention is one off from typical Python
|
| 457 |
+
lists. The reason for the inconsistency is that the demo always
|
| 458 |
+
prints 'Block n/N, and N is the total, so it would be very odd to use
|
| 459 |
+
zero-indexing here."""
|
| 460 |
+
|
| 461 |
+
index = self._get_index(index)
|
| 462 |
+
if index is None:
|
| 463 |
+
return
|
| 464 |
+
try:
|
| 465 |
+
marquee = self.marquee
|
| 466 |
+
next_block = self.src_blocks[index]
|
| 467 |
+
self.block_index += 1
|
| 468 |
+
if self._silent[index]:
|
| 469 |
+
print(marquee('Executing silent block # %s (%s remaining)' %
|
| 470 |
+
(index,self.nblocks-index-1)))
|
| 471 |
+
else:
|
| 472 |
+
self.pre_cmd()
|
| 473 |
+
self.show(index)
|
| 474 |
+
if self.auto_all or self._auto[index]:
|
| 475 |
+
print(marquee('output:'))
|
| 476 |
+
else:
|
| 477 |
+
print(marquee('Press <q> to quit, <Enter> to execute...'), end=' ')
|
| 478 |
+
ans = py3compat.input().strip()
|
| 479 |
+
if ans:
|
| 480 |
+
print(marquee('Block NOT executed'))
|
| 481 |
+
return
|
| 482 |
+
try:
|
| 483 |
+
save_argv = sys.argv
|
| 484 |
+
sys.argv = self.sys_argv
|
| 485 |
+
self.run_cell(next_block)
|
| 486 |
+
self.post_cmd()
|
| 487 |
+
finally:
|
| 488 |
+
sys.argv = save_argv
|
| 489 |
+
|
| 490 |
+
except:
|
| 491 |
+
if self.inside_ipython:
|
| 492 |
+
self.ip_showtb(filename=self.fname)
|
| 493 |
+
else:
|
| 494 |
+
if self.inside_ipython:
|
| 495 |
+
self.ip_ns.update(self.user_ns)
|
| 496 |
+
|
| 497 |
+
if self.block_index == self.nblocks:
|
| 498 |
+
mq1 = self.marquee('END OF DEMO')
|
| 499 |
+
if mq1:
|
| 500 |
+
# avoid spurious print if empty marquees are used
|
| 501 |
+
print()
|
| 502 |
+
print(mq1)
|
| 503 |
+
print(self.marquee('Use <demo_name>.reset() if you want to rerun it.'))
|
| 504 |
+
self.finished = True
|
| 505 |
+
|
| 506 |
+
# These methods are meant to be overridden by subclasses who may wish to
|
| 507 |
+
# customize the behavior of of their demos.
|
| 508 |
+
def marquee(self,txt='',width=78,mark='*'):
|
| 509 |
+
"""Return the input string centered in a 'marquee'."""
|
| 510 |
+
return marquee(txt,width,mark)
|
| 511 |
+
|
| 512 |
+
def pre_cmd(self):
|
| 513 |
+
"""Method called before executing each block."""
|
| 514 |
+
pass
|
| 515 |
+
|
| 516 |
+
def post_cmd(self):
|
| 517 |
+
"""Method called after executing each block."""
|
| 518 |
+
pass
|
| 519 |
+
|
| 520 |
+
def highlight(self, block):
|
| 521 |
+
"""Method called on each block to highlight it content"""
|
| 522 |
+
tokens = pygments.lex(block, self.python_lexer)
|
| 523 |
+
if self.format_rst:
|
| 524 |
+
from pygments.token import Token
|
| 525 |
+
toks = []
|
| 526 |
+
for token in tokens:
|
| 527 |
+
if token[0] == Token.String.Doc and len(token[1]) > 6:
|
| 528 |
+
toks += pygments.lex(token[1][:3], self.python_lexer)
|
| 529 |
+
# parse doc string content by rst lexer
|
| 530 |
+
toks += pygments.lex(token[1][3:-3], self.rst_lexer)
|
| 531 |
+
toks += pygments.lex(token[1][-3:], self.python_lexer)
|
| 532 |
+
elif token[0] == Token.Comment.Single:
|
| 533 |
+
toks.append((Token.Comment.Single, token[1][0]))
|
| 534 |
+
# parse comment content by rst lexer
|
| 535 |
+
# remove the extra newline added by rst lexer
|
| 536 |
+
toks += list(pygments.lex(token[1][1:], self.rst_lexer))[:-1]
|
| 537 |
+
else:
|
| 538 |
+
toks.append(token)
|
| 539 |
+
tokens = toks
|
| 540 |
+
return pygments.format(tokens, self.formatter)
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
class IPythonDemo(Demo):
|
| 544 |
+
"""Class for interactive demos with IPython's input processing applied.
|
| 545 |
+
|
| 546 |
+
This subclasses Demo, but instead of executing each block by the Python
|
| 547 |
+
interpreter (via exec), it actually calls IPython on it, so that any input
|
| 548 |
+
filters which may be in place are applied to the input block.
|
| 549 |
+
|
| 550 |
+
If you have an interactive environment which exposes special input
|
| 551 |
+
processing, you can use this class instead to write demo scripts which
|
| 552 |
+
operate exactly as if you had typed them interactively. The default Demo
|
| 553 |
+
class requires the input to be valid, pure Python code.
|
| 554 |
+
"""
|
| 555 |
+
|
| 556 |
+
def run_cell(self,source):
|
| 557 |
+
"""Execute a string with one or more lines of code"""
|
| 558 |
+
|
| 559 |
+
self.shell.run_cell(source)
|
| 560 |
+
|
| 561 |
+
class LineDemo(Demo):
|
| 562 |
+
"""Demo where each line is executed as a separate block.
|
| 563 |
+
|
| 564 |
+
The input script should be valid Python code.
|
| 565 |
+
|
| 566 |
+
This class doesn't require any markup at all, and it's meant for simple
|
| 567 |
+
scripts (with no nesting or any kind of indentation) which consist of
|
| 568 |
+
multiple lines of input to be executed, one at a time, as if they had been
|
| 569 |
+
typed in the interactive prompt.
|
| 570 |
+
|
| 571 |
+
Note: the input can not have *any* indentation, which means that only
|
| 572 |
+
single-lines of input are accepted, not even function definitions are
|
| 573 |
+
valid."""
|
| 574 |
+
|
| 575 |
+
def reload(self):
|
| 576 |
+
"""Reload source from disk and initialize state."""
|
| 577 |
+
# read data and parse into blocks
|
| 578 |
+
self.fload()
|
| 579 |
+
lines = self.fobj.readlines()
|
| 580 |
+
src_b = [l for l in lines if l.strip()]
|
| 581 |
+
nblocks = len(src_b)
|
| 582 |
+
self.src = ''.join(lines)
|
| 583 |
+
self._silent = [False]*nblocks
|
| 584 |
+
self._auto = [True]*nblocks
|
| 585 |
+
self.auto_all = True
|
| 586 |
+
self.nblocks = nblocks
|
| 587 |
+
self.src_blocks = src_b
|
| 588 |
+
|
| 589 |
+
# also build syntax-highlighted source
|
| 590 |
+
self.src_blocks_colored = list(map(self.highlight,self.src_blocks))
|
| 591 |
+
|
| 592 |
+
# ensure clean namespace and seek offset
|
| 593 |
+
self.reset()
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
class IPythonLineDemo(IPythonDemo,LineDemo):
|
| 597 |
+
"""Variant of the LineDemo class whose input is processed by IPython."""
|
| 598 |
+
pass
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
class ClearMixin:
|
| 602 |
+
"""Use this mixin to make Demo classes with less visual clutter.
|
| 603 |
+
|
| 604 |
+
Demos using this mixin will clear the screen before every block and use
|
| 605 |
+
blank marquees.
|
| 606 |
+
|
| 607 |
+
Note that in order for the methods defined here to actually override those
|
| 608 |
+
of the classes it's mixed with, it must go /first/ in the inheritance
|
| 609 |
+
tree. For example:
|
| 610 |
+
|
| 611 |
+
class ClearIPDemo(ClearMixin,IPythonDemo): pass
|
| 612 |
+
|
| 613 |
+
will provide an IPythonDemo class with the mixin's features.
|
| 614 |
+
"""
|
| 615 |
+
|
| 616 |
+
def marquee(self,txt='',width=78,mark='*'):
|
| 617 |
+
"""Blank marquee that returns '' no matter what the input."""
|
| 618 |
+
return ''
|
| 619 |
+
|
| 620 |
+
def pre_cmd(self):
|
| 621 |
+
"""Method called before executing each block.
|
| 622 |
+
|
| 623 |
+
This one simply clears the screen."""
|
| 624 |
+
from IPython.utils.terminal import _term_clear
|
| 625 |
+
_term_clear()
|
| 626 |
+
|
| 627 |
+
class ClearDemo(ClearMixin,Demo):
|
| 628 |
+
pass
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
class ClearIPDemo(ClearMixin,IPythonDemo):
|
| 632 |
+
pass
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
def slide(file_path, noclear=False, format_rst=True, formatter="terminal",
|
| 636 |
+
style="native", auto_all=False, delimiter='...'):
|
| 637 |
+
if noclear:
|
| 638 |
+
demo_class = Demo
|
| 639 |
+
else:
|
| 640 |
+
demo_class = ClearDemo
|
| 641 |
+
demo = demo_class(file_path, format_rst=format_rst, formatter=formatter,
|
| 642 |
+
style=style, auto_all=auto_all)
|
| 643 |
+
while not demo.finished:
|
| 644 |
+
demo()
|
| 645 |
+
try:
|
| 646 |
+
py3compat.input('\n' + delimiter)
|
| 647 |
+
except KeyboardInterrupt:
|
| 648 |
+
exit(1)
|
| 649 |
+
|
| 650 |
+
if __name__ == '__main__':
|
| 651 |
+
import argparse
|
| 652 |
+
parser = argparse.ArgumentParser(description='Run python demos')
|
| 653 |
+
parser.add_argument('--noclear', '-C', action='store_true',
|
| 654 |
+
help='Do not clear terminal on each slide')
|
| 655 |
+
parser.add_argument('--rst', '-r', action='store_true',
|
| 656 |
+
help='Highlight comments and dostrings as rst')
|
| 657 |
+
parser.add_argument('--formatter', '-f', default='terminal',
|
| 658 |
+
help='pygments formatter name could be: terminal, '
|
| 659 |
+
'terminal256, terminal16m')
|
| 660 |
+
parser.add_argument('--style', '-s', default='default',
|
| 661 |
+
help='pygments style name')
|
| 662 |
+
parser.add_argument('--auto', '-a', action='store_true',
|
| 663 |
+
help='Run all blocks automatically without'
|
| 664 |
+
'confirmation')
|
| 665 |
+
parser.add_argument('--delimiter', '-d', default='...',
|
| 666 |
+
help='slides delimiter added after each slide run')
|
| 667 |
+
parser.add_argument('file', nargs=1,
|
| 668 |
+
help='python demo file')
|
| 669 |
+
args = parser.parse_args()
|
| 670 |
+
slide(args.file[0], noclear=args.noclear, format_rst=args.rst,
|
| 671 |
+
formatter=args.formatter, style=args.style, auto_all=args.auto,
|
| 672 |
+
delimiter=args.delimiter)
|