本文整理汇总了Python中traceback.extract_tb方法的典型用法代码示例。如果您正苦于以下问题:Python traceback.extract_tb方法的具体用法?Python traceback.extract_tb怎么用?Python traceback.extract_tb使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类traceback
的用法示例。
在下文中一共展示了traceback.extract_tb方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_future_traceback
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_tb [as 别名]
def test_future_traceback(self):
@return_future
@gen.engine
def f(callback):
yield gen.Task(self.io_loop.add_callback)
try:
1 / 0
except ZeroDivisionError:
self.expected_frame = traceback.extract_tb(
sys.exc_info()[2], limit=1)[0]
raise
try:
yield f()
self.fail("didn't get expected exception")
except ZeroDivisionError:
tb = traceback.extract_tb(sys.exc_info()[2])
self.assertIn(self.expected_frame, tb)
# The following series of classes demonstrate and test various styles
# of use, with and without generators and futures.
示例2: extra_serializer
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_tb [as 别名]
def extra_serializer(obj: Any) -> Union[int, str, List[Any], Dict[str, Any]]:
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, datetime.datetime):
return dtutil.dt2ts(obj)
if isinstance(obj, bytes):
return obj.decode('utf-8')
if isinstance(obj, decimal.Decimal):
return obj.to_eng_string()
if isinstance(obj, (set, KeysView)):
return list(obj)
if isinstance(obj, Exception):
stack = traceback.extract_tb(obj.__traceback__)
return traceback.format_list(stack)
if hasattr(obj, 'to_dict'):
return obj.to_dict()
if hasattr(obj, '__attrs_attrs__'):
val: Dict[str, Any] = {}
for a in obj.__attrs_attrs__:
val[a.name] = getattr(obj, a.name)
return val
raise TypeError('Type {t} not serializable - {obj}'.format(t=type(obj), obj=obj))
示例3: hook_exceptions
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_tb [as 别名]
def hook_exceptions(self, logger: logging.RootLogger) -> None:
"""Format excetion traceback.
Parameters:
logger:
The logger for logging exceptions.
"""
def _hook(exc_type, value, exc_tb) -> None:
nest_dir = os.path.dirname(os.path.abspath(__file__))
traceback_str = ''
idx = 0
for file_name, line_number, func_name, text in traceback.extract_tb(exc_tb)[1:]:
# skip Nest-related tracebacks to make it more readable
if os.path.dirname(os.path.abspath(file_name)) == nest_dir:
continue
idx += 1
traceback_str += '\n [%d] File "%s", line %d, in function "%s"\n %s' % \
(idx, file_name, line_number, func_name, text)
if traceback_str != '':
traceback_str = 'Traceback: ' + traceback_str
logger.critical('Exception occurred during resolving:\nType: %s\nMessage: %s\n%s' % \
(exc_type.__name__, value, traceback_str))
sys.excepthook = _hook
示例4: log_excepthook
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_tb [as 别名]
def log_excepthook(exc_class, exc_value, tb):
import traceback
tb_txt = ''.join(traceback.format_tb(tb))
try:
(filename, number, function, line_text) = traceback.extract_tb(tb)[-1]
exc_txt = "{} line {} function {} [{}]".format(
filename, number, function, line_text)
except Exception:
exc_txt = ""
logger.error("Unhandled exception '{}' at {}"
.format(exc_value, exc_txt),
traceback=tb_txt,
exc_class=repr(exc_class),
exc_value=repr(exc_value))
sys.__excepthook__(exc_class, exc_value, tb)
示例5: log_excepthook
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_tb [as 别名]
def log_excepthook(exc_class, exc_value, tb):
# at this point we have substituted the module once,
# so we need to import all modules again
import traceback
import kano.logging # Don't think about this one too hard...
import sys
tb_txt = ''.join(traceback.format_tb(tb))
try:
(filename, number, function, line_text) = traceback.extract_tb(tb)[-1]
exc_txt = "{} line {} function {} [{}]".format(
filename, number, function, line_text)
except Exception:
exc_txt = ""
kano.logging.logger.error(
"Unhandled exception '{}' at {} (see logfile for full trace)".format(
exc_value, exc_txt
),
traceback=tb_txt,
exc_class=str(exc_class),
exc_value=str(exc_value)
)
sys.__excepthook__(exc_class, exc_value, tb)
示例6: check_errors
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_tb [as 别名]
def check_errors(fn):
def wrapper(*args, **kwargs):
try:
fn(*args, **kwargs)
except (ImportError, IndentationError, NameError, SyntaxError,
TypeError, AttributeError):
et, ev, tb = sys.exc_info()
if getattr(ev, 'filename', None) is None:
# get the filename from the last item in the stack
filename = traceback.extract_tb(tb)[-1][0]
else:
filename = ev.filename
if filename not in _error_files:
_error_files.append(filename)
raise
return wrapper
示例7: showtraceback
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_tb [as 别名]
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)
示例8: SConscript_exception
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_tb [as 别名]
def SConscript_exception(file=sys.stderr):
"""Print an exception stack trace just for the SConscript file(s).
This will show users who have Python errors where the problem is,
without cluttering the output with all of the internal calls leading
up to where we exec the SConscript."""
exc_type, exc_value, exc_tb = sys.exc_info()
tb = exc_tb
while tb and stack_bottom not in tb.tb_frame.f_locals:
tb = tb.tb_next
if not tb:
# We did not find our exec statement, so this was actually a bug
# in SCons itself. Show the whole stack.
tb = exc_tb
stack = traceback.extract_tb(tb)
try:
type = exc_type.__name__
except AttributeError:
type = str(exc_type)
if type[:11] == "exceptions.":
type = type[11:]
file.write('%s: %s:\n' % (type, exc_value))
for fname, line, func, text in stack:
file.write(' File "%s", line %d:\n' % (fname, line))
file.write(' %s\n' % text)
示例9: find_deepest_user_frame
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_tb [as 别名]
def find_deepest_user_frame(tb):
"""
Find the deepest stack frame that is not part of SCons.
Input is a "pre-processed" stack trace in the form
returned by traceback.extract_tb() or traceback.extract_stack()
"""
tb.reverse()
# find the deepest traceback frame that is not part
# of SCons:
for frame in tb:
filename = frame[0]
if filename.find(os.sep+'SCons'+os.sep) == -1:
return frame
return tb[0]
示例10: doTraceback
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_tb [as 别名]
def doTraceback(self, module):
try:
module.do_raise()
except:
tb = sys.exc_info()[2].tb_next
f,lno,n,line = extract_tb(tb, 1)[0]
self.assertEqual(line, raise_src.strip())
f,lno,n,line = extract_stack(tb.tb_frame, 1)[0]
self.assertEqual(line, raise_src.strip())
s = StringIO.StringIO()
print_tb(tb, 1, s)
self.assertTrue(s.getvalue().endswith(raise_src))
else:
raise AssertionError("This ought to be impossible")
示例11: format_exc
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_tb [as 别名]
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
示例12: output_wechat
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_tb [as 别名]
def output_wechat():
from . import config
exc_type, exc_value, exc_tb = sys.exc_info()
exc_type_msg = exc_type.__name__ if exc_type else exc_type
exc_tbs = sorted(
[e for e in traceback.extract_tb(exc_tb)],
key=lambda e: len(e.filename))
exc_tb = exc_tbs[0] if exc_tbs else None
exc_tb = exc_tb if exc_tb else None
for user in eval(config['base']['maintainer']):
send_msg(
user,
config['template']['url'],
exc_type_msg,
str(exc_value) if exc_value else None,
*exc_tb
) if exc_type_msg or exc_value or exc_tb else None
示例13: traceback_get_exception
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_tb [as 别名]
def traceback_get_exception(num = -1):
# build error message
exception_string = ''.join(traceback.format_exception_only(sys.exc_type, hasattr(sys, 'exc_value') and sys.exc_value or 'Unknown'))
# extract error location from traceback
if hasattr(sys, 'exc_traceback'):
(filename, line_number, function_name, text) = traceback.extract_tb(sys.exc_traceback)[num]
else:
(filename, line_number, function_name, text) = ('-', '-', '-', '-')
error = {
'message': exception_string,
'location': {
'filename': filename,
'line_number': line_number,
'function_name': function_name,
'text': text,
}
}
return error
示例14: import_symbol
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_tb [as 别名]
def import_symbol(import_path, setting_name):
"""
Import a class or function by name.
"""
mod_name, class_name = import_path.rsplit('.', 1)
# import module
try:
mod = import_module(mod_name)
cls = getattr(mod, class_name)
except ImportError as e:
__, __, exc_traceback = sys.exc_info()
frames = traceback.extract_tb(exc_traceback)
if len(frames) > 1 and any('importlib' not in f[0] for f in frames[1:]):
raise # import error is a level deeper.
raise ImproperlyConfigured("{0} does not point to an existing class: {1}".format(setting_name, import_path))
except AttributeError:
raise ImproperlyConfigured("{0} does not point to an existing class: {1}".format(setting_name, import_path))
return cls
示例15: check_errors
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_tb [as 别名]
def check_errors(fn):
def wrapper(*args, **kwargs):
global _exception
try:
fn(*args, **kwargs)
except Exception:
_exception = sys.exc_info()
et, ev, tb = _exception
if getattr(ev, 'filename', None) is None:
# get the filename from the last item in the stack
filename = traceback.extract_tb(tb)[-1][0]
else:
filename = ev.filename
if filename not in _error_files:
_error_files.append(filename)
raise
return wrapper