本文整理汇总了Python中traceback.format_exception方法的典型用法代码示例。如果您正苦于以下问题:Python traceback.format_exception方法的具体用法?Python traceback.format_exception怎么用?Python traceback.format_exception使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类traceback
的用法示例。
在下文中一共展示了traceback.format_exception方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: addFailure
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exception [as 别名]
def addFailure(self, test, err, capt=None):
"""Add failure output to Xunit report.
"""
exc_type, exc_val, tb = err
tb = ''.join(traceback.format_exception(
exc_type,
exc_val if isinstance(exc_val, exc_type) else exc_type(exc_val),
tb
))
name = id_split(test.id())
group = self.report_data[name[0]]
self.stats['failures'] += 1
group.stats['failures'] += 1
group.tests.append({
'name': name[-1],
'failed': True,
'errtype': nice_classname(err[0]),
'message': exc_message(err),
'tb': tb,
})
示例2: handle_exception
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exception [as 别名]
def handle_exception(exc_type, exc_value, exc_traceback):
""" handle all exceptions """
# KeyboardInterrupt is a special case.
# We don't raise the error dialog when it occurs.
if issubclass(exc_type, KeyboardInterrupt):
return
Logger.error("Unhandled Exception:")
Logger.error("".join(traceback.format_exception(exc_type, exc_value, exc_traceback)))
try:
App.get_running_app().stop()
except Exception:
pass
# we want to handle TERM signal cleanly (sent by sv down)
示例3: save
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exception [as 别名]
def save(ops, cnt):
f = open("%d.ops" % cnt, "w")
tbLines = traceback.format_exception(*sys.exc_info())
for l in tbLines:
# traceback lines contain embedded newlines so it gets a bit
# complex escaping every line with # and keeping the formatting
# correct.
f.write("#" + l.rstrip().replace("\n", "\n#") + "\n")
f.write(ops.save())
f.close()
f = open("%d.trelby" % cnt, "w")
f.write(ops.sp.save())
f.close()
示例4: handle_exception
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exception [as 别名]
def handle_exception(title="Exception raised!"):
'''Displays a traceback in a window if an exception is raised.
If the user clicks on "abort", sys.exit() is called and the
program ends. If the user clicks on "ignore", the program
resumes its execution.
:param title: the window title
.. image:: ../docs/images/handle_exception.png
'''
try:
message = "\n".join(traceback.format_exception(sys.exc_info()[0],
sys.exc_info()[1] , sys.exc_info()[2]))
except AttributeError:
return "No exception was raised"
get_abort(title=title, message=message)
示例5: write_error
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exception [as 别名]
def write_error(self, status_code, **kwargs):
"""复写这个方法来实现自定义错误页.
``write_error`` 可能调用 `write`, `render`, `set_header`,等
来产生一般的输出.
如果错误是由未捕获的异常造成的(包括HTTPError), 三个一组的
``exc_info`` 将变成可用的通过 ``kwargs["exc_info"]``.
注意这个异常可能不是"当前(current)" 目的或方法的异常就像
``sys.exc_info()`` 或 ``traceback.format_exc``.
"""
if self.settings.get("serve_traceback") and "exc_info" in kwargs:
# in debug mode, try to send a traceback
self.set_header('Content-Type', 'text/plain')
for line in traceback.format_exception(*kwargs["exc_info"]):
self.write(line)
self.finish()
else:
self.finish("<html><title>%(code)d: %(message)s</title>"
"<body>%(code)d: %(message)s</body></html>" % {
"code": status_code,
"message": self._reason,
})
示例6: getrepr
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exception [as 别名]
def getrepr(self, showlocals=False, style="long",
abspath=False, tbfilter=True, funcargs=False):
""" return str()able representation of this exception info.
showlocals: show locals per traceback entry
style: long|short|no|native traceback style
tbfilter: hide entries (where __tracebackhide__ is true)
in case of style==native, tbfilter and showlocals is ignored.
"""
if style == 'native':
return ReprExceptionInfo(ReprTracebackNative(
traceback.format_exception(
self.type,
self.value,
self.traceback[0]._rawentry,
)), self._getreprcrash())
fmt = FormattedExcinfo(
showlocals=showlocals, style=style,
abspath=abspath, tbfilter=tbfilter, funcargs=funcargs)
return fmt.repr_excinfo(self)
示例7: _timed_block_factory
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exception [as 别名]
def _timed_block_factory(opening_text):
from timeit import default_timer as timer
from traceback import format_exception
from sys import exc_info
def _timed_block_decorator(s, before=None, after=None):
display(opening_text, s)
def wrapper(func):
if callable(before):
before()
time = timer()
try:
func()
except AssertionError as e:
display('FAILED', str(e))
except Exception:
fail('Unexpected exception raised')
tb_str = ''.join(format_exception(*exc_info()))
display('ERROR', tb_str)
display('COMPLETEDIN', '{:.2f}'.format((timer() - time) * 1000))
if callable(after):
after()
return wrapper
return _timed_block_decorator
示例8: _gather_crash_info
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exception [as 别名]
def _gather_crash_info(self):
self._crash_info += [
("Exception", ''.join(traceback.format_exception(*self._exc))),
]
super()._gather_crash_info()
if self._chk_log.isChecked():
self._crash_info += [
("Commandline args", ' '.join(sys.argv[1:])),
("Open Pages", '\n\n'.join('\n'.join(e) for e in self._pages)),
("Command history", '\n'.join(self._cmdhist)),
("Objects", self._qobjects),
]
try:
text = "Log output was disabled."
if log.ram_handler is not None:
text = log.ram_handler.dump_log()
self._crash_info.append(("Debug log", text))
except Exception:
self._crash_info.append(("Debug log", traceback.format_exc()))
示例9: import_class
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exception [as 别名]
def import_class(import_str):
"""
Returns a class from a string that specifies a module and/or class
:param import_str: import path, e.g. 'httplib.HTTPConnection'
:returns imported object
:raises: ImportedError if the class does not exist or the path is invalid
"""
(mod_str, separator, class_str) = import_str.rpartition('.')
try:
__import__(mod_str)
return getattr(sys.modules[mod_str], class_str)
except (ValueError, AttributeError):
raise ImportError('Class %s cannot be found (%)' %
(class_str,
traceback.format_exception(*sys.exc_info())))
示例10: emit
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exception [as 别名]
def emit(self, record: logging.LogRecord):
"""Print the log record formatted as JSON to stdout."""
created = datetime.datetime.fromtimestamp(record.created, timezone)
obj = {
"level": record.levelname.lower(),
"msg": record.msg % record.args,
"source": "%s:%d" % (record.filename, record.lineno),
"time": format_datetime(created),
"thread": reduce_thread_id(record.thread),
}
if record.exc_info is not None:
obj["error"] = traceback.format_exception(*record.exc_info)[1:]
try:
obj["context"] = self.local.context
except AttributeError:
pass
json.dump(obj, sys.stdout, sort_keys=True)
sys.stdout.write("\n")
sys.stdout.flush()
示例11: task
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exception [as 别名]
def task(*d_args, **d_kwargs):
# behaves like @task, but emails about exceptions.
def real_decorator(f):
@shared_task(*d_args, **d_kwargs)
@wraps(f)
def wrapper(*f_args, **f_kwargs):
# try the task; email any exceptions we get
try:
res = f(*f_args, **f_kwargs)
except Exception as e:
# email admins and re-raise
exc_type, exc_value, exc_traceback = sys.exc_info()
subject = 'task failure in %s.%s' % (f.__module__, f.__name__)
msg = 'The task %s.%s failed:\n\n%s' % (f.__module__, f.__name__,
'\n'.join(traceback.format_exception(exc_type, exc_value, exc_traceback)))
mail_admins(subject=subject, message=msg, fail_silently=True)
raise
return res
return wrapper
return real_decorator
示例12: periodic_task
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exception [as 别名]
def periodic_task(*d_args, **d_kwargs):
# behaves like @periodic_task, but emails about exceptions.
def real_decorator(f):
@celery_periodic_task(*d_args, **d_kwargs)
@wraps(f)
def wrapper(*f_args, **f_kwargs):
# try the task; email any exceptions we get
try:
res = f(*f_args, **f_kwargs)
except Exception as e:
# email admins and re-raise
exc_type, exc_value, exc_traceback = sys.exc_info()
subject = 'task failure in %s.%s' % (f.__module__, f.__name__)
msg = 'The periodic task %s.%s failed:\n\n%s' % (f.__module__, f.__name__,
'\n'.join(traceback.format_exception(exc_type, exc_value, exc_traceback)))
mail_admins(subject=subject, message=msg, fail_silently=True)
raise
return res
return wrapper
return real_decorator
示例13: handle_alias_exception
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exception [as 别名]
def handle_alias_exception(ctx, err):
e = err.original
location = ''
if isinstance(e, AvraeException):
return await ctx.channel.send(err)
elif isinstance(e, draconic.InvalidExpression):
try:
location = f" on line {e.node.lineno}, col {e.node.col_offset}"
except AttributeError:
pass
elif isinstance(e, draconic.DraconicSyntaxError):
location = f" on line {e.lineno}, col {e.offset}"
tb = ''.join(traceback.format_exception(type(e), e, e.__traceback__, limit=0, chain=False))
try:
await ctx.author.send(
f"```py\n"
f"Error{location} when parsing expression {err.expression}:\n"
f"{tb}\n"
f"```")
except:
pass
return await ctx.channel.send(err)
示例14: handle_exception
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exception [as 别名]
def handle_exception(exc_type, exc_value, exc_traceback):
"""Log unhandled exceptions."""
message = "".join(traceback.format_exception(exc_type, exc_value, exc_traceback))
logger.error("Unhandled exception in executor: {}".format(message))
loop.run_until_complete(
asyncio.gather(
*logging_future_list,
manager_commands.send_manager_command(
ExecutorProtocol.UPDATE,
extra_fields={
ExecutorProtocol.UPDATE_CHANGESET: {
"process_error": ["Unhandled exception in executor."],
"status": DATA_META["STATUS_ERROR"],
}
},
),
manager_commands.send_manager_command(
ExecutorProtocol.ABORT, expect_reply=False
),
)
)
示例15: _retrial
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exception [as 别名]
def _retrial(func, *args, **kwargs):
"""
Retrial method
"""
delay = 0
while True:
try:
return func(*args, **kwargs)
except DataIdentifierNotFound as error:
logging.warning(error)
return 1
except DatabaseException as error:
logging.error(error)
if exp(delay) > 600:
logging.error('Cannot execute %s after %i attempt. Failing the job.' % (func.__name__, delay))
raise
else:
logging.error('Failure to execute %s. Retrial will be done in %d seconds ' % (func.__name__, exp(delay)))
time.sleep(exp(delay))
delay += 1
except Exception:
exc_type, exc_value, exc_traceback = exc_info()
logging.critical(''.join(format_exception(exc_type, exc_value, exc_traceback)).strip())
raise