Python traceback.print_tb() Examples
The following are 30
code examples of traceback.print_tb().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
traceback
, or try the search function
.
Example #1
Source File: database_worker.py From douglas-quaid with GNU General Public License v3.0 | 7 votes |
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__))
Example #2
Source File: excepthook.py From pandas-qt with MIT License | 7 votes |
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)
Example #3
Source File: utils.py From aws-greengrass-mini-fulfillment with Apache License 2.0 | 6 votes |
def mqtt_connect(mqtt_client, core_info): connected = False # try connecting to all connectivity info objects in the list for connectivity_info in core_info.connectivityInfoList: core_host = connectivity_info.host core_port = connectivity_info.port logging.info("Connecting to Core at {0}:{1}".format( core_host, core_port)) mqtt_client.configureEndpoint(core_host, core_port) try: mqtt_client.connect() connected = True break except socket.error as se: print("SE:{0}".format(se)) except operationTimeoutException as te: print("operationTimeoutException:{0}".format(te.message)) traceback.print_tb(te, limit=25) except Exception as e: print("Exception caught:{0}".format(e.message)) return connected
Example #4
Source File: SConf.py From web2board with GNU Lesser General Public License v3.0 | 6 votes |
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)
Example #5
Source File: ns3modulegen.py From IEEE-802.11ah-ns-3 with GNU General Public License v2.0 | 6 votes |
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
Example #6
Source File: ns3modulegen.py From ntu-dsi-dcn with GNU General Public License v2.0 | 6 votes |
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
Example #7
Source File: rtl_mus.py From rtl_mus with GNU General Public License v3.0 | 6 votes |
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,))
Example #8
Source File: SConf.py From pivy with ISC License | 6 votes |
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)
Example #9
Source File: ns3modulegen.py From ns3-load-balance with GNU General Public License v2.0 | 6 votes |
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
Example #10
Source File: test_main.py From cfripper with Apache License 2.0 | 6 votes |
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
Example #11
Source File: scanner.py From aztarna with GNU General Public License v3.0 | 6 votes |
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}')
Example #12
Source File: pipeline.py From batchflow with Apache License 2.0 | 6 votes |
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()
Example #13
Source File: svg.py From vPiP with Apache License 2.0 | 6 votes |
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
Example #14
Source File: svg.py From vPiP with Apache License 2.0 | 6 votes |
def createDrawingCoords(self): if self.drawingCoords is None: self.drawingCoords = [] tokens = self._tokenize_path(self.points) x = float(next(tokens)) y = float(next(tokens)) startX, startY = x, y 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) self.drawingCoords.append(Coordinate.fromCoords(startX, startY, False)) return self.drawingCoords
Example #15
Source File: ns3modulegen.py From ns3-rdma with GNU General Public License v2.0 | 6 votes |
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
Example #16
Source File: verifier.py From NEXT with Apache License 2.0 | 6 votes |
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)
Example #17
Source File: verifier.py From NEXT with Apache License 2.0 | 6 votes |
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])
Example #18
Source File: App.py From NEXT with Apache License 2.0 | 6 votes |
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)
Example #19
Source File: __init__.py From stytra with GNU General Public License v3.0 | 6 votes |
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()
Example #20
Source File: tracking_experiments.py From stytra with GNU General Public License v3.0 | 6 votes |
def excepthook(self, exctype, value, tb): """ Parameters ---------- exctype : value : tb : Returns ------- """ traceback.print_tb(tb) print("{0}: {1}".format(exctype, value)) self.camera.kill_event.set() self.camera.join()
Example #21
Source File: ns3modulegen.py From royal-chaos with MIT License | 6 votes |
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
Example #22
Source File: gui17.py From pgu with GNU Lesser General Public License v2.1 | 6 votes |
def lkey(_event): e = _event if e.key == K_RETURN: _stdout = sys.stdout s = sys.stdout = StringStream() val = line.value line.value = '' line.focus() print('>>> '+val) try: code = compile(val,'<string>','single') eval(code,globals(),_locals) except Exception: e_type,e_value,e_traceback = sys.exc_info() print('Traceback (most recent call last):') traceback.print_tb(e_traceback,None,s) print(e_type,e_value) sys.stdout = _stdout
Example #23
Source File: gltf2_blender_export.py From glTF-Blender-IO with Apache License 2.0 | 6 votes |
def __write_file(json, buffer, export_settings): try: gltf2_io_export.save_gltf( json, export_settings, gltf2_blender_json.BlenderJSONEncoder, buffer) except AssertionError as e: _, _, tb = sys.exc_info() traceback.print_tb(tb) # Fixed format tb_info = traceback.extract_tb(tb) for tbi in tb_info: filename, line, func, text = tbi print_console('ERROR', 'An error occurred on line {} in statement {}'.format(line, text)) print_console('ERROR', str(e)) raise e
Example #24
Source File: except_hook.py From node-launcher with MIT License | 6 votes |
def except_hook(exception_type, exception_value, traceback_object): notice = f'''Wild bug appears! <br> Please copy this text and <a href="https://github.com/lightning-power-users/node-launcher/issues/new">open an issue on GitHub</a>.<br> Node Launcher version {NODE_LAUNCHER_RELEASE}<br><br> Error information:''' traceback_io = StringIO() traceback.print_tb(traceback_object, None, traceback_io) traceback_io.seek(0) traceback_info = traceback_io.read() sections = [ notice, str(exception_type), str(exception_value), traceback_info ] msg = '<br>'.join(sections) error_message = QMessageBox() error_message.setTextFormat(Qt.RichText) error_message.setTextInteractionFlags(Qt.TextSelectableByMouse) error_message.setFixedWidth(800) error_message.setText(msg) error_message.exec_() sys.exit(1)
Example #25
Source File: utils.py From aws-greengrass-mini-fulfillment with Apache License 2.0 | 6 votes |
def mqtt_connect(mqtt_client, core_info): connected = False # try connecting to all connectivity info objects in the list for connectivity_info in core_info.connectivityInfoList: core_host = connectivity_info.host core_port = connectivity_info.port logging.info("Connecting to Core at {0}:{1}".format( core_host, core_port)) mqtt_client.configureEndpoint(core_host, core_port) try: mqtt_client.connect() connected = True break except socket.error as se: print("SE:{0}".format(se)) except operationTimeoutException as te: print("operationTimeoutException:{0}".format(te.message)) traceback.print_tb(te, limit=25) except Exception as e: print("Exception caught:{0}".format(e.message)) return connected
Example #26
Source File: ns3modulegen.py From 802.11ah-ns3 with GNU General Public License v2.0 | 6 votes |
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
Example #27
Source File: util.py From skutil with BSD 3-Clause "New" or "Revised" License | 5 votes |
def is_integer(x): """Determine whether some object ``x`` is an integer type (int, long, etc). Parameters ---------- x : object The item to assess Returns ------- bool True if ``x`` is an integer type """ try: python_major_version = sys.version_info.major assert(python_major_version == 2 or python_major_version == 3) if python_major_version == 2: return (not isinstance(x, (bool, np.bool))) and \ isinstance(x, (numbers.Integral, int, long, np.int, np.long)) elif python_major_version == 3: return (not isinstance(x, (bool, np.bool))) and \ isinstance(x, (numbers.Integral, int, np.int, np.long)) except AssertionError: _, _, tb = sys.exc_info() traceback.print_tb(tb) # Fixed format tb_info = traceback.extract_tb(tb) filename, line, func, text = tb_info[-1] print('An error occurred on line {} in statement {}'.format(line, text)) exit(1) return _is_integer(x)
Example #28
Source File: test_dash_validate.py From pySHACL with Apache License 2.0 | 5 votes |
def test_dash_validate_all_sparql_rules(target_file, shacl_file): try: val, _, v_text = pyshacl.validate( target_file, shacl_graph=shacl_file, advanced=True, inference='rdfs', check_dash_result=True, debug=True, meta_shacl=False) except (NotImplementedError, ReportableRuntimeError) as e: import traceback print(e) traceback.print_tb(e.__traceback__) val = False v_text = "" assert val print(v_text) return True # Get all triple-rules tests.
Example #29
Source File: test_dash_validate.py From pySHACL with Apache License 2.0 | 5 votes |
def test_dash_validate_all_triple_rules(target_file, shacl_file): test_name = shacl_file or target_file try: val, _, v_text = pyshacl.validate( target_file, shacl_graph=shacl_file, advanced=True, inference='rdfs', check_dash_result=True, debug=True, meta_shacl=False) except NotImplementedError as ne: for ani in ALLOWABLE_NOT_IMPLEMENTED: if test_name.endswith(ani): v_text = "Skipping not implemented feature in test: {}".format(test_name) print(v_text) val = True break else: print(ne) val = False v_text = "" except ReportableRuntimeError as e: import traceback print(e) traceback.print_tb(e.__traceback__) val = False v_text = "" try: assert val except AssertionError as ae: for af in ALLOWABLE_FAILURES: if test_name.endswith(af): v_text = "Allowing failure in test: {}".format(test_name) print(v_text) break else: raise ae print(v_text) return True # Get all triple-rules tests.
Example #30
Source File: App.py From NEXT with Apache License 2.0 | 5 votes |
def processAnswer(self, exp_uid, args_json): try: args_dict = self.helper.convert_json(args_json) args_dict = verifier.verify(args_dict, self.reference_dict['processAnswer']['args']) # Update timing info in query query = self.butler.queries.get(uid=args_dict['args']['query_uid']) timestamp_answer_received = args_dict['args'].get('timestamp_answer_received', None) delta_datetime = utils.str2datetime(timestamp_answer_received) - \ utils.str2datetime(query['timestamp_query_generated']) round_trip_time = delta_datetime.total_seconds() response_time = float(args_dict['args'].get('response_time',0.)) query_update = self.call_app_fn(query['alg_label'], query['alg_id'], 'processAnswer', args_dict) query_update.update({'response_time':response_time, 'network_delay':round_trip_time - response_time, 'timestamp_answer_received': timestamp_answer_received }) self.butler.queries.set_many(uid=args_dict['args']['query_uid'],key_value_dict=query_update) return json.dumps({'args': {}, 'meta': {'log_entry_durations':self.log_entry_durations}}), 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("processAnswer Exception: " + full_error, color='red') log_entry = { 'exp_uid':exp_uid,'task':'processAnswer','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) raise Exception(error)