我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用traceback.format_list()。
def __init__(self, msg='', ex=None): """ :param msg: error message :type msg: string :param ex: exception causing this error (optional) :type ex: exception """ self.msg = msg assert not isinstance(msg, Exception) self.stack = [] if ex: if not msg: self.msg = str(ex) if isinstance(ex, WafError): self.stack = ex.stack else: self.stack = traceback.extract_tb(sys.exc_info()[2]) self.stack += traceback.extract_stack()[:-1] self.verbose_msg = ''.join(traceback.format_list(self.stack))
def format_exception(bfn, ex): import traceback, linecache exinfo = traceback.format_exception_only(ex.__class__, ex) if ex.__class__ == SyntaxError: exinfo = exinfo[1:] lineno = ex.lineno content = '' sys.stderr.write('Error while processing %s:%s\n\t%s\n' % (os.path.abspath(bfn), lineno, content.strip())) else: exec_line = None exloc = traceback.extract_tb(sys.exc_info()[2]) for idx, entry in enumerate(exloc): if entry[3] is None: exec_line = idx if exec_line is not None: exloc = [(bfn, exloc[exec_line][1], '', linecache.getline(bfn, exloc[exec_line][1]))] + exloc[exec_line:] sys.stderr.write('Error while processing %s\n' % os.path.abspath(bfn)) sys.stderr.write(str.join('', traceback.format_list(exloc))) sys.stderr.write(str.join('', exinfo)) sys.exit(1)
def showtraceback(self): """Display the exception that just occurred. We remove the first stack item because it is our own code. The output is written by self.write(), below. """ try: type, value, tb = sys.exc_info() sys.last_type = type sys.last_value = value sys.last_traceback = tb tblist = traceback.extract_tb(tb) del tblist[:1] list = traceback.format_list(tblist) if list: list.insert(0, "Traceback (most recent call last):\n") list[len(list):] = traceback.format_exception_only(type, value) finally: tblist = tb = None map(self.write, list)
def print_exception(exc_type, exc_value, exc_tb): # remove debugger frames from the top and bottom of the traceback tb = traceback.extract_tb(exc_tb) for i in [0, -1]: while tb: frame_file = path.normcase(tb[i][0]) if not any(is_same_py_file(frame_file, f) for f in DONT_DEBUG): break del tb[i] # print the traceback if tb: print('Traceback (most recent call last):') for out in traceback.format_list(tb): sys.stderr.write(out) # print the exception for out in traceback.format_exception_only(exc_type, exc_value): sys.stdout.write(out)
def __del__(self): if self.tb: msg = 'Future/Task exception was never retrieved\n' if self.source_traceback: src = ''.join(traceback.format_list(self.source_traceback)) msg += 'Future/Task created at (most recent call last):\n' msg += '%s\n' % src.rstrip() msg += ''.join(self.tb).rstrip() self.loop.call_exception_handler({'message': msg}) ######################################### # Future ? # # ??: # - ??? # - Future??????iter?????? # - ?????????: # - BaseEventLoop() ??, ????? # - Task() ??, ????? # - ???????, ????? # #########################################
def __del__(self): # Be careful accessing self.gen.frame -- self.gen might not exist. gen = getattr(self, 'gen', None) frame = getattr(gen, 'gi_frame', None) if frame is not None and frame.f_lasti == -1: msg = '%r was never yielded from' % self tb = getattr(self, '_source_traceback', ()) if tb: tb = ''.join(traceback.format_list(tb)) msg += ('\nCoroutine object created at ' '(most recent call last):\n') msg += tb.rstrip() logger.error(msg) ######################################### # ????? # # ??: # #########################################
def _in_thread_run_script(self): """ Run the script. """ try: self.run_script() except Exception as e: # handle any exception thrown exc_type,exc_value,exc_traceback = sys.exc_info() print "Exception Error: ", exc_value print e # print traceback, excluding this file traceback.print_tb(exc_traceback) # exc_strings = traceback.format_list(traceback.extract_tb(exc_traceback)) # exc_strings = [s for s in exc_strings if s.find("parlay_script.py")< 0 ] # for s in exc_strings: # print s
def showtraceback(self): """Display the exception that just occurred.""" #Override for avoid using sys.excepthook PY-12600 try: type, value, tb = sys.exc_info() sys.last_type = type sys.last_value = value sys.last_traceback = tb tblist = traceback.extract_tb(tb) del tblist[:1] lines = traceback.format_list(tblist) if lines: lines.insert(0, "Traceback (most recent call last):\n") lines.extend(traceback.format_exception_only(type, value)) finally: tblist = tb = None sys.stderr.write(''.join(lines))
def format_exc(limit=None, exception=None, tb_list=None): """ This is like print_exc(limit) but returns a string instead of printing to a file. """ result = ["Traceback (most recent call last):\n"] if exception is None: exception = get_context_with_traceback(get_async_context()).exception if tb_list is None: tb_list = extract_tb(limit) if tb_list: result.extend(traceback.format_list(tb_list)) result.extend(traceback.format_exception_only(exception.__class__, exception)) return result else: return None
def format_exc(self, limit=None): """ This is like exception.print_exc(limit) but returns a string instead of printing to a file. """ result = ["Traceback (most recent call last):\n"] tb_list = self._traceback if limit is not None: tb_list = tb_list[-limit:] result.extend(traceback.format_list(tb_list)) if self.cause is not None: result.extend(traceback.format_exception_only(self.cause.__class__, self.cause)) return result else: return result
def blockingCallFromThread(reactor, f, *args, **kwargs): """ Improved version of twisted's blockingCallFromThread that shows the complete stacktrace when an exception is raised on the reactor's thread. If being called from the reactor thread already, just return the result of execution of the callable. """ if isInIOThread(): return f(*args, **kwargs) else: queue = Queue.Queue() def _callFromThread(): result = defer.maybeDeferred(f, *args, **kwargs) result.addBoth(queue.put) reactor.callFromThread(_callFromThread) result = queue.get() if isinstance(result, failure.Failure): other_thread_tb = traceback.extract_tb(result.getTracebackObject()) this_thread_tb = traceback.extract_stack() logger.error("Exception raised on the reactor's thread %s: \"%s\".\n Traceback from this thread:\n%s\n" " Traceback from the reactor's thread:\n %s", result.type.__name__, result.getErrorMessage(), ''.join(traceback.format_list(this_thread_tb)), ''.join(traceback.format_list(other_thread_tb))) result.raiseException() return result
def setUpClass(cls): cls.__lockup_timestamp__ = time.time() def check_twisted(): while time.time() - cls.__lockup_timestamp__ < cls.MAX_TEST_TIME: time.sleep(2) # If the test class completed normally, exit if not cls.__testing__: return # If we made it here, there is a serious issue which we cannot recover from. # Most likely the Twisted threadpool got into a deadlock while shutting down. import os, traceback print >> sys.stderr, "The test-suite locked up! Force quitting! Thread dump:" for tid, stack in sys._current_frames().items(): if tid != threading.currentThread().ident: print >> sys.stderr, "THREAD#%d" % tid for line in traceback.format_list(traceback.extract_stack(stack)): print >> sys.stderr, "|", line[:-1].replace('\n', '\n| ') os._exit(1) t = threading.Thread(target=check_twisted) t.daemon = True t.start()
def print_exception(): # count the debugger frames to be removed tb = traceback.extract_tb(sys.exc_info()[2]) debugger_count = len(tb) while debugger_count: if is_same_py_file(tb[debugger_count - 1][0], __file__): break debugger_count -= 1 # print the traceback tb = tb[debugger_count:] if tb: print('Traceback (most recent call last):') for out in traceback.format_list(tb): sys.stdout.write(out) # print the exception for out in traceback.format_exception_only(sys.exc_info()[0], sys.exc_info()[1]): sys.stdout.write(out)
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_thread_stack(frame, skip_modules=[threading]): stack = traceback.extract_stack(frame) if skip_modules: itr_stack = iter(stack) items = [] fnames = {m.__file__ for m in ilistify(skip_modules)} # skip everything until after specified module for fname, *_ in itr_stack: if fname in fnames: items.append([fname] + _) for i, (fname, *_) in enumerate(itr_stack, 1): if fname not in fnames: if i > 1: items.append([last_fname, "...(%s)" % i, "---", "---"]) break last_fname = fname items.append([fname] + _) if len(items) <= 2: items = stack else: items = stack return ''.join(traceback.format_list(items))
def threadDump(signum, frame): """Signal handler for dumping thread stack frames to stdout.""" print print "App server has been signaled to attempt a thread dump." print print "Thread stack frame dump at", asclocaltime() sys.stdout.flush() frames = sys._current_frames() print print "-" * 79 print for threadID in sorted(frames): frame = frames[threadID] print "Thread ID: %d (reference count = %d)" % ( threadID, sys.getrefcount(frame)) print ''.join(traceback.format_list(traceback.extract_stack(frame))) print "-" * 79 sys.stdout.flush()
def format_lines(self): lines = self.traceback_format() return ''.join(traceback.format_list(lines))
def format_trace(self): if self.has_trace(): # convert trace entries back to tuples. the trace member was # set by the server side rpc mechanism. rpc messages cannot # contain tuples (incompatible with JSON) so the entries were # converted to lists. convert = [] for entry in self.trace: convert.append(tuple(entry)) formatted = traceback.format_list(convert) return ''.join(formatted) return ''
def follow_config(path, poll_interval=1.0, force_interval=30.0): last_reload = -float("inf") last_mtime = None last_error_msg = None abspath = os.path.abspath(path) while True: now = time.time() if now < last_reload: last_reload = now mtime = os.path.getmtime(abspath) if now > last_reload + force_interval or last_mtime != mtime: try: configs = load_configs(abspath) except Exception: _, exc_value, exc_tb = sys.exc_info() stack = traceback.extract_tb(exc_tb) stack = stack[1:] # Make the traceback flatter by discarding the current stack frame error_msg = "Could not load {path!r} (most recent call last):\n{stack}\n{exception}".format( path=abspath, stack="".join(traceback.format_list(stack)).rstrip(), exception=utils.format_exception(exc_value) ) if error_msg != last_error_msg: yield idiokit.send(False, error_msg) last_error_msg = error_msg last_mtime = None else: yield idiokit.send(True, configs) last_error_msg = None last_mtime = mtime last_reload = now yield idiokit.sleep(poll_interval)
def traceback_to_string(exc, tb=None): _tb = tb or exc.__traceback__ s = traceback.extract_stack()[:-3] + traceback.extract_tb(_tb) l = traceback.format_list(s) return ''.join(l) + '\\n {} {}'.format(exc.__class__, exc)
def format_exception(self): """ Return the same data as from traceback.format_exception. """ import traceback frames = self.get_traceback_frames() tb = [(f['filename'], f['lineno'], f['function'], f['context_line']) for f in frames] list = ['Traceback (most recent call last):\n'] list += traceback.format_list(tb) list += traceback.format_exception_only(self.exc_type, self.exc_value) return list
def console(self, message): self.set_point(self.get_length()) self.freeze() previous_kind = None style = self.get_style() style_cache = {} try: for element in message: if element[0] == 'exception': s = traceback.format_list(element[1]['traceback']) s.extend(element[1]['exception']) s = string.join(s, '') else: s = element[1] if element[0] != previous_kind: style = style_cache.get(element[0], None) if style is None: gtk.rc_parse_string( 'widget \"Manhole.*.Console\" ' 'style \"Console_%s\"\n' % (element[0])) self.set_rc_style() style_cache[element[0]] = style = self.get_style() # XXX: You'd think we'd use style.bg instead of 'None' # here, but that doesn't seem to match the color of # the backdrop. self.insert(style.font, style.fg[gtk.STATE_NORMAL], None, s) previous_kind = element[0] l = self.get_length() diff = self.maxBufSz - l if diff < 0: diff = - diff self.delete_text(0,diff) finally: self.thaw() a = self.get_vadjustment() a.set_value(a.upper - a.page_size)
def handle_exception(exc_type, exc_value, exc_tb): # Specifies list of files not to display in stack trace. do_not_debug = [__file__, _vspu.__file__] if sys.version_info >= (3, 3): do_not_debug.append('<frozen importlib._bootstrap>') if sys.version_info >= (3, 5): do_not_debug.append('<frozen importlib._bootstrap_external>') # Remove debugger frames from the top and bottom of the traceback. tb = traceback.extract_tb(exc_tb) for i in [0, -1]: while tb: frame_file = path.normcase(tb[i][0]) if not any(is_same_py_file(frame_file, f) for f in do_not_debug): break del tb[i] # Print the traceback. if tb: sys.stderr.write('Traceback (most recent call last):') for out in traceback.format_list(tb): sys.stderr.write(out) sys.stderr.flush() # Print the exception. for out in traceback.format_exception_only(exc_type, exc_value): sys.stderr.write(out) sys.stderr.flush()
def trouble(self, message=None, tb=None): """Determine action to take when a download problem appears. Depending on if the downloader has been configured to ignore download errors or not, this method may throw an exception or not when errors are found, after printing the message. tb, if given, is additional traceback information. """ if message is not None: self.to_stderr(message) if self.params.get('verbose'): if tb is None: if sys.exc_info()[0]: # if .trouble has been called from an except block tb = '' if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]: tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info)) tb += encode_compat_str(traceback.format_exc()) else: tb_data = traceback.format_list(traceback.extract_stack()) tb = ''.join(tb_data) self.to_stderr(tb) if not self.params.get('ignoreerrors', False): if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]: exc_info = sys.exc_info()[1].exc_info else: exc_info = sys.exc_info() raise DownloadError(message, exc_info) self._download_retcode = 1
def get_trace(self): '''This returns an abbreviated stack trace with lines that only concern the caller. In other words, the stack trace inside the Pexpect module is not included. ''' tblist = traceback.extract_tb(sys.exc_info()[2]) tblist = [item for item in tblist if ('pexpect/__init__' not in item[0]) and ('pexpect/expect' not in item[0])] tblist = traceback.format_list(tblist) return ''.join(tblist)
def _print_traceback(self): base_path = getattr(settings, 'ERASERHEAD_TRACEBACK_BASE_PATH', None) for trace_line in traceback.format_list(self._traceback): if base_path and (base_path not in trace_line): continue print("\t" + trace_line.strip().replace('\n', '\n\t'))
def set_test_result(self, test_id, result_state, output, when, outcome, exc_type=None, exc_value=None, extracted_traceback=None, last_failed_exempt=None): if not test_id in self.test_data: self.test_data[test_id] = { 'id': test_id } if extracted_traceback: output += ''.join( traceback.format_list(extracted_traceback) + [exc_value] ) test_data = self.test_data[test_id] test_data['exc_type'] = exc_type test_data['exc_value'] = exc_value test_data['exc_tb'] = extracted_traceback if when == 'call' and last_failed_exempt is not None: test_data['last_failed_exempt'] = last_failed_exempt # Ignore success, except for the 'call' step # ignore successive failure, take only the first if (outcome != 'passed' or when == 'call') \ and not test_data.get('result_state'): test_data['result_state'] = result_state test_data['output'] = output self.ui.update_test_result(test_data) if when == 'teardown': test_data['runstate'] = None self.ui.update_test_line(test_data)
def warn(*args, **kwargs): tb = traceback.extract_stack() _old_warn(*args, **kwargs) print("".join(traceback.format_list(tb)[:-1]))