我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用linecache.checkcache()。
def __init__(self): codeop.Compile.__init__(self) # This is ugly, but it must be done this way to allow multiple # simultaneous ipython instances to coexist. Since Python itself # directly accesses the data structures in the linecache module, and # the cache therein is global, we must work with that data structure. # We must hold a reference to the original checkcache routine and call # that in our own check_cache() below, but the special IPython cache # must also be shared by all IPython instances. If we were to hold # separate caches (one in each CachingCompiler instance), any call made # by Python itself to linecache.checkcache() would obliterate the # cached data from the other IPython instances. if not hasattr(linecache, '_ipython_cache'): linecache._ipython_cache = {} if not hasattr(linecache, '_checkcache_ori'): linecache._checkcache_ori = linecache.checkcache # Now, we must monkeypatch the linecache directly so that parts of the # stdlib that call it outside our control go through our codepath # (otherwise we'd lose our tracebacks). linecache.checkcache = check_linecache_ipython
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): """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).""" 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 # By default we use linecache.checkcache, but the user can provide a # different check_cache implementation. This is used by the IPython # kernel to provide tracebacks for interactive code that is cached, # by a compiler instance that flushes the linecache but preserves its # own code cache. if check_cache is None: check_cache = linecache.checkcache self.check_cache = check_cache self.debugger_cls = debugger_cls or debugger.Pdb
def print_exception(): import linecache linecache.checkcache() flush_stdout() efile = sys.stderr typ, val, tb = excinfo = sys.exc_info() sys.last_type, sys.last_value, sys.last_traceback = excinfo tbe = traceback.extract_tb(tb) print('Traceback (most recent call last):', file=efile) exclude = ("run.py", "rpc.py", "threading.py", "queue.py", "RemoteDebugger.py", "bdb.py") cleanup_traceback(tbe, exclude) traceback.print_list(tbe, file=efile) lines = traceback.format_exception_only(typ, val) for line in lines: print(line, end='', file=efile)
def extended_linecache_checkcache(filename=None, orig_checkcache=linecache.checkcache): """Extend linecache.checkcache to preserve the <pyshell#...> entries Rather than repeating the linecache code, patch it to save the <pyshell#...> entries, call the original linecache.checkcache() (skipping them), and then restore the saved entries. orig_checkcache is bound at definition time to the original method, allowing it to be patched. """ cache = linecache.cache save = {} for key in list(cache): if key[:1] + key[-1:] == '<>': save[key] = cache.pop(key) orig_checkcache(filename) cache.update(save) # Patch linecache.checkcache():
def print_exception(): import linecache linecache.checkcache() flush_stdout() efile = sys.stderr typ, val, tb = excinfo = sys.exc_info() sys.last_type, sys.last_value, sys.last_traceback = excinfo tbe = traceback.extract_tb(tb) print>>efile, '\nTraceback (most recent call last):' exclude = ("run.py", "rpc.py", "threading.py", "Queue.py", "RemoteDebugger.py", "bdb.py") cleanup_traceback(tbe, exclude) traceback.print_list(tbe, file=efile) lines = traceback.format_exception_only(typ, val) for line in lines: print>>efile, line,
def SaveFile(self, fileName, encoding=None): if isRichText: view = self.GetFirstView() view.SaveTextFile(fileName, encoding=encoding) else: # Old style edit view window. self.GetFirstView().SaveFile(fileName) try: # Make sure line cache has updated info about me! import linecache linecache.checkcache() except: pass # # Color state stuff #
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): """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).""" TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, ostream=ostream) self.tb_offset = tb_offset self.long_header = long_header self.include_vars = include_vars # By default we use linecache.checkcache, but the user can provide a # different check_cache implementation. This is used by the IPython # kernel to provide tracebacks for interactive code that is cached, # by a compiler instance that flushes the linecache but preserves its # own code cache. if check_cache is None: check_cache = linecache.checkcache self.check_cache = check_cache self.debugger_cls = debugger_cls or debugger.Pdb
def _extract_tb_or_stack_iter(curr, limit, extractor): if limit is None: limit = getattr(sys, 'tracebacklimit', None) n = 0 while curr is not None and (limit is None or n < limit): f, lineno, next_item = extractor(curr) co = f.f_code filename = co.co_filename name = co.co_name linecache.checkcache(filename) line = linecache.getline(filename, lineno, f.f_globals) if line: line = line.strip() else: line = None yield (filename, lineno, name, line) curr = next_item n += 1
def _format_stack(task): ''' Formats a traceback from a stack of coroutines/generators ''' extracted_list = [] checked = set() for f in _get_stack(task): lineno = f.f_lineno co = f.f_code filename = co.co_filename name = co.co_name if filename not in checked: checked.add(filename) linecache.checkcache(filename) line = linecache.getline(filename, lineno, f.f_globals) extracted_list.append((filename, lineno, name, line)) if not extracted_list: resp = 'No stack for %r' % task else: resp = 'Stack for %r (most recent call last):\n' % task resp += ''.join(traceback.format_list(extracted_list)) return resp
def _format_stack(task): extracted_list = [] checked = set() for f in _get_stack(task): lineno = f.f_lineno co = f.f_code filename = co.co_filename name = co.co_name if filename not in checked: checked.add(filename) linecache.checkcache(filename) line = linecache.getline(filename, lineno, f.f_globals) extracted_list.append((filename, lineno, name, line)) if not extracted_list: resp = 'No stack for %r' % task else: resp = 'Stack for %r (most recent call last):\n' % task resp += ''.join(traceback.format_list(extracted_list)) return resp
def _format_traceback_line(self, tb): """ Formats the file / lineno / function line of a traceback element. Returns None is the line is not relevent to the user i.e. inside the test runner. """ if self._is_relevant_tb_level(tb): return None f = tb.tb_frame filename = f.f_code.co_filename lineno = tb.tb_lineno linecache.checkcache(filename) function_name = f.f_code.co_name line_contents = linecache.getline(filename, lineno, f.f_globals).strip() return " %s line %s in %s\n %s" % ( termstyle.blue(self._relative_path(filename) if self.use_relative_path else filename), termstyle.bold(termstyle.cyan(lineno)), termstyle.cyan(function_name), line_contents )
def extract_tb(tb, limit=None): """This implementation is stolen from traceback module but respects __traceback_hide__.""" if limit is None: if hasattr(sys, 'tracebacklimit'): limit = sys.tracebacklimit tb_list = [] n = 0 while tb is not None and (limit is None or n < limit): f = tb.tb_frame if not _should_skip_frame(f): lineno = tb.tb_lineno co = f.f_code filename = co.co_filename name = co.co_name linecache.checkcache(filename) line = linecache.getline(filename, lineno, f.f_globals) if line: line = line.strip() else: line = None tb_list.append((filename, lineno, name, line)) tb = tb.tb_next n = n + 1 return tb_list
def print_tb(tb, limit=None, file=None): """Print up to 'limit' stack trace entries from the traceback 'tb'. If 'limit' is omitted or None, all entries are printed. If 'file' is omitted or None, the output goes to sys.stderr; otherwise 'file' should be an open file or file-like object with a write() method. """ if file is None: file = sys.stderr if limit is None: if hasattr(sys, 'tracebacklimit'): limit = sys.tracebacklimit n = 0 while tb is not None and (limit is None or n < limit): f = tb.tb_frame lineno = tb.tb_lineno co = f.f_code filename = co.co_filename name = co.co_name _print(file, ' File "%s", line %d, in %s' % (filename, lineno, name)) linecache.checkcache(filename) line = linecache.getline(filename, lineno, f.f_globals) if line: _print(file, ' ' + line.strip()) tb = tb.tb_next n = n+1
def extract_tb(tb, limit = None): """Return list of up to limit pre-processed entries from traceback. This is useful for alternate formatting of stack traces. If 'limit' is omitted or None, all entries are extracted. A pre-processed stack trace entry is a quadruple (filename, line number, function name, text) representing the information that is usually printed for a stack trace. The text is a string with leading and trailing whitespace stripped; if the source is not available it is None. """ if limit is None: if hasattr(sys, 'tracebacklimit'): limit = sys.tracebacklimit list = [] n = 0 while tb is not None and (limit is None or n < limit): f = tb.tb_frame lineno = tb.tb_lineno co = f.f_code filename = co.co_filename name = co.co_name linecache.checkcache(filename) line = linecache.getline(filename, lineno, f.f_globals) if line: line = line.strip() else: line = None list.append((filename, lineno, name, line)) tb = tb.tb_next n = n+1 return list
def extract_stack(f=None, limit = None): """Extract the raw traceback from the current stack frame. The return value has the same format as for extract_tb(). The optional 'f' and 'limit' arguments have the same meaning as for print_stack(). Each item in the list is a quadruple (filename, line number, function name, text), and the entries are in order from oldest to newest stack frame. """ if f is None: try: raise ZeroDivisionError except ZeroDivisionError: f = sys.exc_info()[2].tb_frame.f_back if limit is None: if hasattr(sys, 'tracebacklimit'): limit = sys.tracebacklimit list = [] n = 0 while f is not None and (limit is None or n < limit): lineno = f.f_lineno co = f.f_code filename = co.co_filename name = co.co_name linecache.checkcache(filename) line = linecache.getline(filename, lineno, f.f_globals) if line: line = line.strip() else: line = None list.append((filename, lineno, name, line)) f = f.f_back n = n+1 list.reverse() return list
def reset(self): import linecache linecache.checkcache() self.botframe = None self._set_stopinfo(None, None)
def GetException(): exc_type, exc_obj, tb = sys.exc_info() f = tb.tb_frame lineno = tb.tb_lineno filename = f.f_code.co_filename linecache.checkcache(filename) line = linecache.getline(filename, lineno, f.f_globals) return 'EXCEPTION {} IN ({}, LINE {} "{}"): {}'.format(exc_type, filename, lineno, line.strip(), exc_obj)
def print_stack(self, *, limit=None, file=None): """Print the stack or traceback for this task's coroutine. This produces output similar to that of the traceback module, for the frames retrieved by get_stack(). The limit argument is passed to get_stack(). The file argument is an I/O stream to which the output is written; by default output is written to sys.stderr. """ extracted_list = [] checked = set() for f in self.get_stack(limit=limit): lineno = f.f_lineno co = f.f_code filename = co.co_filename name = co.co_name if filename not in checked: checked.add(filename) linecache.checkcache(filename) line = linecache.getline(filename, lineno, f.f_globals) extracted_list.append((filename, lineno, name, line)) exc = self._exception if not extracted_list: print('No stack for %r' % self, file=file) elif exc is not None: print('Traceback for %r (most recent call last):' % self, file=file) else: print('Stack for %r (most recent call last):' % self, file=file) traceback.print_list(extracted_list, file=file) if exc is not None: for line in traceback.format_exception_only(exc.__class__, exc): print(line, file=file, end='')
def PrintException(): exc_type, exc_obj, tb = sys.exc_info() f = tb.tb_frame lineno = tb.tb_lineno filename = f.f_code.co_filename linecache.checkcache(filename) line = linecache.getline(filename, lineno, f.f_globals) print('EXCEPTION IN ({}, LINE {} "{}"): {}'.format( filename, lineno, line.strip(), exc_obj))
def check_linecache_ipython(*args): """Call linecache.checkcache() safely protecting our cached values. """ # First call the orignal checkcache as intended linecache._checkcache_ori(*args) # Then, update back the cache with our data, so that tracebacks related # to our compiled codes can be produced. linecache.cache.update(linecache._ipython_cache)
def psource(self, obj, oname=''): """Print the source code for an object.""" # Flush the source cache because inspect can return out-of-date source linecache.checkcache() try: src = getsource(obj, oname=oname) except Exception: src = None if src is None: self.noinfo('source', oname) else: page.page(self.format(src))
def test_compiler_check_cache(): """Test the compiler properly manages the cache. """ # Rather simple-minded tests that just exercise the API cp = compilerop.CachingCompiler() cp.cache('x=1', 99) # Ensure now that after clearing the cache, our entries survive linecache.checkcache() for k in linecache.cache: if k.startswith('<ipython-input-99'): break else: raise AssertionError('Entry for input-99 missing from linecache')
def extract_tb(tb, limit=None): """Return list of up to limit pre-processed entries from traceback. This is useful for alternate formatting of stack traces. If 'limit' is omitted or None, all entries are extracted. A pre-processed stack trace entry is a quadruple (filename, line number, function name, text) representing the information that is usually printed for a stack trace. The text is a string with leading and trailing whitespace stripped; if the source is not available it is None. """ if limit is None: if hasattr(sys, 'tracebacklimit'): limit = sys.tracebacklimit list = [] n = 0 while tb is not None and (limit is None or n < limit): f = tb.tb_frame lineno = tb.tb_lineno co = f.f_code filename = co.co_filename name = co.co_name linecache.checkcache(filename) line = linecache.getline(filename, lineno, f.f_globals) if line: line = line.strip() else: line = None list.append((filename, lineno, name, line)) tb = tb.tb_next n = n+1 return list