desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'List currently available magic functions.'
@line_magic def lsmagic(self, parameter_s=''):
return MagicsDisplay(self.shell.magics_manager, ignore=[self.pip])
'Return docstrings from magic functions.'
def _magic_docs(self, brief=False, rest=False):
mman = self.shell.magics_manager docs = mman.lsmagic_docs(brief, missing='No documentation') if rest: format_string = '**%s%s**::\n\n%s\n\n' else: format_string = '%s%s:\n%s\n' return ''.join(([(format_string % (magic_escapes['line'], fname, indent(dedent(fndoc)))) for (fname, fnd...
'Print information about the magic function system. Supported formats: -latex, -brief, -rest'
@line_magic def magic(self, parameter_s=''):
mode = '' try: mode = parameter_s.split()[0][1:] except IndexError: pass brief = (mode == 'brief') rest = (mode == 'rest') magic_docs = self._magic_docs(brief, rest) if (mode == 'latex'): print self.format_latex(magic_docs) return else: magic_docs ...
'Pretty print the object and display it through a pager. %page [options] OBJECT If no object is given, use _ (last output). Options: -r: page str(object), don\'t pretty-print it.'
@line_magic def page(self, parameter_s=''):
(opts, args) = self.parse_options(parameter_s, 'r') raw = ('r' in opts) oname = ((args and args) or '_') info = self.shell._ofind(oname) if info['found']: txt = ((raw and str) or pformat)(info['obj']) page.page(txt) else: print ('Object `%s` not found' % oname)
'DEPRECATED since IPython 2.0. Raise `UsageError`. To profile code use the :magic:`prun` magic. See Also prun : run code using the Python profiler (:magic:`prun`)'
@line_magic def profile(self, parameter_s=''):
raise UsageError('The `%profile` magic has been deprecated since IPython 2.0. and removed in IPython 6.0. Please use the value of `get_ipython().profile` instead to see current profile in use. Perhaps you meant to use `%...
'Toggle pretty printing on/off.'
@line_magic def pprint(self, parameter_s=''):
ptformatter = self.shell.display_formatter.formatters['text/plain'] ptformatter.pprint = bool((1 - ptformatter.pprint)) print ('Pretty printing has been turned', ['OFF', 'ON'][ptformatter.pprint])
'Switch color scheme for prompts, info system and exception handlers. Currently implemented schemes: NoColor, Linux, LightBG. Color scheme names are not case-sensitive. Examples To get a plain black and white terminal:: %colors nocolor'
@line_magic def colors(self, parameter_s=''):
def color_switch_err(name): warn(('Error changing %s color schemes.\n%s' % (name, sys.exc_info()[1])), stacklevel=2) new_scheme = parameter_s.strip() if (not new_scheme): raise UsageError("%colors: you must specify a color scheme. See '%colors?'") shel...
'Switch modes for the exception handlers. Valid modes: Plain, Context and Verbose. If called without arguments, acts as a toggle.'
@line_magic def xmode(self, parameter_s=''):
def xmode_switch_err(name): warn(('Error changing %s exception modes.\n%s' % (name, sys.exc_info()[1]))) shell = self.shell new_mode = parameter_s.strip().capitalize() try: shell.InteractiveTB.set_mode(mode=new_mode) print ('Exception reporting mode:', shell.Int...
'Intercept usage of ``pip`` in IPython and direct user to run command outside of IPython.'
@line_magic def pip(self, args=''):
print textwrap.dedent('\n The following command must be run outside of the IPython shell:\n\n $ pip {args}\n\n The Python package manager (pip) can only ...
'Show a quick reference sheet'
@line_magic def quickref(self, arg):
from IPython.core.usage import quick_reference qr = (quick_reference + self._magic_docs(brief=True)) page.page(qr)
'Toggle doctest mode on and off. This mode is intended to make IPython behave as much as possible like a plain Python shell, from the perspective of how its prompts, exceptions and output look. This makes it easy to copy and paste parts of a session into doctests. It does so by: - Changing the prompts to the classic ...
@line_magic def doctest_mode(self, parameter_s=''):
shell = self.shell meta = shell.meta disp_formatter = self.shell.display_formatter ptformatter = disp_formatter.formatters['text/plain'] dstore = meta.setdefault('doctest_mode', Struct()) save_dstore = dstore.setdefault mode = save_dstore('mode', False) save_dstore('rc_pprint', ptformatt...
'Enable or disable IPython GUI event loop integration. %gui [GUINAME] This magic replaces IPython\'s threaded shells that were activated using the (pylab/wthread/etc.) command line flags. GUI toolkits can now be enabled at runtime and keyboard interrupts should work without any problems. The following toolkits are su...
@line_magic def gui(self, parameter_s=''):
(opts, arg) = self.parse_options(parameter_s, '') if (arg == ''): arg = None try: return self.shell.enable_gui(arg) except Exception as e: error(str(e))
'Set floating point precision for pretty printing. Can set either integer precision or a format string. If numpy has been imported and precision is an int, numpy display precision will also be set, via ``numpy.set_printoptions``. If no argument is given, defaults will be restored. Examples In [1]: from math import pi I...
@skip_doctest @line_magic def precision(self, s=''):
ptformatter = self.shell.display_formatter.formatters['text/plain'] ptformatter.float_precision = s return ptformatter.float_format
'Export and convert IPython notebooks. This function can export the current IPython history to a notebook file. For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb". The -e or --export flag is deprecated in IPython 5.2, and will be removed in the future.'
@magic_arguments.magic_arguments() @magic_arguments.argument('-e', '--export', action='store_true', default=False, help=argparse.SUPPRESS) @magic_arguments.argument('filename', type=str, help='Notebook name or filename') @line_magic def notebook(self, s):
args = magic_arguments.parse_argstring(self.notebook, s) from nbformat import write, v4 cells = [] hist = list(self.shell.history_manager.get_range()) if (len(hist) <= 1): raise ValueError('History is empty, cannot export') for (session, execution_count, source) in hist[:(-1)...
'Return descriptive string with automagic status.'
def auto_status(self):
return self._auto_status[self.auto_magic]
'Return a dict of currently available magic functions. The return dict has the keys \'line\' and \'cell\', corresponding to the two types of magics we support. Each value is a list of names.'
def lsmagic(self):
return self.magics
'Return dict of documentation of magic functions. The return dict has the keys \'line\' and \'cell\', corresponding to the two types of magics we support. Each value is a dict keyed by magic name whose value is the function docstring. If a docstring is unavailable, the value of `missing` is used instead. If brief is Tr...
def lsmagic_docs(self, brief=False, missing=''):
docs = {} for m_type in self.magics: m_docs = {} for (m_name, m_func) in self.magics[m_type].items(): if m_func.__doc__: if brief: m_docs[m_name] = m_func.__doc__.split('\n', 1)[0] else: m_docs[m_name] = m_func._...
'Register one or more instances of Magics. Take one or more classes or instances of classes that subclass the main `core.Magic` class, and register them with IPython to use the magic functions they provide. The registration process will then ensure that any methods that have decorated to provide line and/or cell magic...
def register(self, *magic_objects):
for m in magic_objects: if (not m.registered): raise ValueError('Class of magics %r was constructed without the @register_magics class decorator') if isinstance(m, type): m = m(shell=self.shell) self.registry[m.__class__.__name__] = m ...
'Expose a standalone function as magic function for IPython. This will create an IPython magic (line, cell or both) from a standalone function. The functions should have the following signatures: * For line magics: `def f(line)` * For cell magics: `def f(line, cell)` * For a function that does both: `def f(line, cell=...
def register_function(self, func, magic_kind='line', magic_name=None):
validate_type(magic_kind) magic_name = (func.__name__ if (magic_name is None) else magic_name) setattr(self.user_magics, magic_name, func) record_magic(self.magics, magic_kind, magic_name, func)
'Register an alias to a magic function. The alias is an instance of :class:`MagicAlias`, which holds the name and kind of the magic it should call. Binding is done at call time, so if the underlying magic function is changed the alias will call the new function. Parameters alias_name : str The name of the magic to be r...
def register_alias(self, alias_name, magic_name, magic_kind='line', magic_params=None):
if (magic_kind not in magic_kinds): raise ValueError(('magic_kind must be one of %s, %s given' % magic_kinds), magic_kind) alias = MagicAlias(self.shell, magic_name, magic_kind, magic_params) setattr(self.user_magics, alias_name, alias) record_magic(self.magics, magic_kind, ...
'Print docstring if incorrect arguments were passed'
def arg_err(self, func):
print 'Error in arguments:' print oinspect.getdoc(func)
'Format a string for latex inclusion.'
def format_latex(self, strng):
escape_re = re.compile('(%|_|\\$|#|&)', re.MULTILINE) cmd_name_re = re.compile(('^(%s.*?):' % ESC_MAGIC), re.MULTILINE) cmd_re = re.compile(('(?P<cmd>%s.+?\\b)(?!\\}\\}:)' % ESC_MAGIC), re.MULTILINE) par_re = re.compile('\\\\$', re.MULTILINE) newline_re = re.compile('\\\\n') strng = cmd_name_re....
'Parse options passed to an argument string. The interface is similar to that of :func:`getopt.getopt`, but it returns a :class:`~IPython.utils.struct.Struct` with the options as keys and the stripped argument string still as a string. arg_str is quoted as a true sys.argv vector by using shlex.split. This allows us to ...
def parse_options(self, arg_str, opt_str, *long_opts, **kw):
caller = sys._getframe(1).f_code.co_name arg_str = ('%s %s' % (self.options_table.get(caller, ''), arg_str)) mode = kw.get('mode', 'string') if (mode not in ['string', 'list']): raise ValueError(('incorrect mode given: %s' % mode)) list_all = kw.get('list_all', 0) posix = kw....
'Make an entry in the options_table for fn, with value optstr'
def default_option(self, fn, optstr):
if (fn not in self.lsmagic()): error(('%s is not a magic function' % fn)) self.options_table[fn] = optstr
'Call the magic alias.'
def __call__(self, *args, **kwargs):
fn = self.shell.find_magic(self.magic_name, self.magic_kind) if (fn is None): raise UsageError(('Magic `%s` not found.' % self.pretty_target)) if self._in_call: raise UsageError('Infinite recursion detected; magic aliases cannot call themselves.') self._in_c...
'ensure a directory exists at a given path This is a version of os.mkdir, with the following differences: - returns True if it created the directory, False otherwise - ignores EEXIST, protecting against race conditions where the dir may have been created in between the check and the creation - sets permissions if reque...
def _mkdir(self, path, mode=None):
if os.path.exists(path): if (mode and (os.stat(path).st_mode != mode)): try: os.chmod(path, mode) except OSError: self.log.warning('Could not set permissions on %s', path) return False try: if mode: os.mkd...
'Copy a default config file into the active profile directory. Default configuration files are kept in :mod:`IPython.core.profile`. This function moves these from that location to the working profile directory.'
def copy_config_file(self, config_file, path=None, overwrite=False):
dst = os.path.join(self.location, config_file) if (os.path.isfile(dst) and (not overwrite)): return False if (path is None): path = os.path.join(get_ipython_package_dir(), u'core', u'profile', u'default') src = os.path.join(path, config_file) shutil.copy(src, dst) return True
'Create a new profile directory given a full path. Parameters profile_dir : str The full path to the profile directory. If it does exist, it will be used. If not, it will be created.'
@classmethod def create_profile_dir(cls, profile_dir, config=None):
return cls(location=profile_dir, config=config)
'Create a profile dir by profile name and path. Parameters path : unicode The path (directory) to put the profile directory in. name : unicode The name of the profile. The name of the profile directory will be "profile_<profile>".'
@classmethod def create_profile_dir_by_name(cls, path, name=u'default', config=None):
if (not os.path.isdir(path)): raise ProfileDirError(('Directory not found: %s' % path)) profile_dir = os.path.join(path, (u'profile_' + name)) return cls(location=profile_dir, config=config)
'Find an existing profile dir by profile name, return its ProfileDir. This searches through a sequence of paths for a profile dir. If it is not found, a :class:`ProfileDirError` exception will be raised. The search path algorithm is: 1. ``os.getcwd()`` 2. ``ipython_dir`` Parameters ipython_dir : unicode or str The IPy...
@classmethod def find_profile_dir_by_name(cls, ipython_dir, name=u'default', config=None):
dirname = (u'profile_' + name) paths = [os.getcwd(), ipython_dir] for p in paths: profile_dir = os.path.join(p, dirname) if os.path.isdir(profile_dir): return cls(location=profile_dir, config=config) else: raise ProfileDirError(('Profile directory not found ...
'Find/create a profile dir and return its ProfileDir. This will create the profile directory if it doesn\'t exist. Parameters profile_dir : unicode or str The path of the profile directory.'
@classmethod def find_profile_dir(cls, profile_dir, config=None):
profile_dir = expand_path(profile_dir) if (not os.path.isdir(profile_dir)): raise ProfileDirError(('Profile directory not found: %s' % profile_dir)) return cls(location=profile_dir, config=config)
'Raise a catchable error instead of exiting.'
def error(self, message):
raise UsageError(message)
'Split a string into an argument list and parse that argument list.'
def parse_argstring(self, argstring):
argv = arg_split(argstring) return self.parse_args(argv)
'Add this object\'s information to the parser, if necessary.'
def add_to_parser(self, parser, group):
pass
'Add this object\'s information to the parser.'
def add_to_parser(self, parser, group):
if (group is not None): parser = group getattr(parser, self._method_name)(*self.args, **self.kwds) return None
'Add this object\'s information to the parser.'
def add_to_parser(self, parser, group):
return parser.add_argument_group(*self.args, **self.kwds)
'Include or update the specified `data` payload in the PayloadManager. If a previous payload with the same source exists and `single` is True, it will be overwritten with the new one.'
def write_payload(self, data, single=True):
if (not isinstance(data, dict)): raise TypeError(('Each payload write must be a dict, got: %r' % data)) if (single and ('source' in data)): source = data['source'] for (i, pl) in enumerate(self._payload): if (('source' in pl) and (pl['source'] == sourc...
'Parse code to an AST with the current compiler flags active. Arguments are exactly the same as ast.parse (in the standard library), and are passed to the built-in compile function.'
def ast_parse(self, source, filename='<unknown>', symbol='exec'):
return compile(source, filename, symbol, (self.flags | PyCF_ONLY_AST), 1)
'Reset compiler flags to default state.'
def reset_compiler_flags(self):
self.flags = codeop.PyCF_DONT_IMPLY_DEDENT
'Flags currently active in the compilation process.'
@property def compiler_flags(self):
return self.flags
'Make a name for a block of code, and cache the code. Parameters code : str The Python source code to cache. number : int A number which forms part of the code\'s name. Used for the execution counter. Returns The name of the cached code (as a string). Pass this as the filename argument to compilation, so that traceback...
def cache(self, code, number=0):
name = code_name(code, number) entry = (len(code), time.time(), [(line + '\n') for line in code.splitlines()], name) linecache.cache[name] = entry linecache._ipython_cache[name] = entry return name
'Load an IPython extension by its module name. Returns the string "already loaded" if the extension is already loaded, "no load function" if the module doesn\'t have a load_ipython_extension function, or None if it succeeded.'
def load_extension(self, module_str):
if (module_str in self.loaded): return 'already loaded' from IPython.utils.syspathcontext import prepended_to_syspath with self.shell.builtin_trap: if (module_str not in sys.modules): with prepended_to_syspath(self.ipython_extension_dir): mod = import_module(mo...
'Unload an IPython extension by its module name. This function looks up the extension\'s name in ``sys.modules`` and simply calls ``mod.unload_ipython_extension(self)``. Returns the string "no unload function" if the extension doesn\'t define a function to unload itself, "not loaded" if the extension isn\'t loaded, oth...
def unload_extension(self, module_str):
if (module_str not in self.loaded): return 'not loaded' if (module_str in sys.modules): mod = sys.modules[module_str] if self._call_unload_ipython_extension(mod): self.loaded.discard(module_str) else: return 'no unload function'
'Reload an IPython extension by calling reload. If the module has not been loaded before, :meth:`InteractiveShell.load_extension` is called. Otherwise :func:`reload` is called and then the :func:`load_ipython_extension` function of the module, if it exists is called.'
def reload_extension(self, module_str):
from IPython.utils.syspathcontext import prepended_to_syspath if ((module_str in self.loaded) and (module_str in sys.modules)): self.unload_extension(module_str) mod = sys.modules[module_str] with prepended_to_syspath(self.ipython_extension_dir): reload(mod) if self._...
'Deprecated.'
@undoc def install_extension(self, url, filename=None):
raise DeprecationWarning('`install_extension` and the `install_ext` magic have been deprecated since IPython 4.0Use pip or other package managers to manage ipython extensions.')
'Add current working directory, \'\', to sys.path'
def init_path(self):
if (sys.path[0] != ''): sys.path.insert(0, '')
'Enable GUI event loop integration, taking pylab into account.'
def init_gui_pylab(self):
enable = False shell = self.shell if self.pylab: enable = (lambda key: shell.enable_pylab(key, import_all=self.pylab_import_all)) key = self.pylab elif self.matplotlib: enable = shell.enable_matplotlib key = self.matplotlib elif self.gui: enable = shell.enable...
'Load all IPython extensions in IPythonApp.extensions. This uses the :meth:`ExtensionManager.load_extensions` to load all the extensions listed in ``self.extensions``.'
def init_extensions(self):
try: self.log.debug('Loading IPython extensions...') extensions = (self.default_extensions + self.extensions) if self.extra_extension: extensions.append(self.extra_extension) for ext in extensions: try: self.log.info(('Loading IPython ...
'run the pre-flight code, specified via exec_lines'
def init_code(self):
self._run_startup_files() self._run_exec_lines() self._run_exec_files() if self.hide_initial_ns: self.shell.user_ns_hidden.update(self.shell.user_ns) self._run_cmd_line_code() self._run_module() sys.stdout.flush() sys.stderr.flush()
'Run lines of code in IPythonApp.exec_lines in the user\'s namespace.'
def _run_exec_lines(self):
if (not self.exec_lines): return try: self.log.debug('Running code from IPythonApp.exec_lines...') for line in self.exec_lines: try: self.log.info(('Running code in user namespace: %s' % line)) self.shell.run_cell(line, ...
'Run files from profile startup directory'
def _run_startup_files(self):
startup_dirs = ([self.profile_dir.startup_dir] + [os.path.join(p, 'startup') for p in chain(ENV_CONFIG_DIRS, SYSTEM_CONFIG_DIRS)]) startup_files = [] if (self.exec_PYTHONSTARTUP and os.environ.get('PYTHONSTARTUP', False) and (not (self.file_to_run or self.code_to_run or self.module_to_run))): python...
'Run files from IPythonApp.exec_files'
def _run_exec_files(self):
if (not self.exec_files): return self.log.debug('Running files in IPythonApp.exec_files...') try: for fname in self.exec_files: self._exec_file(fname) except: self.log.warning('Unknown error in handling IPythonApp.exec_files:') self.shell....
'Run code or file specified at the command-line'
def _run_cmd_line_code(self):
if self.code_to_run: line = self.code_to_run try: self.log.info(('Running code given at command line (c=): %s' % line)) self.shell.run_cell(line, store_history=False) except: self.log.warning(('Error in executing line in ...
'Run module specified at the command-line.'
def _run_module(self):
if self.module_to_run: save_argv = sys.argv sys.argv = ([sys.executable] + self.extra_args) try: self.shell.safe_run_module(self.module_to_run, self.shell.user_ns) finally: sys.argv = save_argv
'Create a new InputSplitter instance.'
def __init__(self):
self._buffer = [] self._compile = codeop.CommandCompiler() self.encoding = get_input_encoding()
'Reset the input buffer and associated state.'
def reset(self):
self.indent_spaces = 0 self._buffer[:] = [] self.source = '' self.code = None self._is_complete = False self._is_invalid = False self._full_dedent = False
'Return the input source and perform a full reset.'
def source_reset(self):
out = self.source self.reset() return out
'Return whether a block of code is ready to execute, or should be continued This is a non-stateful API, and will reset the state of this InputSplitter. Parameters source : string Python input code, which can be multiline. Returns status : str One of \'complete\', \'incomplete\', or \'invalid\' if source is not a prefix...
def check_complete(self, source):
self.reset() try: self.push(source) except SyntaxError: return ('invalid', None) else: if self._is_invalid: return ('invalid', None) elif self.push_accepts_more(): return ('incomplete', self.indent_spaces) else: return ('complet...
'Push one or more lines of input. This stores the given lines and returns a status code indicating whether the code forms a complete Python block or not. Any exceptions generated in compilation are swallowed, but if an exception was produced, the method returns True. Parameters lines : string One or more lines of Pytho...
def push(self, lines):
self._store(lines) source = self.source (self.code, self._is_complete) = (None, None) self._is_invalid = False if source.endswith('\\\n'): return False self._update_indent() try: with warnings.catch_warnings(): warnings.simplefilter('error', SyntaxWarning) ...
'Return whether a block of interactive input can accept more input. This method is meant to be used by line-oriented frontends, who need to guess whether a block is complete or not based solely on prior and current input lines. The InputSplitter considers it has a complete interactive block and will not accept more in...
def push_accepts_more(self):
if (not self._is_complete): return True last_line = self.source.splitlines()[(-1)] if ((not last_line) or last_line.isspace()): return False if (self.indent_spaces == 0): if (len(self.source.splitlines()) <= 1): return False try: code_ast = ast.par...
'Store one or more lines of input. If input lines are not newline-terminated, a newline is automatically appended.'
def _store(self, lines, buffer=None, store='source'):
if (buffer is None): buffer = self._buffer if lines.endswith('\n'): buffer.append(lines) else: buffer.append((lines + '\n')) setattr(self, store, self._set_source(buffer))
'Quick access to all transformers.'
@property def transforms(self):
return ((((self.physical_line_transforms + [self.assemble_logical_lines]) + self.logical_line_transforms) + [self.assemble_python_lines]) + self.python_line_transforms)
'Transformers, excluding logical line transformers if we\'re in a Python line.'
@property def transforms_in_use(self):
t = self.physical_line_transforms[:] if (not self.within_python_line): t += ([self.assemble_logical_lines] + self.logical_line_transforms) return ((t + [self.assemble_python_lines]) + self.python_line_transforms)
'Reset the input buffer and associated state.'
def reset(self):
super(IPythonInputSplitter, self).reset() self._buffer_raw[:] = [] self.source_raw = '' self.transformer_accumulating = False self.within_python_line = False for t in self.transforms: try: t.reset() except SyntaxError: pass
'Return raw input only and perform a full reset.'
def raw_reset(self):
out = self.source_raw self.reset() return out
'Process and translate a cell of input.'
def transform_cell(self, cell):
self.reset() try: self.push(cell) self.flush_transformers() return self.source finally: self.reset()
'Push one or more lines of IPython input. This stores the given lines and returns a status code indicating whether the code forms a complete Python block or not, after processing all input lines for special IPython syntax. Any exceptions generated in compilation are swallowed, but if an exception was produced, the meth...
def push(self, lines):
lines = cast_unicode(lines, self.encoding) lines_list = lines.splitlines() if (not lines_list): lines_list = [''] self._store(lines, self._buffer_raw, 'source_raw') for line in lines_list: out = self.push_line(line) return out
'DEPRECATED Create a local debugger instance. Parameters colors : str, optional The name of the color scheme to use, it must be one of IPython\'s valid color schemes. If not given, the function will default to the current IPython scheme when running inside IPython, and to \'NoColor\' otherwise. Examples from IPython.c...
@skip_doctest def __init__(self, colors=None):
warnings.warn('`Tracer` is deprecated since version 5.1, directly use `IPython.core.debugger.Pdb.set_trace()`', DeprecationWarning, stacklevel=2) ip = get_ipython() if (ip is None): sys.excepthook = functools.partial(BdbQuit_excepthook, excepthook=sys.excepthook) def_...
'Starts an interactive debugger at the point where called. This is similar to the pdb.set_trace() function from the std lib, but using IPython\'s enhanced debugger.'
def __call__(self):
self.debugger.set_trace(sys._getframe().f_back)
'Shorthand access to the color table scheme selector method.'
def set_colors(self, scheme):
self.color_scheme_table.set_active_scheme(scheme) self.parser.style = scheme
'Restart command. In the context of ipython this is exactly the same thing as \'quit\'.'
def new_do_restart(self, arg):
self.msg("Restart doesn't make sense here. Using 'quit' instead.") return self.do_quit(arg)
'The printing (as opposed to the parsing part of a \'list\' command.'
def print_list_lines(self, filename, first, last):
try: Colors = self.color_scheme_table.active_colors ColorsNormal = Colors.Normal tpl_line = ('%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)) tpl_line_em = ('%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)) src = [] if ((filename == '<string>')...
'Print lines of code from the current stack frame'
def do_list(self, arg):
self.lastcmd = 'list' last = None if arg: try: x = eval(arg, {}, {}) if (type(x) == type(())): (first, last) = x first = int(first) last = int(last) if (last < first): last = (first + last) ...
'Print lines of code from the current stack frame. Shows more lines than \'list\' does.'
def do_longlist(self, arg):
self.lastcmd = 'longlist' try: (lines, lineno) = self.getsourcelines(self.curframe) except OSError as err: self.error(err) return last = (lineno + len(lines)) self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
'Print the call signature for any callable object. The debugger interface to %pdef'
def do_pdef(self, arg):
namespaces = [('Locals', self.curframe.f_locals), ('Globals', self.curframe.f_globals)] self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
'Print the docstring for an object. The debugger interface to %pdoc.'
def do_pdoc(self, arg):
namespaces = [('Locals', self.curframe.f_locals), ('Globals', self.curframe.f_globals)] self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
'Print (or run through pager) the file where an object is defined. The debugger interface to %pfile.'
def do_pfile(self, arg):
namespaces = [('Locals', self.curframe.f_locals), ('Globals', self.curframe.f_globals)] self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
'Provide detailed information about an object. The debugger interface to %pinfo, i.e., obj?.'
def do_pinfo(self, arg):
namespaces = [('Locals', self.curframe.f_locals), ('Globals', self.curframe.f_globals)] self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
'Provide extra detailed information about an object. The debugger interface to %pinfo2, i.e., obj??.'
def do_pinfo2(self, arg):
namespaces = [('Locals', self.curframe.f_locals), ('Globals', self.curframe.f_globals)] self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
'Print (or run through pager) the source code for an object.'
def do_psource(self, arg):
namespaces = [('Locals', self.curframe.f_locals), ('Globals', self.curframe.f_globals)] self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
'w(here) Print a stack trace, with the most recent frame at the bottom. An arrow indicates the "current frame", which determines the context of most commands. \'bt\' is an alias for this command. Take a number as argument as an (optional) number of context line to print'
def do_where(self, arg):
if arg: context = int(arg) self.print_stack_trace(context) else: self.print_stack_trace()
'Output stream that exceptions are written to. Valid values are: - None: the default, which means that IPython will dynamically resolve to sys.stdout. This ensures compatibility with most tools, including Windows (where plain stdout doesn\'t recognize ANSI escapes). - Any object with \'write\' and \'flush\' attributes...
def _get_ostream(self):
return (sys.stdout if (self._ostream is None) else self._ostream)
'Shorthand access to the color table scheme selector method.'
def set_colors(self, *args, **kw):
self.color_scheme_table.set_active_scheme(*args, **kw) self.Colors = self.color_scheme_table.active_colors if (hasattr(self, 'pdb') and (self.pdb is not None)): self.pdb.set_colors(*args, **kw)
'Toggle between the currently active color scheme and NoColor.'
def color_toggle(self):
if (self.color_scheme_table.active_scheme_name == 'NoColor'): self.color_scheme_table.set_active_scheme(self.old_scheme) self.Colors = self.color_scheme_table.active_colors else: self.old_scheme = self.color_scheme_table.active_scheme_name self.color_scheme_table.set_active_schem...
'Convert a structured traceback (a list) to a string.'
def stb2text(self, stb):
return '\n'.join(stb)
'Return formatted traceback. Subclasses may override this if they add extra arguments.'
def text(self, etype, value, tb, tb_offset=None, context=5):
tb_list = self.structured_traceback(etype, value, tb, tb_offset, context) return self.stb2text(tb_list)
'Return a list of traceback frames. Must be implemented by each class.'
def structured_traceback(self, etype, evalue, tb, tb_offset=None, context=5, mode=None):
raise NotImplementedError()
'Return a color formatted string with the traceback info. Parameters etype : exception type Type of the exception raised. value : object Data stored in the exception elist : list List of frames, see class docstring for details. tb_offset : int, optional Number of frames in the traceback to skip. If not given, the inst...
def structured_traceback(self, etype, value, elist, tb_offset=None, context=5):
tb_offset = (self.tb_offset if (tb_offset is None) else tb_offset) Colors = self.Colors out_list = [] if elist: if (tb_offset and (len(elist) > tb_offset)): elist = elist[tb_offset:] out_list.append((('Traceback %s(most recent call last)%s:' % (Colors.normalEm, Co...
'Format a list of traceback entry tuples for printing. Given a list of tuples as returned by extract_tb() or extract_stack(), return a list of strings ready for printing. Each string in the resulting list corresponds to the item with the same index in the argument list. Each string ends in a newline; the strings may c...
def _format_list(self, extracted_list):
Colors = self.Colors list = [] for (filename, lineno, name, line) in extracted_list[:(-1)]: item = (' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % (Colors.filename, filename, Colors.Normal, Colors.lineno, lineno, Colors.Normal, Colors.name, name, Colors.Normal)) if line: ...
'Format the exception part of a traceback. The arguments are the exception type and value such as given by sys.exc_info()[:2]. The return value is a list of strings, each ending in a newline. Normally, the list contains a single string; however, for SyntaxError exceptions, it contains several lines that (when printed)...
def _format_exception_only(self, etype, value):
have_filedata = False Colors = self.Colors list = [] stype = py3compat.cast_unicode(((Colors.excName + etype.__name__) + Colors.Normal)) if (value is None): list.append((stype + '\n')) else: if issubclass(etype, SyntaxError): have_filedata = True if (not v...
'Only print the exception type and message, without a traceback. Parameters etype : exception type value : exception value'
def get_exception_only(self, etype, value):
return ListTB.structured_traceback(self, etype, value, [])
'Only print the exception type and message, without a traceback. Parameters etype : exception type value : exception value'
def show_exception_only(self, etype, evalue):
ostream = self.ostream ostream.flush() ostream.write('\n'.join(self.get_exception_only(etype, evalue))) ostream.flush()
'Specify traceback offset, headers and color scheme. Define how many frames to drop from the tracebacks. Calling it with tb_offset=1 allows use of this handler in interpreters which will have their own code at the top of the traceback (VerboseTB will first remove that frame before printing the traceback info).'
def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None, tb_offset=0, long_header=False, include_vars=True, check_cache=None, debugger_cls=None, parent=None, config=None):
TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, ostream=ostream, parent=parent, config=config) self.tb_offset = tb_offset self.long_header = long_header self.include_vars = include_vars if (check_cache is None): check_cache = linecache.checkcache self.check_cache = c...
'Format the stack frames of the traceback'
def format_records(self, records, last_unique, recursion_repeat):
frames = [] for r in records[:((last_unique + recursion_repeat) + 1)]: frames.append(self.format_record(*r)) if recursion_repeat: frames.append(('... last %d frames repeated, from the frame below ...\n' % recursion_repeat)) frames.append(self.format_record(...
'Format a single stack frame'
def format_record(self, frame, file, lnum, func, lines, index):
Colors = self.Colors ColorsNormal = Colors.Normal col_scheme = self.color_scheme_table.active_scheme_name indent = (' ' * INDENT_SIZE) em_normal = ('%s\n%s%s' % (Colors.valEm, indent, ColorsNormal)) undefined = ('%sundefined%s' % (Colors.em, ColorsNormal)) tpl_link = ('%s%%s%s' % (Colors....
'Formats the header, traceback and exception message for a single exception. This may be called multiple times by Python 3 exception chaining (PEP 3134).'
def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset):
orig_etype = etype try: etype = etype.__name__ except AttributeError: pass tb_offset = (self.tb_offset if (tb_offset is None) else tb_offset) head = self.prepare_header(etype, self.long_header) records = self.get_records(etb, number_of_lines_of_context, tb_offset) if (records...
'Return a nice text document describing the traceback.'
def structured_traceback(self, etype, evalue, etb, tb_offset=None, number_of_lines_of_context=5):
formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context, tb_offset) colors = self.Colors colorsnormal = colors.Normal head = ('%s%s%s' % (colors.topline, ('-' * min(75, get_terminal_size()[0])), colorsnormal)) structured_traceback_parts = [head] if p...
'Call up the pdb debugger if desired, always clean up the tb reference. Keywords: - force(False): by default, this routine checks the instance call_pdb flag and does not actually invoke the debugger if the flag is false. The \'force\' option forces the debugger to activate even if the flag is false. If the call_pdb fla...
def debugger(self, force=False):
if (force or self.call_pdb): if (self.pdb is None): self.pdb = self.debugger_cls() display_trap = DisplayTrap(hook=sys.__displayhook__) with display_trap: self.pdb.reset() if (hasattr(self, 'tb') and (self.tb is not None)): etb = self.tb ...
'This hook can replace sys.excepthook (for Python 2.1 or higher).'
def __call__(self, etype=None, evalue=None, etb=None):
if (etb is None): self.handler() else: self.handler((etype, evalue, etb)) try: self.debugger() except KeyboardInterrupt: print '\nKeyboardInterrupt'
'Convert a structured traceback (a list) to a string.'
def stb2text(self, stb):
return self.tb_join_char.join(stb)