Python traceback.print_stack() Examples

The following are 30 code examples of traceback.print_stack(). 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: db_engine.py    From ReadableWebProxy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def delete_db_session(postfix="", flask_sess_if_possible=True):
	if flags.IS_FLASK and flask_sess_if_possible:
		# No need to do anything with flask sess
		return

	cpid = multiprocessing.current_process().name
	ctid = threading.current_thread().name
	csid = "{}-{}-{}".format(cpid, ctid, postfix)


	# print("Releasing session for thread: %s" % csid)
	# print(traceback.print_stack())
	# print("==========================")

	if csid in SESSIONS:
		with SESSION_LOCK:
			# check if the session was created while
			# we were waiting for the lock
			if not csid in SESSIONS:
				return
			SESSIONS[csid][1].close()
			del SESSIONS[csid]
			# print("Deleted session for id: ", csid) 
Example #2
Source File: paymentReport.py    From grin-pool with Apache License 2.0 6 votes vote down vote up
def main():
    CONFIG = lib.get_config()
    LOGGER = lib.get_logger(PROCESS)
    LOGGER.warn("=== Starting {}".format(PROCESS))
    # Connect to DB
    database = lib.get_db()
    database.db.initializeSession()

    pp = pprint.PrettyPrinter(indent=4)

    # Fetch and print pool block reward estimates for latest N pool blocks
    try:
        pool_blocks = Pool_blocks.get_latest(NUM_BLOCKS)
        pool_blocks_h = [blk.height for blk in pool_blocks]
        LOGGER.warn("Will report estimates for pool blocks: {}".format(pool_blocks_h))

        # Print Estimate
        for height in pool_blocks_h:
            pp.pprint("Eestimate for block: {}".format(height))
            payout_map = pool.get_block_payout_map_estimate(height, LOGGER)
            pp.pprint(payout_map)
    except Exception as e:  # AssertionError as e:
        LOGGER.error("Something went wrong: {} - {}".format(e, traceback.print_stack()))
    
        LOGGER.warn("=== Completed {}".format(PROCESS)) 
Example #3
Source File: __init__.py    From flappy-bird-py with GNU General Public License v2.0 6 votes vote down vote up
def _error_handler(display, event):
    # By default, all errors are silently ignored: this has a better chance
    # of working than the default behaviour of quitting ;-)
    #
    # We've actually never seen an error that was our fault; they're always
    # driver bugs (and so the reports are useless).  Nevertheless, set
    # environment variable PYGLET_DEBUG_X11 to 1 to get dumps of the error
    # and a traceback (execution will continue).
    if pyglet.options['debug_x11']:
        event = event.contents
        buf = c_buffer(1024)
        xlib.XGetErrorText(display, event.error_code, buf, len(buf))
        print 'X11 error:', buf.value
        print '   serial:', event.serial
        print '  request:', event.request_code
        print '    minor:', event.minor_code
        print ' resource:', event.resourceid

        import traceback
        print 'Python stack trace (innermost last):'
        traceback.print_stack()
    return 0 
Example #4
Source File: ns3modulegen.py    From royal-chaos with MIT License 6 votes vote down vote up
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 #5
Source File: ns3modulegen.py    From IEEE-802.11ah-ns-3 with GNU General Public License v2.0 6 votes vote down vote up
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: __init__.py    From flappy-bird-py with GNU General Public License v2.0 6 votes vote down vote up
def _error_handler(display, event):
    # By default, all errors are silently ignored: this has a better chance
    # of working than the default behaviour of quitting ;-)
    #
    # We've actually never seen an error that was our fault; they're always
    # driver bugs (and so the reports are useless).  Nevertheless, set
    # environment variable PYGLET_DEBUG_X11 to 1 to get dumps of the error
    # and a traceback (execution will continue).
    if pyglet.options['debug_x11']:
        event = event.contents
        buf = c_buffer(1024)
        xlib.XGetErrorText(display, event.error_code, buf, len(buf))
        print 'X11 error:', buf.value
        print '   serial:', event.serial
        print '  request:', event.request_code
        print '    minor:', event.minor_code
        print ' resource:', event.resourceid

        import traceback
        print 'Python stack trace (innermost last):'
        traceback.print_stack()
    return 0 
Example #7
Source File: __init__.py    From flappy-bird-py with GNU General Public License v2.0 6 votes vote down vote up
def _error_handler(display, event):
    # By default, all errors are silently ignored: this has a better chance
    # of working than the default behaviour of quitting ;-)
    #
    # We've actually never seen an error that was our fault; they're always
    # driver bugs (and so the reports are useless).  Nevertheless, set
    # environment variable PYGLET_DEBUG_X11 to 1 to get dumps of the error
    # and a traceback (execution will continue).
    if pyglet.options['debug_x11']:
        event = event.contents
        buf = c_buffer(1024)
        xlib.XGetErrorText(display, event.error_code, buf, len(buf))
        print 'X11 error:', buf.value
        print '   serial:', event.serial
        print '  request:', event.request_code
        print '    minor:', event.minor_code
        print ' resource:', event.resourceid

        import traceback
        print 'Python stack trace (innermost last):'
        traceback.print_stack()
    return 0 
Example #8
Source File: __init__.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def formatException(self, ei):
        """
        Format and return the specified exception information as a string.

        This default implementation just uses
        traceback.print_exception()
        """
        sio = io.StringIO()
        tb = ei[2]
        # See issues #9427, #1553375. Commented out for now.
        #if getattr(self, 'fullstack', False):
        #    traceback.print_stack(tb.tb_frame.f_back, file=sio)
        traceback.print_exception(ei[0], ei[1], tb, None, sio)
        s = sio.getvalue()
        sio.close()
        if s[-1:] == "\n":
            s = s[:-1]
        return s 
Example #9
Source File: env.py    From indras_net with GNU General Public License v3.0 6 votes vote down vote up
def scatter_graph(self):
        """
        Show agent locations.
        """
        if self.has_disp():
            try:
                data = self.plot_data()
                scatter_plot = disp.ScatterPlot(
                    self.plot_title, data,
                    int(self.width), int(self.height),
                    anim=True, data_func=self.plot_data,
                    is_headless=self.headless(),
                    attrs=self.attrs)
                scatter_plot.show()
                return scatter_plot
            except ValueError as e:  # Exception as e:
                self.user.tell("Error when drawing scatter plot: " + str(e))
                traceback.print_stack()
        else:
            return None 
Example #10
Source File: elmfactory.py    From debin with Apache License 2.0 6 votes vote down vote up
def make_direct_offset(offset, blk, pc, access=None):
    # if offset < 100000:
    #     print(offset)
    #     traceback.print_stack(file=sys.stdout)
    function = blk.function
    binary = function.binary

    if offset in binary.direct_offsets:
        direct_offset = binary.direct_offsets[offset]
    else:
        direct_offset = DirectOffset(binary=binary, offset=offset, access=access)
        binary.direct_offsets[offset] = direct_offset

    function.direct_offsets.add(offset)

    return direct_offset 
Example #11
Source File: __init__.py    From loopchain with Apache License 2.0 6 votes vote down vote up
def exit_and_msg(msg):
    traceback.print_stack()

    exit_msg = "Service Stop by: " + msg
    logging.exception(exit_msg)

    # To make sure of terminating process exactly
    os.killpg(0, signal.SIGKILL)
    time.sleep(5)

    os.kill(os.getpid(), signal.SIGKILL)
    time.sleep(5)

    os._exit(-1)
    time.sleep(5)

    sys.exit(-1) 
Example #12
Source File: EventDispatcher.py    From b2bua with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def go(self):
        if self.ed.my_ident != get_ident():
            print(datetime.now(), 'EventDispatcher2: Timer.go() from wrong thread, expect Bad Stuff[tm] to happen')
            print('-' * 70)
            traceback.print_stack(file = sys.stdout)
            print('-' * 70)
            sys.stdout.flush()
        if not self.abs_time:
            if self.randomize_runs != None:
                ival = self.randomize_runs(self.ival)
            else:
                ival = self.ival
            self.etime = self.itime.getOffsetCopy(ival)
        else:
            self.etime = self.ival
            self.ival = None
            self.nticks = 1
        heappush(self.ed.tlisteners, self)
        return 
Example #13
Source File: solve.py    From pyDcop with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def on_timeout():
    logger.debug("cli timeout ")
    # Timeout should have been handled by the orchestrator, if the cli timeout
    # has been reached, something is probably wrong : dump threads.
    for th in threading.enumerate():
        print(th)
        traceback.print_stack(sys._current_frames()[th.ident])
        print()

    if orchestrator is None:
        logger.debug("cli timeout with no orchestrator ?")
        return
    global timeout_stopped
    timeout_stopped = True
    # Stopping agents can be rather long, we need a big timeout !
    logger.debug("stop agent on cli timeout ")
    orchestrator.stop_agents(20)
    logger.debug("stop orchestrator on cli timeout ")
    orchestrator.stop()
    _results("TIMEOUT")
    # sys.exit(0)
    os._exit(2) 
Example #14
Source File: orchestrator.py    From pyDcop with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def on_timeout():
    logger.debug("cli timeout ")
    # Timeout should have been handled by the orchestrator, if the cli timeout
    # has been reached, something is probably wrong : dump threads.
    for th in threading.enumerate():
        print(th)
        traceback.print_stack(sys._current_frames()[th.ident])
        print()

    if orchestrator is None:
        logger.debug("cli timeout with no orchestrator ?")
        return
    global timeout_stopped
    timeout_stopped = True

    orchestrator.stop_agents(20)
    orchestrator.stop()
    _results("TIMEOUT")
    sys.exit(0) 
Example #15
Source File: CumulusGateway.py    From ufora with Apache License 2.0 6 votes vote down vote up
def handleClientMessage_(self, msg):
        if isinstance(msg, CumulusNative.ComputationResult):
            self.onComputationResult(msg.computation, msg.deserializedResult(self.vdm), msg.statistics)

        elif isinstance(msg, tuple):
            self.onCheckpointStatus(msg[0], msg[1])

        elif isinstance(msg, CumulusNative.VectorLoadedResponse):
            if not msg.loadSuccessful:
                traceback.print_stack()
                logging.info("MN>> Failure in handleClientMessage_: %s", traceback.format_exc())
                logging.critical("Page Load failed. This is not handled correctly yet. %s", msg)

            self.onCacheLoad(msg.vdid)
        elif isinstance(msg, CumulusNative.GlobalUserFacingLogMessage):
            self.onNewGlobalUserFacingLogMessage(msg)
        elif isinstance(msg, CumulusNative.ExternalIoTaskCompleted):
            self.onExternalIoTaskCompleted(msg) 
Example #16
Source File: logSetup.py    From ReadableWebProxy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def emit(self, record):
		"""
		Emit a record.

		If the stream was not opened because 'delay' was specified in the
		constructor, open it before calling the superclass's emit.
		"""
		failures = 0
		while failures < 3:
			try:
				self.stream_emit(record, record.name)
				break
			except:
				failures += 1
		else:
			traceback.print_stack()
			print("Error writing to file?")


		self.close() 
Example #17
Source File: utils.py    From pyquarkchain with MIT License 6 votes vote down vote up
def findCaller(self, stack_info=False):
        frame = sys._getframe(2)
        f_to_skip = {
            func for func in dir(Logger) if callable(getattr(Logger, func))
        }.union({func for func in dir(QKCLogger) if callable(getattr(QKCLogger, func))})

        while frame:
            code = frame.f_code
            if _LOGGING_FILE_PREFIX not in code.co_filename and (
                "utils.py" not in code.co_filename or code.co_name not in f_to_skip
            ):
                if not stack_info:
                    return (code.co_filename, frame.f_lineno, code.co_name, "")
                else:
                    sinfo = None
                    if stack_info:
                        out = io.StringIO()
                        out.write(u"Stack (most recent call last):\n")
                        traceback.print_stack(frame, file=out)
                        sinfo = out.getvalue().rstrip(u"\n")
                    return (code.co_filename, frame.f_lineno, code.co_name, sinfo)
            frame = frame.f_back 
Example #18
Source File: mutex.py    From tf-pose with Apache License 2.0 6 votes vote down vote up
def lock(self, id=None):
        c = 0
        waitTime = 5000  # in ms
        while True:
            if self.tryLock(waitTime, id):
                break
            c += 1
            if self.debug:
                self.l.lock()
                try:
                    print("Waiting for mutex lock (%0.1f sec). Traceback follows:" 
                          % (c*waitTime/1000.))
                    traceback.print_stack()
                    if len(self.tb) > 0:
                        print("Mutex is currently locked from:\n")
                        print(self.tb[-1])
                    else:
                        print("Mutex is currently locked from [???]")
                finally:
                    self.l.unlock()
        #print 'lock', self, len(self.tb) 
Example #19
Source File: ns3modulegen.py    From ns3-load-balance with GNU General Public License v2.0 6 votes vote down vote up
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 #20
Source File: ns3modulegen.py    From 802.11ah-ns3 with GNU General Public License v2.0 6 votes vote down vote up
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 #21
Source File: ns3modulegen.py    From ns3-rdma with GNU General Public License v2.0 6 votes vote down vote up
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: distribute.py    From pyDcop with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def on_timeout():
    global result, output_file
    global start_t
    duration = time.time() - start_t

    print("TIMEOUT when distributing")
    logger.info("cli timeout when distributing")
    for th in threading.enumerate():
        print(th)
        traceback.print_stack(sys._current_frames()[th.ident])

    result["status"] =  "TIMEOUT"
    result["inputs"]["duration"] = duration

    if output_file is not None:
        with open(output_file, encoding="utf-8", mode="w") as fo:
            fo.write(yaml.dump(result))
    print(yaml.dump(result))

    #os._exit(0)
    sys.exit(0) 
Example #23
Source File: run.py    From pyDcop with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def on_timeout():
    if orchestrator is None:
        return
    # Timeout should have been handled by the orchestrator, if the cli timeout
    # has been reached, something is probably wrong : dump threads.
    for th in threading.enumerate():
        print(th)
        traceback.print_stack(sys._current_frames()[th.ident])
        print()
    if orchestrator is None:
        logger.debug("cli timeout with no orchestrator ?")
        return
    global timeout_stopped
    timeout_stopped = True

    # Stopping agents can be rather long, we need a big timeout !
    orchestrator.stop_agents(20)
    orchestrator.stop()
    _results("TIMEOUT")
    sys.exit(0) 
Example #24
Source File: ns3modulegen.py    From ntu-dsi-dcn with GNU General Public License v2.0 6 votes vote down vote up
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 #25
Source File: debuginfo.py    From debin with Apache License 2.0 5 votes vote down vote up
def indirect_offset_add_info(self, function, base_pointer, offset, die, low_pc, high_pc, ttype):
        key = (base_pointer, offset)
        # print(key)
        # traceback.print_stack(file=sys.stdout)
        if key in function.indirect_offsets:
            for indirect_offset in function.indirect_offsets[key].values():
                if low_pc is None and high_pc is None:
                    indirect_offset.train_info(die, ttype)
                else:
                    for pc in indirect_offset.pcs:
                        if pc >= low_pc and pc < high_pc:
                            indirect_offset.train_info(die, ttype)
                            break 
Example #26
Source File: crefutil.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def __call__(self, *args, **kw):
        import traceback
        log.msg('instance method %s.%s' % (reflect.qual(self.my_class), self.name))
        log.msg('being called with %r %r' % (args, kw))
        traceback.print_stack(file=log.logfile)
        assert 0 
Example #27
Source File: base.py    From aiologger with MIT License 5 votes vote down vote up
def format_stack(self, stack_info):
        """
        This method is provided as an extension point for specialized
        formatting of stack information.

        The input data is a string as returned from a call to
        :func:`traceback.print_stack`, but with the last trailing newline
        removed.

        The base implementation just returns the value passed in.
        """
        return stack_info 
Example #28
Source File: EventDispatcher.py    From b2bua with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def breakLoop(self):
        self.endloop = True
        #print('breakLoop')
        #import traceback
        #import sys
        #traceback.print_stack(file = sys.stdout) 
Example #29
Source File: training_loop_mixin.py    From fastMRI with MIT License 5 votes vote down vote up
def check_for_nan(self, loss):
        def check(x, desc):
            result = torch.any(torch.isnan(x)) or torch.any(torch.isinf(x))
            if result:
                traceback.print_stack(file=sys.stdout)
                print(f"NaN/Inf detected in {desc}")
                pdb.set_trace()
            return result

        check(loss.data, "loss")
        # Check all model parameters, and gradients
        for nm, p in self.model.named_parameters():
            check(p.data, nm)
            if p.grad is not None:
                check(p.grad.data, nm + ".grad") 
Example #30
Source File: _utils.py    From scanpy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def warn_with_traceback(message, category, filename, lineno, file=None, line=None):
    """Get full tracebacks when warning is raised by setting

    warnings.showwarning = warn_with_traceback

    See also
    --------
    http://stackoverflow.com/questions/22373927/get-traceback-of-warnings
    """
    import traceback

    traceback.print_stack()
    log = file if hasattr(file, 'write') else sys.stderr
    settings.write(warnings.formatwarning(message, category, filename, lineno, line))