def __init__(self,color_scheme='NoColor',completekey=None, stdin=None, stdout=None): # Parent constructor: if has_pydb and completekey is None: OldPdb.__init__(self,stdin=stdin,stdout=io.stdout) else: OldPdb.__init__(self,completekey,stdin,stdout) self.prompt = prompt # The default prompt is '(Pdb)' # IPython changes... self.is_pydb = has_pydb self.shell = ipapi.get() if self.is_pydb: # interactiveshell.py's ipalias seems to want pdb's checkline # which located in pydb.fn import pydb.fns self.checkline = lambda filename, lineno: \ pydb.fns.checkline(self, filename, lineno) self.curframe = None self.do_restart = self.new_do_restart self.old_all_completions = self.shell.Completer.all_completions self.shell.Completer.all_completions=self.all_completions self.do_list = decorate_fn_with_doc(self.list_command_pydb, OldPdb.do_list) self.do_l = self.do_list self.do_frame = decorate_fn_with_doc(self.new_do_frame, OldPdb.do_frame) self.aliases = {} # Create color table: we copy the default one from the traceback # module and add a few attributes needed for debugging self.color_scheme_table = exception_colors() # shorthands C = coloransi.TermColors cst = self.color_scheme_table cst['NoColor'].colors.breakpoint_enabled = C.NoColor cst['NoColor'].colors.breakpoint_disabled = C.NoColor cst['Linux'].colors.breakpoint_enabled = C.LightRed cst['Linux'].colors.breakpoint_disabled = C.Red cst['LightBG'].colors.breakpoint_enabled = C.LightRed cst['LightBG'].colors.breakpoint_disabled = C.Red self.set_colors(color_scheme) # Add a python parser so we can syntax highlight source while # debugging. self.parser = PyColorize.Parser()
def __init__(self, color_table=InspectColors, code_color_table=PyColorize.ANSICodeColors, scheme='NoColor', str_detail_level=0): self.color_table = color_table self.parser = PyColorize.Parser(code_color_table,out='str') self.format = self.parser.format self.str_detail_level = str_detail_level self.set_active_scheme(scheme)
def __init__(self, color_scheme='NoColor', completekey=None, stdin=None, stdout=None, context=5): # Parent constructor: try: self.context = int(context) if self.context <= 0: raise ValueError("Context must be a positive integer") except (TypeError, ValueError): raise ValueError("Context must be a positive integer") OldPdb.__init__(self, completekey, stdin, stdout) # IPython changes... self.shell = get_ipython() if self.shell is None: # No IPython instance running, we must create one from IPython.terminal.interactiveshell import \ TerminalInteractiveShell self.shell = TerminalInteractiveShell.instance() self.aliases = {} # Create color table: we copy the default one from the traceback # module and add a few attributes needed for debugging self.color_scheme_table = exception_colors() # shorthands C = coloransi.TermColors cst = self.color_scheme_table cst['NoColor'].colors.prompt = C.NoColor cst['NoColor'].colors.breakpoint_enabled = C.NoColor cst['NoColor'].colors.breakpoint_disabled = C.NoColor cst['Linux'].colors.prompt = C.Green cst['Linux'].colors.breakpoint_enabled = C.LightRed cst['Linux'].colors.breakpoint_disabled = C.Red cst['LightBG'].colors.prompt = C.Blue cst['LightBG'].colors.breakpoint_enabled = C.LightRed cst['LightBG'].colors.breakpoint_disabled = C.Red self.set_colors(color_scheme) # Add a python parser so we can syntax highlight source while # debugging. self.parser = PyColorize.Parser() # Set the prompt - the default prompt is '(Pdb)' self.prompt = prompt
def __init__(self, color_table, code_color_table, scheme, str_detail_level=0): self.color_table = color_table self.parser = PyColorize.Parser(code_color_table, out='str') self.format = self.parser.format self.str_detail_level = str_detail_level self.set_active_scheme(scheme)
def __init__(self, color_table=InspectColors, code_color_table=PyColorize.ANSICodeColors, scheme=None, str_detail_level=0, parent=None, config=None): super(Inspector, self).__init__(parent=parent, config=config) self.color_table = color_table self.parser = PyColorize.Parser(out='str', parent=self, style=scheme) self.format = self.parser.format self.str_detail_level = str_detail_level self.set_active_scheme(scheme)
def _report(ipython, msg): """Output a message prepended by a colored `Autoimport:` tag.""" # Tell prompt_toolkit to pass ANSI escapes through (PTK#187); harmless on # pre-PTK versions. try: sys.stdout._raw = True except AttributeError: pass cs = PyColorize.Parser().color_table[ipython.colors].colors # Token.NUMBER: bright blue (cyan), looks reasonable. print("{}Autoimport:{} {}".format(cs[token.NUMBER], cs["normal"], msg))
def findsymbol(arg): global _symbols_running, _symbols_error, _symbols_last if _symbols_error: print("ipython-suggestions had an error while scanning.") return if _symbols_running: print("ipython-suggestions is still scanning symbols...") return args = parse_argstring(findsymbol, arg) if args.as_ is not None: as_ = ' as %s' % args.as_ else: as_ = '' if '...' in args.symbol: try: name, modulepath = args.symbol.split('...') if modulepath == '': line = 'import %s%s' % (name, as_) else: line = 'from %s import %s%s' % (modulepath, name, as_) except: print("An error occured when trying to import symbol.") else: shell = get_ipython() try: sys.stdout._raw = True except AttributeError: pass cs = PyColorize.Parser().color_table[shell.colors].colors print("{}Suggestions:{} {}".format(cs[token.NUMBER], cs["normal"], line)) shell.execution_count += 1 shell.run_cell(line, store_history=True) return suggestions = close_cached_symbol(args.symbol, args.exact) if suggestions: _symbols_last = [] print("Found the following symbols:") for i, (suggestion, code) in enumerate(suggestions): print(i, suggestion + as_) _symbols_last.append(('exec', code + as_)) else: print("Didn't find symbol.")
def __init__(self, color_scheme='NoColor'): bdb.Bdb.__init__(self) cmd.Cmd.__init__(self, completekey=None) # don't load readline self.prompt = 'ipdb> ' # The default prompt is '(Pdb)' self.aliases = {} # These two lines are part of the py2.4 constructor, let's put them # unconditionally here as they won't cause any problems in 2.3. self.mainpyfile = '' self._wait_for_mainpyfile = 0 # Read $HOME/.pdbrc and ./.pdbrc try: self.rcLines = _file_lines( os.path.join(os.environ['HOME'], ".pdbrc")) except KeyError: self.rcLines = [] self.rcLines.extend(_file_lines(".pdbrc")) # Create color table: we copy the default one from the traceback # module and add a few attributes needed for debugging self.color_scheme_table = exception_colors() # shorthands C = coloransi.TermColors cst = self.color_scheme_table cst['NoColor'].colors.breakpoint_enabled = C.NoColor cst['NoColor'].colors.breakpoint_disabled = C.NoColor cst['Linux'].colors.breakpoint_enabled = C.LightRed cst['Linux'].colors.breakpoint_disabled = C.Red cst['LightBG'].colors.breakpoint_enabled = C.LightRed cst['LightBG'].colors.breakpoint_disabled = C.Red self.set_colors(color_scheme) # Add a python parser so we can syntax highlight source while # debugging. self.parser = PyColorize.Parser()
def suggestion(arg): global _symbols_last args = parse_argstring(suggestion, arg) if -len(_symbols_last) < args.suggestion_index < len(_symbols_last): method, line = _symbols_last[args.suggestion_index] if method == 'exec': shell = get_ipython() try: sys.stdout._raw = True except AttributeError: pass cs = PyColorize.Parser().color_table[shell.colors].colors print("{}Suggestions:{} {}".format(cs[token.NUMBER], cs["normal"], line)) shell.execution_count += 1 shell.run_cell(line, store_history=True) elif method == 'fill': get_ipython().set_next_input(line) else: print("Invalid suggestion index.")
start = max(maybeStart, 0) end = start + context lines = linecache.getlines(file)[start:end] buf = list(records[i]) buf[LNUM_POS] = lnum buf[INDEX_POS] = lnum - 1 - start buf[LINES_POS] = lines records[i] = tuple(buf) return records[tb_offset:] # Helper function -- largely belongs to VerboseTB, but we need the same # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they # can be recognized properly by ipython.el's py-traceback-line-re # (SyntaxErrors have to be treated specially because they have no traceback) _parser = PyColorize.Parser() def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None): numbers_width = INDENT_SIZE - 1 res = [] i = lnum - index # This lets us get fully syntax-highlighted tracebacks. if scheme is None: ipinst = ipapi.get() if ipinst is not None: scheme = ipinst.colors else: scheme = DEFAULT_SCHEME _line_format = _parser.format2
def __init__(self, color_scheme=None, completekey=None, stdin=None, stdout=None, context=5, **kwargs): """Create a new IPython debugger. Parameters ---------- color_scheme : default None Deprecated, do not use. completekey : default None Passed to pdb.Pdb. stdin : default None Passed to pdb.Pdb. stdout : default None Passed to pdb.Pdb. context : int Number of lines of source code context to show when displaying stacktrace information. **kwargs Passed to pdb.Pdb. Notes ----- The possibilities are python version dependent, see the python docs for more info. """ # Parent constructor: try: self.context = int(context) if self.context <= 0: raise ValueError("Context must be a positive integer") except (TypeError, ValueError) as e: raise ValueError("Context must be a positive integer") from e # `kwargs` ensures full compatibility with stdlib's `pdb.Pdb`. OldPdb.__init__(self, completekey, stdin, stdout, **kwargs) # IPython changes... self.shell = get_ipython() if self.shell is None: save_main = sys.modules['__main__'] # No IPython instance running, we must create one from IPython.terminal.interactiveshell import \ TerminalInteractiveShell self.shell = TerminalInteractiveShell.instance() # needed by any code which calls __import__("__main__") after # the debugger was entered. See also #9941. sys.modules["__main__"] = save_main if color_scheme is not None: warnings.warn( "The `color_scheme` argument is deprecated since version 5.1", DeprecationWarning, stacklevel=2) else: color_scheme = self.shell.colors self.aliases = {} # Create color table: we copy the default one from the traceback # module and add a few attributes needed for debugging self.color_scheme_table = exception_colors() # shorthands C = coloransi.TermColors cst = self.color_scheme_table cst['NoColor'].colors.prompt = C.NoColor cst['NoColor'].colors.breakpoint_enabled = C.NoColor cst['NoColor'].colors.breakpoint_disabled = C.NoColor cst['Linux'].colors.prompt = C.Green cst['Linux'].colors.breakpoint_enabled = C.LightRed cst['Linux'].colors.breakpoint_disabled = C.Red cst['LightBG'].colors.prompt = C.Blue cst['LightBG'].colors.breakpoint_enabled = C.LightRed cst['LightBG'].colors.breakpoint_disabled = C.Red cst['Neutral'].colors.prompt = C.Blue cst['Neutral'].colors.breakpoint_enabled = C.LightRed cst['Neutral'].colors.breakpoint_disabled = C.Red # Add a python parser so we can syntax highlight source while # debugging. self.parser = PyColorize.Parser(style=color_scheme) self.set_colors(color_scheme) # Set the prompt - the default prompt is '(Pdb)' self.prompt = prompt self.skip_hidden = True self.report_skipped = True # list of predicates we use to skip frames self._predicates = self.default_predicates
def __init__(self, color_scheme='NoColor', completekey=None, stdin=None, stdout=None, context=5): # Parent constructor: try: self.context = int(context) if self.context <= 0: raise ValueError("Context must be a positive integer") except (TypeError, ValueError): raise ValueError("Context must be a positive integer") if has_pydb and completekey is None: OldPdb.__init__(self, stdin=stdin, stdout=io.stdout) else: OldPdb.__init__(self, completekey, stdin, stdout) # IPython changes... self.is_pydb = has_pydb self.shell = get_ipython() if self.shell is None: # No IPython instance running, we must create one from IPython.terminal.interactiveshell import \ TerminalInteractiveShell self.shell = TerminalInteractiveShell.instance() if self.is_pydb: # interactiveshell.py's ipalias seems to want pdb's checkline # which located in pydb.fn import pydb.fns self.checkline = lambda filename, lineno: \ pydb.fns.checkline(self, filename, lineno) self.curframe = None self.do_restart = self.new_do_restart self.old_all_completions = self.shell.Completer.all_completions self.shell.Completer.all_completions = self.all_completions self.do_list = decorate_fn_with_doc(self.list_command_pydb, OldPdb.do_list) self.do_l = self.do_list self.do_frame = decorate_fn_with_doc(self.new_do_frame, OldPdb.do_frame) self.aliases = {} # Create color table: we copy the default one from the traceback # module and add a few attributes needed for debugging self.color_scheme_table = exception_colors() # shorthands C = coloransi.TermColors cst = self.color_scheme_table cst['NoColor'].colors.prompt = C.NoColor cst['NoColor'].colors.breakpoint_enabled = C.NoColor cst['NoColor'].colors.breakpoint_disabled = C.NoColor cst['Linux'].colors.prompt = C.Green cst['Linux'].colors.breakpoint_enabled = C.LightRed cst['Linux'].colors.breakpoint_disabled = C.Red cst['LightBG'].colors.prompt = C.Blue cst['LightBG'].colors.breakpoint_enabled = C.LightRed cst['LightBG'].colors.breakpoint_disabled = C.Red self.set_colors(color_scheme) # Add a python parser so we can syntax highlight source while # debugging. self.parser = PyColorize.Parser() # Set the prompt - the default prompt is '(Pdb)' Colors = cst.active_colors if color_scheme == 'NoColor': self.prompt = prompt else: # The colour markers are wrapped by bytes 01 and 02 so that readline # can calculate the width. self.prompt = u'\x01%s\x02%s\x01%s\x02' % (Colors.prompt, prompt, Colors.Normal)
def __init__(self, color_scheme=None, completekey=None, stdin=None, stdout=None, context=5): # Parent constructor: try: self.context = int(context) if self.context <= 0: raise ValueError("Context must be a positive integer") except (TypeError, ValueError): raise ValueError("Context must be a positive integer") OldPdb.__init__(self, completekey, stdin, stdout) # IPython changes... self.shell = get_ipython() if self.shell is None: save_main = sys.modules['__main__'] # No IPython instance running, we must create one from IPython.terminal.interactiveshell import \ TerminalInteractiveShell self.shell = TerminalInteractiveShell.instance() # needed by any code which calls __import__("__main__") after # the debugger was entered. See also #9941. sys.modules['__main__'] = save_main if color_scheme is not None: warnings.warn( "The `color_scheme` argument is deprecated since version 5.1", DeprecationWarning) else: color_scheme = self.shell.colors self.aliases = {} # Create color table: we copy the default one from the traceback # module and add a few attributes needed for debugging self.color_scheme_table = exception_colors() # shorthands C = coloransi.TermColors cst = self.color_scheme_table cst['NoColor'].colors.prompt = C.NoColor cst['NoColor'].colors.breakpoint_enabled = C.NoColor cst['NoColor'].colors.breakpoint_disabled = C.NoColor cst['Linux'].colors.prompt = C.Green cst['Linux'].colors.breakpoint_enabled = C.LightRed cst['Linux'].colors.breakpoint_disabled = C.Red cst['LightBG'].colors.prompt = C.Blue cst['LightBG'].colors.breakpoint_enabled = C.LightRed cst['LightBG'].colors.breakpoint_disabled = C.Red cst['Neutral'].colors.prompt = C.Blue cst['Neutral'].colors.breakpoint_enabled = C.LightRed cst['Neutral'].colors.breakpoint_disabled = C.Red self.set_colors(color_scheme) # Add a python parser so we can syntax highlight source while # debugging. self.parser = PyColorize.Parser() # Set the prompt - the default prompt is '(Pdb)' self.prompt = prompt
def _custom_exc(ip, etype, value, tb, tb_offset=None): """Exception handler; attempts to reexecute after loading missing modules. """ global _import_cache with ExitStack() as stack: stack.callback(ip.showtraceback) # Is the innermost frame the IPython interactive environment? while tb.tb_next: tb = tb.tb_next if not re.match(r"\A<ipython-input-.*>\Z", tb.tb_frame.f_code.co_filename): return # Are we just suppressing a context? @stack.callback def _suppress_context(): if value.__context__ == _current_nameerror_stack[-1]: value.__suppress_context__ = True # Retrieve the missing name. tp_regexes = [(NameError, r"\Aname '(.+)' is not defined()\Z"), (AttributeError, r"\Amodule '(.+)' has no attribute '(.+)'\Z")] match = next( filter( None, (re.match(regex, str(value)) if isinstance(value, tp) else None for tp, regex in tp_regexes)), None) if not match: return name, attr = match.groups() (_, _, source), = ip.history_manager.get_tail(1, raw=False, include_latest=True) if not attr: # NameError: was it used as a "module"? as_module = _maybe_modulename(source, name) else: # AttributeError on a module. as_module = True name = "{}.{}".format(name, attr) # Find single matching import, if any. if _import_cache is None: _import_cache = _load_import_cache(ip) imports = ( _import_cache.get(name, {"import {}".format(name)}) if as_module else # If not a module, only keep "from ... import <name>". { entry for entry in _import_cache.get(name, {}) if entry.startswith("from ") }) if len(imports) != 1: if len(imports) > 1: _report(ip, "multiple imports available for {!r}".format(name)) return import_source, = imports cs = PyColorize.Parser().color_table[ip.colors].colors _report(ip, import_source) try: _current_nameerror_stack.append(value) # Prevent chaining. er = ip.run_cell(import_source) if er.error_in_exec: return # Anyways, success! stack.pop_all() ip.run_cell(source) finally: _current_nameerror_stack.pop()
def _report(ip, msg): """Output a message prepended by a colored `Autoimport:` tag. """ cs = PyColorize.Parser().color_table[ip.colors].colors # Token.NUMBER: (light) cyan, looks reasonable. print("{}Autoimport{}: {}".format(cs[token.NUMBER], cs["normal"], msg))
def format_record(self, frame_info): """Format a single stack frame""" Colors = self.Colors # just a shorthand + quicker name lookup ColorsNormal = Colors.Normal # used a lot if isinstance(frame_info, stack_data.RepeatedFrames): return ' %s[... skipping similar frames: %s]%s\n' % ( Colors.excName, frame_info.description, ColorsNormal) col_scheme = self.color_scheme_table.active_scheme_name indent = ' ' * INDENT_SIZE em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal) tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal) tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal) tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \ (Colors.vName, Colors.valEm, ColorsNormal) tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal) tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal) file = frame_info.filename file = py3compat.cast_unicode(file, util_path.fs_encoding) link = tpl_link % util_path.compress_user(file) args, varargs, varkw, locals_ = inspect.getargvalues(frame_info.frame) func = frame_info.executing.code_qualname() if func == '<module>': call = tpl_call % (func, '') else: # Decide whether to include variable details or not var_repr = eqrepr if self.include_vars else nullrepr try: call = tpl_call % ( func, inspect.formatargvalues( args, varargs, varkw, locals_, formatvalue=var_repr)) except KeyError: # This happens in situations like errors inside generator # expressions, where local variables are listed in the # line, but can't be extracted from the frame. I'm not # 100% sure this isn't actually a bug in inspect itself, # but since there's no info for us to compute with, the # best we can do is report the failure and move on. Here # we must *not* call any traceback construction again, # because that would mess up use of %debug later on. So we # simply report the failure and move on. The only # limitation will be that this frame won't have locals # listed in the call signature. Quite subtle problem... # I can't think of a good way to validate this in a unit # test, but running a script consisting of: # dict( (k,v.strip()) for (k,v) in range(10) ) # will illustrate the error, if this exception catch is # disabled. call = tpl_call_fail % func lvals = '' lvals_list = [] if self.include_vars: for var in frame_info.variables_in_executing_piece: lvals_list.append(tpl_name_val % (var.name, repr(var.value))) if lvals_list: lvals = '%s%s' % (indent, em_normal.join(lvals_list)) result = '%s %s\n' % (link, call) _line_format = PyColorize.Parser(style=col_scheme, parent=self).format2 result += ''.join( _format_traceback_lines(frame_info.lines, Colors, lvals, _line_format)) return result