Python traceback.print_stack() Examples

The following are 60 code examples for showing how to use traceback.print_stack(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

You may also check out all available functions/classes of the module traceback , or try the search function .

Example 1
Project: indras_net   Author: gcallah   File: env.py    License: 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 2
Project: rtp_cluster   Author: sippy   File: EventDispatcher.py    License: 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 3
Project: jawfish   Author: war-and-code   File: __init__.py    License: MIT License 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 4
Project: pyDcop   Author: Orange-OpenSource   File: orchestrator.py    License: 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 5
Project: pyDcop   Author: Orange-OpenSource   File: solve.py    License: 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 6
Project: pyDcop   Author: Orange-OpenSource   File: run.py    License: 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 7
Project: pyDcop   Author: Orange-OpenSource   File: distribute.py    License: 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 8
Project: tf-pose   Author: SrikanthVelpuri   File: mutex.py    License: 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 9
Project: pyquarkchain   Author: QuarkChain   File: utils.py    License: 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 10
Project: ReadableWebProxy   Author: fake-name   File: logSetup.py    License: 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 11
Project: ReadableWebProxy   Author: fake-name   File: db_engine.py    License: 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 12
Project: ntu-dsi-dcn   Author: ntu-dsi-dcn   File: ns3modulegen.py    License: 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 13
Project: IEEE-802.11ah-ns-3   Author: imec-idlab   File: ns3modulegen.py    License: 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 14
Project: loopchain   Author: icon-project   File: __init__.py    License: 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 15
Project: debin   Author: eth-sri   File: elmfactory.py    License: 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 16
Project: b2bua   Author: sippy   File: EventDispatcher.py    License: 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 17
Project: ns3-load-balance   Author: snowzjx   File: ns3modulegen.py    License: 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 18
Project: ufora   Author: ufora   File: CumulusGateway.py    License: 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 19
Project: 802.11ah-ns3   Author: MOSAIC-UA   File: ns3modulegen.py    License: 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
Project: ns3-rdma   Author: bobzhuyb   File: ns3modulegen.py    License: 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
Project: grin-pool   Author: grin-pool   File: paymentReport.py    License: 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 22
Project: royal-chaos   Author: KTH   File: ns3modulegen.py    License: 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 23
Project: flappy-bird-py   Author: shrimpboyho   File: __init__.py    License: 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 24
Project: flappy-bird-py   Author: shrimpboyho   File: __init__.py    License: 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 25
Project: flappy-bird-py   Author: shrimpboyho   File: __init__.py    License: 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 26
Project: Fluid-Designer   Author: Microvellum   File: __init__.py    License: 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 27
Project: controller   Author: deis   File: config.py    License: MIT License 5 votes vote down vote up
def worker_int(worker):
    """Print a stack trace when a worker receives a SIGINT or SIGQUIT signal."""
    worker.log.warning('worker terminated')
    import traceback
    traceback.print_stack() 
Example 28
Project: controller   Author: deis   File: config.py    License: MIT License 5 votes vote down vote up
def worker_abort(worker):
    """Print a stack trace when a worker receives a SIGABRT signal, generally on timeout."""
    worker.log.warning('worker aborted')
    import traceback
    traceback.print_stack() 
Example 29
Project: rtp_cluster   Author: sippy   File: EventDispatcher.py    License: 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 30
Project: IGMC   Author: muhanzhang   File: Main.py    License: MIT License 5 votes vote down vote up
def warn_with_traceback(message, category, filename, lineno, file=None, line=None):

    log = file if hasattr(file,'write') else sys.stderr
    traceback.print_stack(file=log)
    log.write(warnings.formatwarning(message, category, filename, lineno, line)) 
Example 31
Project: jawfish   Author: war-and-code   File: __init__.py    License: MIT License 5 votes vote down vote up
def formatStack(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 32
Project: jawfish   Author: war-and-code   File: __init__.py    License: MIT License 5 votes vote down vote up
def findCaller(self, stack_info=False):
        """
        Find the stack frame of the caller so that we can note the source
        file name, line number and function name.
        """
        f = currentframe()
        #On some versions of IronPython, currentframe() returns None if
        #IronPython isn't run with -X:Frames.
        if f is not None:
            f = f.f_back
        rv = "(unknown file)", 0, "(unknown function)", None
        while hasattr(f, "f_code"):
            co = f.f_code
            filename = os.path.normcase(co.co_filename)
            if filename == _srcfile:
                f = f.f_back
                continue
            sinfo = None
            if stack_info:
                sio = io.StringIO()
                sio.write('Stack (most recent call last):\n')
                traceback.print_stack(f, file=sio)
                sinfo = sio.getvalue()
                if sinfo[-1] == '\n':
                    sinfo = sinfo[:-1]
                sio.close()
            rv = (co.co_filename, f.f_lineno, co.co_name, sinfo)
            break
        return rv 
Example 33
Project: verge3d-blender-addon   Author: Soft8Soft   File: log.py    License: GNU General Public License v3.0 5 votes vote down vote up
def printLog(level, output):

    global outputFile
    global outputLevels
    global outputLevel

    if outputLevels.index(level) > outputLevels.index(outputLevel):
        return

    print('V3D-' + level + ': ' + output, file=outputFile)
    if level == 'ERROR':
        traceback.print_stack(file=outputFile)

    if outputFile != sys.stdout:
        outputFile.flush() 
Example 34
Project: python-control   Author: python-control   File: runtests.py    License: 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):
    traceback.print_stack()
    log = file if hasattr(file, 'write') else sys.stderr
    log.write(warnings.formatwarning(message, category, filename, lineno, line)) 
Example 35
Project: frigate   Author: blakeblackshear   File: util.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def print_stack(sig, frame):
    traceback.print_stack(frame) 
Example 36
Project: frigate   Author: blakeblackshear   File: util.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def listen():
    signal.signal(signal.SIGUSR1, print_stack) 
Example 37
Project: benchmarks   Author: tensorflow   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def print_thread_stacktrace():
  print('Here is the stacktrace for all threads:')
  thread_names = {t.ident: t.name for t in threading.enumerate()}
  for thread_id, frame in sys._current_frames().items():  # pylint: disable=protected-access
    print('Thread {}'.format(thread_names.get(thread_id, thread_id)))
    traceback.print_stack(frame) 
Example 38
Project: pyDcop   Author: Orange-OpenSource   File: run.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def on_force_exit(sig, frame):
    if orchestrator is None:
        return
    orchestrator.status = "STOPPED"
    orchestrator.stop_agents(5)
    orchestrator.stop()
    _results("STOPPED")
    # for th in threading.enumerate():
    #     print(th)
    #     traceback.print_stack(sys._current_frames()[th.ident])
    #     print() 
Example 39
Project: mishkal   Author: linuxscout   File: watchthreads.py    License: GNU General Public License v3.0 5 votes vote down vote up
def traceback_thread(thread_id):
    """
    Returns a plain-text traceback of the given thread, or None if it
    can't get a traceback.
    """
    if not hasattr(sys, '_current_frames'):
        # Only 2.5 has support for this, with this special function
        return None
    frames = sys._current_frames()
    if not thread_id in frames:
        return None
    frame = frames[thread_id]
    out = StringIO()
    traceback.print_stack(frame, file=out)
    return out.getvalue() 
Example 40
Project: tf-pose   Author: SrikanthVelpuri   File: Parameter.py    License: Apache License 2.0 5 votes vote down vote up
def __getattr__(self, attr):
        ## Leaving this undocumented because I might like to remove it in the future..
        #print type(self), attr
        
        if 'names' not in self.__dict__:
            raise AttributeError(attr)
        if attr in self.names:
            import traceback
            traceback.print_stack()
            print("Warning: Use of Parameter.subParam is deprecated. Use Parameter.param(name) instead.")
            return self.param(attr)
        else:
            raise AttributeError(attr) 
Example 41
Project: tf-pose   Author: SrikanthVelpuri   File: remoteproxy.py    License: Apache License 2.0 5 votes vote down vote up
def result(self, block=True, timeout=None):
        """
        Return the result for this request. 
        
        If block is True, wait until the result has arrived or *timeout* seconds passes.
        If the timeout is reached, raise NoResultError. (use timeout=None to disable)
        If block is False, raise NoResultError immediately if the result has not arrived yet.
        
        If the process's connection has closed before the result arrives, raise ClosedError.
        """
        
        if self.gotResult:
            return self._result
            
        if timeout is None:
            timeout = self.timeout 
        
        if block:
            start = time.time()
            while not self.hasResult():
                if self.proc.exited:
                    raise ClosedError()
                time.sleep(0.005)
                if timeout >= 0 and time.time() - start > timeout:
                    print("Request timed out: %s" % self.description)
                    import traceback
                    traceback.print_stack()
                    raise NoResultError()
            return self._result
        else:
            self._result = self.proc.getResult(self.reqId)  ## raises NoResultError if result is not available yet
            self.gotResult = True
            return self._result 
Example 42
Project: tf-pose   Author: SrikanthVelpuri   File: debug.py    License: Apache License 2.0 5 votes vote down vote up
def write(self, x):
        self.stdout.write(x)
        traceback.print_stack() 
Example 43
Project: tf-pose   Author: SrikanthVelpuri   File: debug.py    License: Apache License 2.0 5 votes vote down vote up
def run(self):
        while True:
            with self.lock:
                if self._stop is True:
                    return
                    
            print("\n=============  THREAD FRAMES:  ================")
            for id, frame in sys._current_frames().items():
                if id == threading.current_thread().ident:
                    continue
                print("<< thread %d >>" % id)
                traceback.print_stack(frame)
            print("===============================================\n")
            
            time.sleep(self.interval) 
Example 44
Project: ReadableWebProxy   Author: fake-name   File: stuck.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def handler(signum, frame):
	for th in threading.enumerate():
		print("Dumping stack for thread: ", th)
		traceback.print_stack(sys._current_frames()[th.ident])
		print() 
Example 45
Project: ReadableWebProxy   Author: fake-name   File: db_engine.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def session_context(name="", override_timeout_ms=False, quiet_override=False):
	postfix_name = name + 'context-sess'
	sess = get_db_session(postfix=postfix_name)

	try:
		if override_timeout_ms and not quiet_override:
			log.warning("Query timeout overridden to be %0.2f seconds!", override_timeout_ms / 1000.0, )
			sess.execute("""SET statement_timeout TO :new_timeout;""", { 'new_timeout' : override_timeout_ms, })
		yield sess

	except sqlalchemy.exc.InternalError:
		log.warning("(session_context) -> Transaction error (sqlalchemy.exc.InternalError).")
		sess.rollback()
		raise
	except sqlalchemy.exc.OperationalError:
		log.warning("(session_context) -> Transaction error (sqlalchemy.exc.OperationalError).")
		sess.rollback()
		raise
	except sqlalchemy.exc.IntegrityError:
		log.warning("(session_context) -> Transaction error (sqlalchemy.exc.IntegrityError).")
		sess.rollback()
		raise
	except sqlalchemy.exc.InvalidRequestError:
		log.warning("(session_context) -> Transaction error (sqlalchemy.exc.InvalidRequestError).")
		traceback.print_exc()
		sess.rollback()
		raise

	finally:
		if override_timeout_ms:
			sess.execute("""RESET statement_timeout;""")
		delete_db_session(postfix=postfix_name)


# import traceback
# traceback.print_stack() 
Example 46
Project: debugger   Author: Vector35   File: test.py    License: MIT License 5 votes vote down vote up
def assert_equality(a, b):
	if a == b: return
	utils.red('EXPECTED EQUALITY!')
	utils.red('  actual: %s' % a)
	utils.red('expected: %s' % b)
	traceback.print_stack()
	sys.exit(-1)

# let there be a single check for single-step
# (abstract away OS-exceptional cases) 
Example 47
Project: ironpython2   Author: IronLanguages   File: test_traceback.py    License: Apache License 2.0 5 votes vote down vote up
def test_print_stack(self):
        def prn():
            traceback.print_stack()
        with captured_output("stderr") as stderr:
            prn()
        lineno = prn.__code__.co_firstlineno
        file = prn.__code__.co_filename
        self.assertEqual(stderr.getvalue().splitlines()[-4:], [
            '  File "%s", line %d, in test_print_stack' % (file, lineno+3),
            '    prn()',
            '  File "%s", line %d, in prn' % (file, lineno+1),
            '    traceback.print_stack()',
        ]) 
Example 48
Project: thenextquant   Author: SimoHaiLiu   File: logger.py    License: MIT License 5 votes vote down vote up
def exception(*args, **kwargs):
    logging.error("*" * 60)
    msg_header, kwargs = _log_msg_header(*args, **kwargs)
    logging.error(_log(msg_header, *args, **kwargs))
    traceback.print_stack()
    logging.error("*" * 60) 
Example 49
Project: aws-media-services-simple-vod-workflow   Author: aws-samples   File: simple_event_collector.py    License: Apache License 2.0 5 votes vote down vote up
def lambda_handler(event, context): 

    print(json.dumps(event))

    job = {}
    tsevent = int(datetime.datetime.strptime(event["time"], "%Y-%m-%dT%H:%M:%SZ").timestamp())
    
    try:
        # Get environment variables set on the CloudFormation stack
        EVENTTABLE = os.environ['EventTable']
        EVENTTABLETTL = os.environ['EventTableTTL']
        
        EVENT_RETENTION_PERIOD = (3600 * 24 * int(EVENTTABLETTL))

        # add expirtation timestamp for dynamo and save the event in dynamo
        event["timestamp"] = tsevent
        event["timestampTTL"] = tsevent + EVENT_RETENTION_PERIOD
        event["jobId"] = event['detail']['jobId']
        s = json.dumps(event, cls=DecimalEncoder)
        event = json.loads(s, parse_float=decimal.Decimal)
        table = DYNAMO_CLIENT.Table(EVENTTABLE)
        response = table.put_item(Item = event)
        print(json.dumps(response, cls=DecimalEncoder))
        
    except Exception as e:
        print('An error occured {}'.format(e))
        traceback.print_stack()
        raise
    else:
        return True 
Example 50
Project: BinderFilter   Author: dxwu   File: rpc.py    License: MIT License 5 votes vote down vote up
def pollmessage(self, wait):
        packet = self.pollpacket(wait)
        if packet is None:
            return None
        try:
            message = pickle.loads(packet)
        except pickle.UnpicklingError:
            print >>sys.__stderr__, "-----------------------"
            print >>sys.__stderr__, "cannot unpickle packet:", repr(packet)
            traceback.print_stack(file=sys.__stderr__)
            print >>sys.__stderr__, "-----------------------"
            raise
        return message 
Example 51
Project: pajbot   Author: pajbot   File: print_traceback.py    License: MIT License 5 votes vote down vote up
def print_traceback():
    traceback.print_stack() 
Example 52
Project: pajbot   Author: pajbot   File: dump_threads.py    License: MIT License 5 votes vote down vote up
def dump_threads():
    import threading
    import traceback

    for th in threading.enumerate():
        print(th)
        traceback.print_stack(sys._current_frames()[th.ident])
        print() 
Example 53
Project: oss-ftp   Author: aliyun   File: rpc.py    License: MIT License 5 votes vote down vote up
def pollmessage(self, wait):
        packet = self.pollpacket(wait)
        if packet is None:
            return None
        try:
            message = pickle.loads(packet)
        except pickle.UnpicklingError:
            print >>sys.__stderr__, "-----------------------"
            print >>sys.__stderr__, "cannot unpickle packet:", repr(packet)
            traceback.print_stack(file=sys.__stderr__)
            print >>sys.__stderr__, "-----------------------"
            raise
        return message 
Example 54
Project: PyDev.Debugger   Author: fabioz   File: pydevd_tracing.py    License: Eclipse Public License 1.0 5 votes vote down vote up
def _get_stack_str(frame):

    msg = '\nIf this is needed, please check: ' + \
          '\nhttp://pydev.blogspot.com/2007/06/why-cant-pydev-debugger-work-with.html' + \
          '\nto see how to restore the debug tracing back correctly.\n'

    if TracingFunctionHolder._traceback_limit:
        s = StringIO.StringIO()
        s.write('Call Location:\n')
        traceback.print_stack(f=frame, limit=TracingFunctionHolder._traceback_limit, file=s)
        msg = msg + s.getvalue()

    return msg 
Example 55
Project: Safejumper-for-Desktop   Author: proxysh   File: crefutil.py    License: 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 56
Project: debin   Author: eth-sri   File: debuginfo.py    License: 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 57
Project: b2bua   Author: sippy   File: EventDispatcher.py    License: 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 58
Project: scanpy   Author: theislab   File: _utils.py    License: 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)) 
Example 59
Project: fastMRI   Author: facebookresearch   File: training_loop_mixin.py    License: 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 60
Project: amplicon_sequencing_pipeline   Author: thomasgurry   File: die.py    License: MIT License 5 votes vote down vote up
def Die(Msg):
	print >> sys.stderr
	print >> sys.stderr

	traceback.print_stack()
	s = ""
	for i in range(0, len(sys.argv)):
		if i > 0:
			s += " "
		s += sys.argv[i]
	print >> sys.stderr, s
	print >> sys.stderr, "**ERROR**", Msg
	print >> sys.stderr
	print >> sys.stderr
	sys.exit(1)