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))
python类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 __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 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 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 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 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 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 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 _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.
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 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 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 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(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 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():
# 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 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 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 _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