Python traceback.print_exc() Examples
The following are 30
code examples of traceback.print_exc().
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: zmirror.py From zmirror with MIT License | 7 votes |
def cron_task_host(): """定时任务宿主, 每分钟检查一次列表, 运行时间到了的定时任务""" while True: # 当全局开关关闭时, 自动退出线程 if not enable_cron_tasks: if threading.current_thread() != threading.main_thread(): exit() else: return sleep(60) try: task_scheduler.run() except: # coverage: exclude errprint('ErrorDuringExecutingCronTasks') traceback.print_exc()
Example #2
Source File: concurrency.py From dataflow with Apache License 2.0 | 6 votes |
def run(self): nr_end = 0 try: while True: task_id, data = self.data_queue.get() if task_id == DIE: self.result_queue.put((task_id, data)) nr_end += 1 if nr_end == self.nr_producer: return else: self.ordered_container.put(task_id, data) while self.ordered_container.has_next(): self.result_queue.put(self.ordered_container.get()) except Exception as e: import traceback traceback.print_exc() raise e
Example #3
Source File: parser_mod.py From Turku-neural-parser-pipeline with Apache License 2.0 | 6 votes |
def launch(args,q_in,q_out): try: parser=parser_lib.NetworkParserWrapper(args.model,args.parser_dir) except: traceback.print_exc() sys.stderr.flush() while True: jobid,txt=q_in.get() if jobid=="FINAL": q_out.put((jobid,txt)) return try: conllu=parser.parse_text(txt) if args.process_morpho == True: conllu=process_batch(conllu, detransfer=True) q_out.put((jobid,conllu)) except: traceback.print_exc() sys.stderr.flush()
Example #4
Source File: test_exception.py From zmirror with MIT License | 6 votes |
def test_import_error_custom_func(self): restore_config_file() try: shutil.copy(zmirror_file('config_default.py'), zmirror_file('config.py')) try: self.reload_zmirror({"custom_text_rewriter_enable": True, "enable_custom_access_cookie_generate_and_verify": True, "identity_verify_required": True, }) except: import traceback traceback.print_exc() os.remove(zmirror_file('config.py')) except: pass copy_default_config_file()
Example #5
Source File: test_format.py From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_format_docstrings(): """ Test if docstrings are well formatted. """ # Disabled for now return True try: verify_format_docstrings() except SkipTest as e: import traceback traceback.print_exc(e) raise AssertionError( "Some file raised SkipTest on import, and inadvertently" " canceled the documentation testing." )
Example #6
Source File: mbusb_gui.py From multibootusb with GNU General Public License v2.0 | 6 votes |
def install_syslinux(self): try: try: self.install_syslinux_impl() finally: config.process_exist = None self.ui_enable_controls() except (KeyboardInterrupt, SystemExit): raise except: uninstall_distro.do_uninstall_distro( config.distro, iso_basename(config.image_path)) o = io.StringIO() traceback.print_exc(None, o) QtWidgets.QMessageBox.information( self, 'install_syslinux() failed', o.getvalue()) log("install_syslinux() failed.") log(o.getvalue())
Example #7
Source File: cookiejar_tp.py From sawtooth-cookiejar with Apache License 2.0 | 6 votes |
def main(): '''Entry-point function for the cookiejar Transaction Processor.''' try: # Setup logging for this class. logging.basicConfig() logging.getLogger().setLevel(logging.DEBUG) # Register the Transaction Handler and start it. processor = TransactionProcessor(url=DEFAULT_URL) sw_namespace = _hash(FAMILY_NAME.encode('utf-8'))[0:6] handler = CookieJarTransactionHandler(sw_namespace) processor.add_handler(handler) processor.start() except KeyboardInterrupt: pass except SystemExit as err: raise err except BaseException as err: traceback.print_exc(file=sys.stderr) sys.exit(1)
Example #8
Source File: events_client.py From sawtooth-cookiejar with Apache License 2.0 | 6 votes |
def main(): '''Entry point function for the client CLI.''' filters = [events_pb2.EventFilter(key="address", match_string= COOKIEJAR_TP_ADDRESS_PREFIX + ".*", filter_type=events_pb2. EventFilter.REGEX_ANY)] try: # To listen to all events, pass delta_filters=None : #listen_to_events(delta_filters=None) listen_to_events(delta_filters=filters) except KeyboardInterrupt: pass except SystemExit as err: raise err except BaseException as err: traceback.print_exc(file=sys.stderr) sys.exit(1)
Example #9
Source File: events_client.py From sawtooth-cookiejar with Apache License 2.0 | 6 votes |
def main(): '''Entry point function for the client CLI.''' filters = [events_pb2.EventFilter(key="address", match_string= COOKIEJAR_TP_ADDRESS_PREFIX + ".*", filter_type=events_pb2. EventFilter.REGEX_ANY)] try: # To listen to all events, pass delta_filters=None : #listen_to_events(delta_filters=None) listen_to_events(delta_filters=filters) except KeyboardInterrupt: pass except SystemExit as err: raise err except BaseException as err: traceback.print_exc(file=sys.stderr) sys.exit(1)
Example #10
Source File: gitter.py From fishroom with GNU General Public License v3.0 | 6 votes |
def test(): gitter = Gitter( token="", rooms=( "57397795c43b8c60197322b9", "5739b957c43b8c6019732c0b", ), me='' ) def response(msg): print(msg) gitter.send_msg( target=msg.receiver, content=msg.content, sender="fishroom") gitter.send_to_bus = response try: gitter.listen_message_stream(id_blacklist=("master_tuna_twitter", )) except Exception: import traceback traceback.print_exc()
Example #11
Source File: app.py From botbuilder-python with MIT License | 6 votes |
def on_error(context: TurnContext, error: Exception): # This check writes out errors to console log .vs. app insights. # NOTE: In production environment, you should consider logging this to Azure # application insights. print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr) traceback.print_exc() # Send a message to the user await context.send_activity("The bot encountered an error or bug.") await context.send_activity( "To continue to run this bot, please fix the bot source code." ) # Send a trace activity if we're talking to the Bot Framework Emulator if context.activity.channel_id == "emulator": # Create a trace activity that contains the error object trace_activity = Activity( label="TurnError", name="on_turn_error Trace", timestamp=datetime.utcnow(), type=ActivityTypes.trace, value=f"{error}", value_type="https://www.botframework.com/schemas/error", ) # Send a trace activity, which will be displayed in Bot Framework Emulator await context.send_activity(trace_activity)
Example #12
Source File: app.py From botbuilder-python with MIT License | 6 votes |
def on_error(context: TurnContext, error: Exception): # This check writes out errors to console log .vs. app insights. # NOTE: In production environment, you should consider logging this to Azure # application insights. print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr) traceback.print_exc() # Send a message to the user await context.send_activity("The bot encountered an error or bug.") await context.send_activity( "To continue to run this bot, please fix the bot source code." ) # Send a trace activity if we're talking to the Bot Framework Emulator if context.activity.channel_id == "emulator": # Create a trace activity that contains the error object trace_activity = Activity( label="TurnError", name="on_turn_error Trace", timestamp=datetime.utcnow(), type=ActivityTypes.trace, value=f"{error}", value_type="https://www.botframework.com/schemas/error", ) # Send a trace activity, which will be displayed in Bot Framework Emulator await context.send_activity(trace_activity)
Example #13
Source File: app.py From botbuilder-python with MIT License | 6 votes |
def on_error(context: TurnContext, error: Exception): # This check writes out errors to console log .vs. app insights. # NOTE: In production environment, you should consider logging this to Azure # application insights. print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr) traceback.print_exc() # Send a message to the user await context.send_activity("The bot encountered an error or bug.") await context.send_activity( "To continue to run this bot, please fix the bot source code." ) # Send a trace activity if we're talking to the Bot Framework Emulator if context.activity.channel_id == "emulator": # Create a trace activity that contains the error object trace_activity = Activity( label="TurnError", name="on_turn_error Trace", timestamp=datetime.utcnow(), type=ActivityTypes.trace, value=f"{error}", value_type="https://www.botframework.com/schemas/error", ) # Send a trace activity, which will be displayed in Bot Framework Emulator await context.send_activity(trace_activity)
Example #14
Source File: extractor.py From firmanal with MIT License | 6 votes |
def update_database(self, field, value): """ Update a given field in the database. """ ret = True if self.database: try: cur = self.database.cursor() cur.execute("UPDATE image SET " + field + "='" + value + "' WHERE id=%s", (self.tag, )) self.database.commit() except BaseException: ret = False traceback.print_exc() self.database.rollback() finally: if cur: cur.close() return ret
Example #15
Source File: Udp_server.py From rtp_cluster with BSD 2-Clause "Simplified" License | 6 votes |
def handle_read(self, data, address, rtime, delayed = False): if len(data) > 0 and self.uopts.data_callback != None: self.stats[2] += 1 if self.uopts.ploss_in_rate > 0.0 and not delayed: if random() < self.uopts.ploss_in_rate: return if self.uopts.pdelay_in_max > 0.0 and not delayed: pdelay = self.uopts.pdelay_in_max * random() Timeout(self.handle_read, pdelay, 1, data, address, rtime.getOffsetCopy(pdelay), True) return try: self.uopts.data_callback(data, address, self, rtime) except Exception as ex: if isinstance(ex, SystemExit): raise print(datetime.now(), 'Udp_server: unhandled exception when processing incoming data') print('-' * 70) traceback.print_exc(file = sys.stdout) print('-' * 70) sys.stdout.flush()
Example #16
Source File: tools.py From OpenTrader with GNU Lesser General Public License v3.0 | 6 votes |
def set_trace(): """Call pdb.set_trace in the caller's frame. First restore sys.stdout and sys.stderr. Note that the streams are NOT reset to whatever they were before the call once pdb is done! """ import pdb for stream in 'stdout', 'stderr': output = getattr(sys, stream) orig_output = getattr(sys, '__%s__' % stream) if output != orig_output: # Flush the output before entering pdb if hasattr(output, 'getvalue'): orig_output.write(output.getvalue()) orig_output.flush() setattr(sys, stream, orig_output) exc, tb = sys.exc_info()[1:] if tb: if isinstance(exc, AssertionError) and exc.args: # The traceback is not printed yet print_exc() pdb.post_mortem(tb) else: pdb.Pdb().set_trace(sys._getframe().f_back)
Example #17
Source File: services.py From bioservices with GNU General Public License v3.0 | 6 votes |
def post_one(self, query=None, frmt='json', **kargs): self._calls() self.logging.debug("BioServices:: Entering post_one function") if query is None: url = self.url else: url = '%s/%s' % (self.url, query) self.logging.debug(url) try: res = self.session.post(url, **kargs) self.last_response = res res = self._interpret_returned_request(res, frmt) try: return res.decode() except: self.logging.debug("BioServices:: Could not decode the response") return res except Exception as err: traceback.print_exc() return None
Example #18
Source File: cmd2plus.py From OpenTrader with GNU Lesser General Public License v3.0 | 6 votes |
def set_trace(): """Call pdb.set_trace in the caller's frame. First restore sys.stdout and sys.stderr. Note that the streams are NOT reset to whatever they were before the call once pdb is done! """ import pdb for stream in 'stdout', 'stderr': output = getattr(sys, stream) orig_output = getattr(sys, '__%s__' % stream) if output != orig_output: # Flush the output before entering pdb if hasattr(output, 'getvalue'): orig_output.write(output.getvalue()) orig_output.flush() setattr(sys, stream, orig_output) exc, tb = sys.exc_info()[1:] if tb: if isinstance(exc, AssertionError) and exc.args: # The traceback is not printed yet print_exc() pdb.post_mortem(tb) else: pdb.Pdb().set_trace(sys._getframe().f_back)
Example #19
Source File: GXDLMSReader.py From Gurux.DLMS.Python with GNU General Public License v2.0 | 6 votes |
def getReadOut(self): #pylint: disable=unidiomatic-typecheck, broad-except for it in self.client.objects: if type(it) == GXDLMSObject: print("Unknown Interface: " + it.objectType.__str__()) continue if isinstance(it, GXDLMSProfileGeneric): continue self.writeTrace("-------- Reading " + str(it.objectType) + " " + str(it.name) + " " + it.description, TraceLevel.INFO) for pos in (it).getAttributeIndexToRead(True): try: val = self.read(it, pos) self.showValue(pos, val) except Exception as ex: self.writeTrace("Error! Index: " + str(pos) + " " + str(ex), TraceLevel.ERROR) self.writeTrace(str(ex), TraceLevel.ERROR) if not isinstance(ex, (GXDLMSException, TimeoutException)): traceback.print_exc()
Example #20
Source File: socketserver.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
def handle_error(self, request, client_address): """Handle an error gracefully. May be overridden. The default is to print a traceback and continue. """ print('-'*40) print('Exception happened during processing of request from', end=' ') print(client_address) import traceback traceback.print_exc() # XXX But this goes to stderr! print('-'*40)
Example #21
Source File: two_nb.py From weiboanalysis with Apache License 2.0 | 5 votes |
def predict(pWordsPosicity, pWordsNegy, prior_Pos, test_word_arrayMarkedArray, D, DS_temp): errorCount = 0 for j in range(testCount): try: pP, pN, smsType = classify_without_D(pWordsPosicity, pWordsNegy, prior_Pos, test_word_arrayMarkedArray[j], D, DS_temp) if smsType != test_word_arrayLabel[j]: errorCount += 1 except Exception as e: traceback.print_exc(e) print(errorCount / testCount)
Example #22
Source File: two_nb.py From weiboanalysis with Apache License 2.0 | 5 votes |
def trainingNaiveBayes(train_mood_array, label): # 计算先验概率 numTrainDoc = len(train_mood_array) numWords = len(train_mood_array[0]) prior_Pos, prior_Neg = 0.0, 0.0 for i in label: if i == 1: prior_Pos = prior_Pos + 1 elif i == 2: prior_Neg = prior_Neg + 1 prior_Neg = prior_Neg / float(numTrainDoc) prior_Pos = prior_Pos / float(numTrainDoc) wordsInPosNum = np.ones(numWords) wordsInNegNum = np.ones(numWords) PosWordsNum = 2.0 # 如果一个概率为0,乘积为0,故初始化1,分母2 NegWordsNum = 2.0 for i in range(0, numTrainDoc): try: if label[i] == 1: wordsInPosNum += train_mood_array[i] PosWordsNum += sum(train_mood_array[i]) # 统计Pos中语料库中词汇出现的总次数 elif label[i] == 2: wordsInNegNum += train_mood_array[i] NegWordsNum += sum(train_mood_array[i]) except Exception as e: traceback.print_exc(e) pWordsPosicity = np.log(wordsInPosNum / PosWordsNum) pWordsNegy = np.log(wordsInNegNum / NegWordsNum) return pWordsPosicity, pWordsNegy, prior_Pos
Example #23
Source File: Bayes.py From weiboanalysis with Apache License 2.0 | 5 votes |
def predict(test_word_array, test_word_arrayLabel, testCount, PosWords, NegWords, NeutralWords, prior_Pos, prior_Neg, prior_Neutral): errorCount = 0 for j in range(testCount): try: pP, pN, pNeu, smsType = classify(PosWords, NegWords, NeutralWords, prior_Pos, prior_Neg, prior_Neutral, test_word_array[j]) if smsType != test_word_arrayLabel[j]: errorCount += 1 except Exception as e: traceback.print_exc(e) print(errorCount / testCount)
Example #24
Source File: _dummy_thread.py From jawfish with MIT License | 5 votes |
def start_new_thread(function, args, kwargs={}): """Dummy implementation of _thread.start_new_thread(). Compatibility is maintained by making sure that ``args`` is a tuple and ``kwargs`` is a dictionary. If an exception is raised and it is SystemExit (which can be done by _thread.exit()) it is caught and nothing is done; all other exceptions are printed out by using traceback.print_exc(). If the executed function calls interrupt_main the KeyboardInterrupt will be raised when the function returns. """ if type(args) != type(tuple()): raise TypeError("2nd arg must be a tuple") if type(kwargs) != type(dict()): raise TypeError("3rd arg must be a dict") global _main _main = False try: function(*args, **kwargs) except SystemExit: pass except: import traceback traceback.print_exc() _main = True global _interrupt if _interrupt: _interrupt = False raise KeyboardInterrupt
Example #25
Source File: _thread.py From jawfish with MIT License | 5 votes |
def start_new_thread(function, args, kwargs={}): """Dummy implementation of _thread.start_new_thread(). Compatibility is maintained by making sure that ``args`` is a tuple and ``kwargs`` is a dictionary. If an exception is raised and it is SystemExit (which can be done by _thread.exit()) it is caught and nothing is done; all other exceptions are printed out by using traceback.print_exc(). If the executed function calls interrupt_main the KeyboardInterrupt will be raised when the function returns. """ if type(args) != type(tuple()): raise TypeError("2nd arg must be a tuple") if type(kwargs) != type(dict()): raise TypeError("3rd arg must be a dict") global _main _main = False try: function(*args, **kwargs) except SystemExit: pass except: import traceback traceback.print_exc() _main = True global _interrupt if _interrupt: _interrupt = False raise KeyboardInterrupt
Example #26
Source File: util.py From jawfish with MIT License | 5 votes |
def _run_finalizers(minpriority=None): ''' Run all finalizers whose exit priority is not None and at least minpriority Finalizers with highest priority are called first; finalizers with the same priority will be called in reverse order of creation. ''' if _finalizer_registry is None: # This function may be called after this module's globals are # destroyed. See the _exit_function function in this module for more # notes. return if minpriority is None: f = lambda p : p[0][0] is not None else: f = lambda p : p[0][0] is not None and p[0][0] >= minpriority items = [x for x in list(_finalizer_registry.items()) if f(x)] items.sort(reverse=True) for key, finalizer in items: sub_debug('calling %s', finalizer) try: finalizer() except Exception: import traceback traceback.print_exc() if minpriority is None: _finalizer_registry.clear() # # Clean up on exit #
Example #27
Source File: tools.py From OpenTrader with GNU Lesser General Public License v3.0 | 5 votes |
def print_exc(): """Print exception, and its relevant stack trace.""" tb = sys.exc_info()[2] length = 0 while tb and '__unittest' not in tb.tb_frame.f_globals: length += 1 tb = tb.tb_next traceback.print_exc(limit=length)
Example #28
Source File: multiprocessor.py From svviz with MIT License | 5 votes |
def _map(cls, methodName, initArgs, args, chunkNum, verbose): """ this takes care of most of the goodies, such as instantiating the Multiprocessor subclass, and performing the actual 'map' activity (as well as taking care of passing progress information back to the main process) """ t0 = time.time() if initArgs != None: instance_ = cls(*initArgs) else: instance_ = cls() boundMethod = getattr(instance_, methodName) results = [] try: tlast = time.time() for i, arg in enumerate(args): tnow = time.time() if verbose > 1 and (i%100==0 or i%(len(args)/20+1)==0 or (tnow-tlast)>1): if hasattr(_map, "q"): _map.q.put((i, len(args), chunkNum)) else: print(i, "of", len(args), chunkNum) tlast = tnow results.append(boundMethod(arg)) t1 = time.time() if 0 < verbose < 3: print("time elapsed:", t1-t0, "chunk:", chunkNum) return results except Exception as e: traceback.print_exc(file=sys.stdout) raise
Example #29
Source File: Bayes.py From weiboanalysis with Apache License 2.0 | 5 votes |
def trainingNaiveBayes(train_mood_array, label): # 计算先验概率 numTrainDoc = len(train_mood_array) numWords = len(train_mood_array[0]) prior_Pos, prior_Neg, prior_Neutral = 0.0, 0.0, 0.0 for i in label: if i == 1: prior_Pos = prior_Pos + 1 elif i == 2: prior_Neg = prior_Neg + 1 else: prior_Neutral = prior_Neutral + 1 prior_Pos = prior_Pos / float(numTrainDoc) prior_Neg = prior_Neg / float(numTrainDoc) prior_Neutral = prior_Neutral / float(numTrainDoc) wordsInPosNum = np.ones(numWords) wordsInNegNum = np.ones(numWords) wordsInNeutralNum = np.ones(numWords) PosWordsNum = 2.0 # 如果一个概率为0,乘积为0,故初始化1,分母2 NegWordsNum = 2.0 NeutralWordsNum = 2.0 for i in range(0, numTrainDoc): try: if label[i] == 1: wordsInPosNum += train_mood_array[i] PosWordsNum += sum(train_mood_array[i]) # 统计Pos中语料库中词汇出现的总次数 elif label[i] == 2: wordsInNegNum += train_mood_array[i] NegWordsNum += sum(train_mood_array[i]) else: wordsInNeutralNum += train_mood_array[i] NeutralWordsNum += sum(train_mood_array[i]) except Exception as e: traceback.print_exc(e) pWordsPosicity = np.log(wordsInPosNum / PosWordsNum) pWordsNegy = np.log(wordsInNegNum / NegWordsNum) pWordsNeutral = np.log(wordsInNeutralNum / NeutralWordsNum) return pWordsPosicity, pWordsNegy, pWordsNeutral, prior_Pos, prior_Neg, prior_Neutral
Example #30
Source File: cmd2plus.py From OpenTrader with GNU Lesser General Public License v3.0 | 5 votes |
def perror(self, errmsg, statement=None): if self.debug: traceback.print_exc() print (str(errmsg)) if self.pdb: set_trace()