本文整理汇总了Python中traceback.print_tb方法的典型用法代码示例。如果您正苦于以下问题:Python traceback.print_tb方法的具体用法?Python traceback.print_tb怎么用?Python traceback.print_tb使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类traceback
的用法示例。
在下文中一共展示了traceback.print_tb方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: excepthook
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import print_tb [as 别名]
def excepthook(excType, excValue, tracebackobj):
"""
Global function to catch unhandled exceptions.
@param excType exception type
@param excValue exception value
@param tracebackobj traceback object
"""
separator = u'-' * 80
logFile = os.path.join(tempfile.gettempdir(), "error.log")
notice = """An unhandled exception occurred. Please report the problem.\n"""
notice += """A log has been written to "{}".\n\nError information:""".format(logFile)
timeString = time.strftime("%Y-%m-%d, %H:%M:%S")
tbinfofile = cStringIO.StringIO()
traceback.print_tb(tracebackobj, None, tbinfofile)
tbinfofile.seek(0)
tbinfo = tbinfofile.read()
tbinfo = tbinfo.decode('utf-8')
try:
excValueStr = str(excValue).decode('utf-8')
except UnicodeEncodeError, e:
excValueStr = unicode(excValue)
示例2: on_command_error
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import print_tb [as 别名]
def on_command_error(self, ctx, exception):
self.stats.increment("RPGBot.errors", tags=["RPGBot:errors"], host="scw-8112e8")
logging.info(f"Exception in {ctx.command} {ctx.guild}:{ctx.channel} {exception}")
exception = getattr(exception, "original", exception)
traceback.print_tb(exception.__traceback__)
print(exception)
try:
if isinstance(exception, commands.MissingRequiredArgument):
await ctx.send(f"```{exception}```")
elif isinstance(exception, TimeoutError):
await ctx.send(await _(ctx, "This operation ran out of time! Please try again"))
elif isinstance(exception, discord.Forbidden):
await ctx.send(await _(ctx, "Error: This command requires the bot to have permission to send links."))
else:
await ctx.send(f"`{exception} If this is unexpected, please report this to the bot creator`")
except discord.Forbidden:
pass
示例3: failed
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import print_tb [as 别名]
def failed(self):
# check, if the reason was a ConfigureDryRunError or a
# ConfigureCacheError and if yes, reraise the exception
exc_type = self.exc_info()[0]
if issubclass(exc_type, SConfError):
raise
elif issubclass(exc_type, SCons.Errors.BuildError):
# we ignore Build Errors (occurs, when a test doesn't pass)
# Clear the exception to prevent the contained traceback
# to build a reference cycle.
self.exc_clear()
else:
self.display('Caught exception while building "%s":\n' %
self.targets[0])
try:
excepthook = sys.excepthook
except AttributeError:
# Earlier versions of Python don't have sys.excepthook...
def excepthook(type, value, tb):
traceback.print_tb(tb)
print type, value
excepthook(*self.exc_info())
return SCons.Taskmaster.Task.failed(self)
示例4: handle_error
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import print_tb [as 别名]
def handle_error(self, wrapper, exception, traceback_):
print >> sys.stderr
print >> sys.stderr, "---- location:"
traceback.print_stack()
print >> sys.stderr, "---- error:"
traceback.print_tb(traceback_)
try:
stack = wrapper.stack_where_defined
except AttributeError:
print >> sys.stderr, "??:??: %s / %r" % (wrapper, exception)
else:
stack = list(stack)
stack.reverse()
for (filename, line_number, function_name, text) in stack:
file_dir = os.path.dirname(os.path.abspath(filename))
if file_dir.startswith(this_script_dir):
print >> sys.stderr, "%s:%i: %r" % (os.path.join("..", "bindings", "python", os.path.basename(filename)),
line_number, exception)
break
return True
示例5: _to_run_forever
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import print_tb [as 别名]
def _to_run_forever(self):
"""
Method called infinitely, in loop. Specified from the parent version. Fetch from database queue and call a process function on it.
:return: Nothing
"""
# Trying to fetch from queue (from parameters)
fetched_id, fetched_dict = self.fetch_from_queue()
# If there is nothing fetched
if not fetched_id:
# Nothing to do
time.sleep(0.1)
else :
try:
self.process_fetched_data(fetched_id, fetched_dict)
except Exception as e:
self.logger.error(f"Error in database worker (DB adder, db Request or FeatureExtractor or ... ) : {e}")
self.logger.error(traceback.print_tb(e.__traceback__))
示例6: handle_error
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import print_tb [as 别名]
def handle_error(self):
global server_missing_logged
global rtl_tcp_connected
rtl_tcp_connected=False
exc_type, exc_value, exc_traceback = sys.exc_info()
self.ok=False
server_is_missing=hasattr(exc_value,"errno") and exc_value.errno==111
if (not server_is_missing) or (not server_missing_logged):
log.error("with rtl_tcp host connection: "+str(exc_value))
#traceback.print_tb(exc_traceback)
server_missing_logged|=server_is_missing
try:
self.close()
except:
pass
thread.start_new_thread(rtl_tcp_asyncore_reset, (2,))
示例7: failed
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import print_tb [as 别名]
def failed(self):
# check, if the reason was a ConfigureDryRunError or a
# ConfigureCacheError and if yes, reraise the exception
exc_type = self.exc_info()[0]
if issubclass(exc_type, SConfError):
raise
elif issubclass(exc_type, SCons.Errors.BuildError):
# we ignore Build Errors (occurs, when a test doesn't pass)
# Clear the exception to prevent the contained traceback
# to build a reference cycle.
self.exc_clear()
else:
self.display('Caught exception while building "%s":\n' %
self.targets[0])
try:
excepthook = sys.excepthook
except AttributeError:
# Earlier versions of Python don't have sys.excepthook...
def excepthook(type, value, tb):
traceback.print_tb(tb)
print(type, value)
excepthook(*self.exc_info())
return SCons.Taskmaster.Task.failed(self)
示例8: test_with_templates
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import print_tb [as 别名]
def test_with_templates(cf_path):
with open(cf_path) as cf_script:
cf_template = convert_json_or_yaml_to_dict(cf_script.read())
config = Config(project_name=cf_path, service_name=cf_path, stack_name=cf_path, rules=DEFAULT_RULES.keys())
# Scan result
cfmodel = pycfmodel.parse(cf_template).resolve()
rules = [DEFAULT_RULES.get(rule)(config) for rule in config.rules]
processor = RuleProcessor(*rules)
result = processor.process_cf_template(cfmodel, config)
# Use this to print the stack if there'IAMManagedPolicyWildcardActionRule an error
if len(result.exceptions):
print(cf_path)
traceback.print_tb(result.exceptions[0].__traceback__)
assert len(result.exceptions) == 0
示例9: analyze_nodes
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import print_tb [as 别名]
def analyze_nodes(self, address, port):
found_nodes = []
async with self.semaphore:
full_host = f'http://{address}:{port}'
self.logger.info(f'[+] Scanning host at {full_host}')
try:
async with aiohttp.ClientSession(loop=asyncio.get_event_loop(), timeout=self.timeout) as client:
ros_master_client = ServerProxy(full_host, client=client)
code, msg, val = await ros_master_client.getSystemState('')
if code == 1:
nodes = list(map(lambda x: x[0], map(lambda x: x[1], reduce(lambda x, y: x + y, val))))
for node in nodes:
if node in self.rosin_nodes:
found_nodes.append(node)
if len(found_nodes) > 0:
ros_host = ROSHost(address, port)
ros_host.nodes = found_nodes
self.hosts.append(ros_host)
except ClientConnectorError:
self.logger.debug(f'[-] Unable to connect to host {address}')
except Exception as e:
ex, msg, tb = sys.exc_info()
traceback.print_tb(tb)
self.logger.debug(f'[-] Connection error on host {address}')
示例10: _run_batches_from_queue
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import print_tb [as 别名]
def _run_batches_from_queue(self):
skip_batch = False
while not self._stop_flag:
future = self._prefetch_queue.get(block=True)
if future is None:
self._prefetch_queue.task_done()
self._batch_queue.put(None)
break
try:
batch = future.result()
except SkipBatchException:
skip_batch = True
except Exception: # pylint: disable=broad-except
exc = future.exception()
print("Exception in a thread:", exc)
traceback.print_tb(exc.__traceback__)
finally:
if not skip_batch:
self._batch_queue.put(batch, block=True)
skip_batch = False
self._prefetch_queue.task_done()
示例11: createDrawingCoords
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import print_tb [as 别名]
def createDrawingCoords(self):
if self.drawingCoords is None:
self.drawingCoords = []
tokens = self._tokenize_path(self.points)
x = float(next(tokens))
y = float(next(tokens))
self.drawingCoords.append(Coordinate.fromCoords(x, y, True))
while True:
try:
self.drawingCoords.append(Coordinate.fromCoords(float(next(tokens)), float(next(tokens)), False))
except StopIteration:
break
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
print("test1 main thread exception : %s" % exc_type)
traceback.print_tb(exc_traceback, limit=2, file=sys.stdout)
return self.drawingCoords
示例12: verify
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import print_tb [as 别名]
def verify(input_dict, reference_dict):
"""
Returns: modified_input, success, list_of_errors
where:
- modified_input is the input populated with default values where applicable
- success is a boolean true if there were no problems and false otherwise
- list_of_errors is as in verify_helper
"""
input_dict, messages = verify_helper("", input_dict, {'type':'dict','values':reference_dict})
try:
if len(messages)>0:
raise Exception("Failed to verify: {}".format(messages))
else:
return input_dict
except Exception:
exc_type, exc_value, exc_traceback = sys.exc_info()
print("Exception: {} {}".format(error, traceback.format_exc()))
traceback.print_tb(exc_traceback)
raise Exception(error)
示例13: verify
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import print_tb [as 别名]
def verify(input_dict, reference_dict):
"""
Returns: modified_input, success, list_of_errors
where:
- modified_input is the input populated with default values where applicable
- success is a boolean true if there were no problems and false otherwise
- list_of_errors is as in verify_helper
"""
input_dict, messages = verify_helper("", input_dict, {'type':'dict','values':reference_dict})
try:
if len(messages)>0:
raise Exception("Failed to verify: {}".format(messages))
else:
return input_dict
except Exception as error:
exc_type, exc_value, exc_traceback = sys.exc_info()
print("Exception: {} {}".format(error, traceback.format_exc()))
traceback.print_tb(exc_traceback)
raise Exception(error.args[0])
示例14: initExp
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import print_tb [as 别名]
def initExp(self, exp_uid, args_json):
try:
self.helper.ensure_indices(self.app_id,self.butler.db, self.butler.ell)
args_dict = self.helper.convert_json(args_json)
args_dict = verifier.verify(args_dict, self.reference_dict['initExp']['args'])
args_dict['exp_uid'] = exp_uid # to get doc from db
args_dict['start_date'] = utils.datetime2str(utils.datetimeNow())
self.butler.admin.set(uid=exp_uid,value={'exp_uid': exp_uid, 'app_id':self.app_id, 'start_date':str(utils.datetimeNow())})
self.butler.experiment.set(value={'exp_uid': exp_uid})
args_dict['args'] = self.init_app(exp_uid, args_dict['args']['alg_list'], args_dict['args'])
args_dict['git_hash'] = git_hash
self.butler.experiment.set_many(key_value_dict=args_dict)
return '{}', True, ''
except Exception, error:
exc_type, exc_value, exc_traceback = sys.exc_info()
full_error = str(traceback.format_exc())+'\n'+str(error)
utils.debug_print("initExp Exception: " + full_error, color='red')
log_entry = { 'exp_uid':exp_uid,'task':'initExp','error':full_error,'timestamp':utils.datetimeNow(),'args_json':args_json }
self.butler.ell.log( self.app_id+':APP-EXCEPTION', log_entry )
traceback.print_tb(exc_traceback)
return '{}', False, str(error)
示例15: excepthook
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import print_tb [as 别名]
def excepthook(self, exctype, value, tb):
"""
Parameters
----------
exctype :
value :
tb :
Returns
-------
"""
traceback.print_tb(tb)
print("{0}: {1}".format(exctype, value))
self.trigger.kill_event.set()
self.trigger.join()