Python traceback.format_list() Examples

The following are code examples for showing how to use traceback.format_list(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: SoCFoundationFlow   Author: mattaw   File: Errors.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def __init__(self, msg='', ex=None):
		"""
		:param msg: error message
		:type msg: string
		:param ex: exception causing this error (optional)
		:type ex: exception
		"""
		self.msg = msg
		assert not isinstance(msg, Exception)

		self.stack = []
		if ex:
			if not msg:
				self.msg = str(ex)
			if isinstance(ex, WafError):
				self.stack = ex.stack
			else:
				self.stack = traceback.extract_tb(sys.exc_info()[2])
		self.stack += traceback.extract_stack()[:-1]
		self.verbose_msg = ''.join(traceback.format_list(self.stack)) 
Example 2
Project: SoCFoundationFlow   Author: mattaw   File: Errors.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def __init__(self, msg='', ex=None):
		"""
		:param msg: error message
		:type msg: string
		:param ex: exception causing this error (optional)
		:type ex: exception
		"""
		self.msg = msg
		assert not isinstance(msg, Exception)

		self.stack = []
		if ex:
			if not msg:
				self.msg = str(ex)
			if isinstance(ex, WafError):
				self.stack = ex.stack
			else:
				self.stack = traceback.extract_tb(sys.exc_info()[2])
		self.stack += traceback.extract_stack()[:-1]
		self.verbose_msg = ''.join(traceback.format_list(self.stack)) 
Example 3
Project: SoCFoundationFlow   Author: mattaw   File: Errors.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def __init__(self, msg='', ex=None):
		"""
		:param msg: error message
		:type msg: string
		:param ex: exception causing this error (optional)
		:type ex: exception
		"""
		self.msg = msg
		assert not isinstance(msg, Exception)

		self.stack = []
		if ex:
			if not msg:
				self.msg = str(ex)
			if isinstance(ex, WafError):
				self.stack = ex.stack
			else:
				self.stack = traceback.extract_tb(sys.exc_info()[2])
		self.stack += traceback.extract_stack()[:-1]
		self.verbose_msg = ''.join(traceback.format_list(self.stack)) 
Example 4
Project: pyrate-build   Author: pyrate-build   File: pyrate.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def format_exception(bfn, ex):
	import traceback, linecache
	exinfo = traceback.format_exception_only(ex.__class__, ex)
	if ex.__class__ == SyntaxError:
		exinfo = exinfo[1:]
		lineno = ex.lineno
		content = ''
		sys.stderr.write('Error while processing %s:%s\n\t%s\n' % (os.path.abspath(bfn), lineno, content.strip()))
	else:
		exec_line = None
		exloc = traceback.extract_tb(sys.exc_info()[2])
		for idx, entry in enumerate(exloc):
			if entry[3] is None:
				exec_line = idx
		if exec_line is not None:
			exloc = [(bfn, exloc[exec_line][1], '', linecache.getline(bfn, exloc[exec_line][1]))] + exloc[exec_line:]
		sys.stderr.write('Error while processing %s\n' % os.path.abspath(bfn))
		sys.stderr.write(str.join('', traceback.format_list(exloc)))
	sys.stderr.write(str.join('', exinfo))
	sys.exit(1) 
Example 5
Project: hostapd-mana   Author: adde88   File: code.py    (license) View Source Project 6 votes vote down vote up
def showtraceback(self):
        """Display the exception that just occurred.

        We remove the first stack item because it is our own code.

        The output is written by self.write(), below.

        """
        try:
            type, value, tb = sys.exc_info()
            sys.last_type = type
            sys.last_value = value
            sys.last_traceback = tb
            tblist = traceback.extract_tb(tb)
            del tblist[:1]
            list = traceback.format_list(tblist)
            if list:
                list.insert(0, "Traceback (most recent call last):\n")
            list[len(list):] = traceback.format_exception_only(type, value)
        finally:
            tblist = tb = None
        map(self.write, list) 
Example 6
Project: pythonVSCode   Author: DonJayamanne   File: visualstudio_py_debugger.py    (license) View Source Project 6 votes vote down vote up
def print_exception(exc_type, exc_value, exc_tb):
    # remove debugger frames from the top and bottom of the traceback
    tb = traceback.extract_tb(exc_tb)
    for i in [0, -1]:
        while tb:
            frame_file = path.normcase(tb[i][0])
            if not any(is_same_py_file(frame_file, f) for f in DONT_DEBUG):
                break
            del tb[i]

    # print the traceback
    if tb:
        print('Traceback (most recent call last):')
        for out in traceback.format_list(tb):
            sys.stderr.write(out)
    
    # print the exception
    for out in traceback.format_exception_only(exc_type, exc_value):
        sys.stdout.write(out) 
Example 7
Project: pythonVSCode   Author: DonJayamanne   File: visualstudio_py_debugger.py    (license) View Source Project 6 votes vote down vote up
def print_exception(exc_type, exc_value, exc_tb):
    # remove debugger frames from the top and bottom of the traceback
    tb = traceback.extract_tb(exc_tb)
    for i in [0, -1]:
        while tb:
            frame_file = path.normcase(tb[i][0])
            if not any(is_same_py_file(frame_file, f) for f in DONT_DEBUG):
                break
            del tb[i]

    # print the traceback
    if tb:
        print('Traceback (most recent call last):')
        for out in traceback.format_list(tb):
            sys.stderr.write(out)
    
    # print the exception
    for out in traceback.format_exception_only(exc_type, exc_value):
        sys.stdout.write(out) 
Example 8
Project: annotated-py-asyncio   Author: hhstore   File: futures.py    (license) View Source Project 6 votes vote down vote up
def __del__(self):
        if self.tb:
            msg = 'Future/Task exception was never retrieved\n'
            if self.source_traceback:
                src = ''.join(traceback.format_list(self.source_traceback))
                msg += 'Future/Task created at (most recent call last):\n'
                msg += '%s\n' % src.rstrip()
            msg += ''.join(self.tb).rstrip()
            self.loop.call_exception_handler({'message': msg})


#########################################
#             Future ?
#
# ??:
#   - ???
#   - Future??????iter??????
#   - ?????????:
#       - BaseEventLoop() ??, ?????
#       - Task() ??, ?????
#       - ???????, ?????
#
######################################### 
Example 9
Project: annotated-py-asyncio   Author: hhstore   File: coroutines.py    (license) View Source Project 6 votes vote down vote up
def __del__(self):
        # Be careful accessing self.gen.frame -- self.gen might not exist.
        gen = getattr(self, 'gen', None)
        frame = getattr(gen, 'gi_frame', None)
        if frame is not None and frame.f_lasti == -1:
            msg = '%r was never yielded from' % self
            tb = getattr(self, '_source_traceback', ())
            if tb:
                tb = ''.join(traceback.format_list(tb))
                msg += ('\nCoroutine object created at '
                        '(most recent call last):\n')
                msg += tb.rstrip()
            logger.error(msg)


#########################################
#             ?????
#
# ??:
#
######################################### 
Example 10
Project: Intranet-Penetration   Author: yuxiaokui   File: code.py    (license) View Source Project 6 votes vote down vote up
def showtraceback(self):
        """Display the exception that just occurred.

        We remove the first stack item because it is our own code.

        The output is written by self.write(), below.

        """
        try:
            type, value, tb = sys.exc_info()
            sys.last_type = type
            sys.last_value = value
            sys.last_traceback = tb
            tblist = traceback.extract_tb(tb)
            del tblist[:1]
            list = traceback.format_list(tblist)
            if list:
                list.insert(0, "Traceback (most recent call last):\n")
            list[len(list):] = traceback.format_exception_only(type, value)
        finally:
            tblist = tb = None
        map(self.write, list) 
Example 11
Project: MKFQ   Author: maojingios   File: code.py    (license) View Source Project 6 votes vote down vote up
def showtraceback(self):
        """Display the exception that just occurred.

        We remove the first stack item because it is our own code.

        The output is written by self.write(), below.

        """
        try:
            type, value, tb = sys.exc_info()
            sys.last_type = type
            sys.last_value = value
            sys.last_traceback = tb
            tblist = traceback.extract_tb(tb)
            del tblist[:1]
            list = traceback.format_list(tblist)
            if list:
                list.insert(0, "Traceback (most recent call last):\n")
            list[len(list):] = traceback.format_exception_only(type, value)
        finally:
            tblist = tb = None
        map(self.write, list) 
Example 12
Project: oil   Author: oilshell   File: code.py    (license) View Source Project 6 votes vote down vote up
def showtraceback(self):
        """Display the exception that just occurred.

        We remove the first stack item because it is our own code.

        The output is written by self.write(), below.

        """
        try:
            type, value, tb = sys.exc_info()
            sys.last_type = type
            sys.last_value = value
            sys.last_traceback = tb
            tblist = traceback.extract_tb(tb)
            del tblist[:1]
            list = traceback.format_list(tblist)
            if list:
                list.insert(0, "Traceback (most recent call last):\n")
            list[len(list):] = traceback.format_exception_only(type, value)
        finally:
            tblist = tb = None
        map(self.write, list) 
Example 13
Project: python2-tracer   Author: extremecoders-re   File: code.py    (license) View Source Project 6 votes vote down vote up
def showtraceback(self):
        """Display the exception that just occurred.

        We remove the first stack item because it is our own code.

        The output is written by self.write(), below.

        """
        try:
            type, value, tb = sys.exc_info()
            sys.last_type = type
            sys.last_value = value
            sys.last_traceback = tb
            tblist = traceback.extract_tb(tb)
            del tblist[:1]
            list = traceback.format_list(tblist)
            if list:
                list.insert(0, "Traceback (most recent call last):\n")
            list[len(list):] = traceback.format_exception_only(type, value)
        finally:
            tblist = tb = None
        map(self.write, list) 
Example 14
Project: sslstrip-hsts-openwrt   Author: adde88   File: code.py    (license) View Source Project 6 votes vote down vote up
def showtraceback(self):
        """Display the exception that just occurred.

        We remove the first stack item because it is our own code.

        The output is written by self.write(), below.

        """
        try:
            type, value, tb = sys.exc_info()
            sys.last_type = type
            sys.last_value = value
            sys.last_traceback = tb
            tblist = traceback.extract_tb(tb)
            del tblist[:1]
            list = traceback.format_list(tblist)
            if list:
                list.insert(0, "Traceback (most recent call last):\n")
            list[len(list):] = traceback.format_exception_only(type, value)
        finally:
            tblist = tb = None
        map(self.write, list) 
Example 15
Project: Parlay   Author: PromenadeSoftware   File: parlay_script.py    (license) View Source Project 6 votes vote down vote up
def _in_thread_run_script(self):
        """ Run the script. """
        try:
            self.run_script()

        except Exception as e:
            # handle any exception thrown
            exc_type,exc_value,exc_traceback = sys.exc_info()
            print "Exception Error:  ",  exc_value
            print e

            # print traceback, excluding this file
            traceback.print_tb(exc_traceback)
            # exc_strings = traceback.format_list(traceback.extract_tb(exc_traceback))
            # exc_strings = [s for s in exc_strings if s.find("parlay_script.py")< 0 ]
            # for s in exc_strings:
            #     print s 
Example 16
Project: specto   Author: mrknow   File: pydevconsole_code_for_ironpython.py    (license) View Source Project 6 votes vote down vote up
def showtraceback(self):
        """Display the exception that just occurred.

        We remove the first stack item because it is our own code.

        The output is written by self.write(), below.

        """
        try:
            type, value, tb = sys.exc_info()
            sys.last_type = type
            sys.last_value = value
            sys.last_traceback = tb
            tblist = traceback.extract_tb(tb)
            del tblist[:1]
            list = traceback.format_list(tblist)
            if list:
                list.insert(0, "Traceback (most recent call last):\n")
            list[len(list):] = traceback.format_exception_only(type, value)
        finally:
            tblist = tb = None
        map(self.write, list) 
Example 17
Project: specto   Author: mrknow   File: pydevconsole.py    (license) View Source Project 6 votes vote down vote up
def showtraceback(self):
        """Display the exception that just occurred."""
        #Override for avoid using sys.excepthook PY-12600
        try:
            type, value, tb = sys.exc_info()
            sys.last_type = type
            sys.last_value = value
            sys.last_traceback = tb
            tblist = traceback.extract_tb(tb)
            del tblist[:1]
            lines = traceback.format_list(tblist)
            if lines:
                lines.insert(0, "Traceback (most recent call last):\n")
            lines.extend(traceback.format_exception_only(type, value))
        finally:
            tblist = tb = None
        sys.stderr.write(''.join(lines)) 
Example 18
Project: botoflow   Author: boto   File: async_traceback.py    (license) View Source Project 6 votes vote down vote up
def format_exc(limit=None, exception=None, tb_list=None):
    """
    This is like print_exc(limit) but returns a string instead of printing to a
    file.
    """
    result = ["Traceback (most recent call last):\n"]
    if exception is None:
        exception = get_context_with_traceback(get_async_context()).exception

    if tb_list is None:
        tb_list = extract_tb(limit)

    if tb_list:
        result.extend(traceback.format_list(tb_list))
        result.extend(traceback.format_exception_only(exception.__class__,
                                                      exception))
        return result
    else:
        return None 
Example 19
Project: botoflow   Author: boto   File: exceptions.py    (license) View Source Project 6 votes vote down vote up
def format_exc(self, limit=None):
        """
        This is like exception.print_exc(limit) but returns a string instead
        of printing to a file.
        """
        result = ["Traceback (most recent call last):\n"]

        tb_list = self._traceback

        if limit is not None:
            tb_list = tb_list[-limit:]

        result.extend(traceback.format_list(tb_list))

        if self.cause is not None:
            result.extend(traceback.format_exception_only(self.cause.__class__,
                                                          self.cause))
            return result
        else:
            return result 
Example 20
Project: xxNet   Author: drzorm   File: code.py    (license) View Source Project 6 votes vote down vote up
def showtraceback(self):
        """Display the exception that just occurred.

        We remove the first stack item because it is our own code.

        The output is written by self.write(), below.

        """
        try:
            type, value, tb = sys.exc_info()
            sys.last_type = type
            sys.last_value = value
            sys.last_traceback = tb
            tblist = traceback.extract_tb(tb)
            del tblist[:1]
            list = traceback.format_list(tblist)
            if list:
                list.insert(0, "Traceback (most recent call last):\n")
            list[len(list):] = traceback.format_exception_only(type, value)
        finally:
            tblist = tb = None
        map(self.write, list) 
Example 21
Project: py-ipv8   Author: qstokkink   File: util.py    (license) View Source Project 6 votes vote down vote up
def blockingCallFromThread(reactor, f, *args, **kwargs):
    """
    Improved version of twisted's blockingCallFromThread that shows the complete
    stacktrace when an exception is raised on the reactor's thread.
    If being called from the reactor thread already, just return the result of execution of the callable.
    """
    if isInIOThread():
            return f(*args, **kwargs)
    else:
        queue = Queue.Queue()

        def _callFromThread():
            result = defer.maybeDeferred(f, *args, **kwargs)
            result.addBoth(queue.put)
        reactor.callFromThread(_callFromThread)
        result = queue.get()
        if isinstance(result, failure.Failure):
            other_thread_tb = traceback.extract_tb(result.getTracebackObject())
            this_thread_tb = traceback.extract_stack()
            logger.error("Exception raised on the reactor's thread %s: \"%s\".\n Traceback from this thread:\n%s\n"
                         " Traceback from the reactor's thread:\n %s", result.type.__name__, result.getErrorMessage(),
                         ''.join(traceback.format_list(this_thread_tb)), ''.join(traceback.format_list(other_thread_tb)))
            result.raiseException()
        return result 
Example 22
Project: py-ipv8   Author: qstokkink   File: base.py    (license) View Source Project 6 votes vote down vote up
def setUpClass(cls):
        cls.__lockup_timestamp__ = time.time()
        def check_twisted():
            while time.time() - cls.__lockup_timestamp__ < cls.MAX_TEST_TIME:
                time.sleep(2)
                # If the test class completed normally, exit
                if not cls.__testing__:
                    return
            # If we made it here, there is a serious issue which we cannot recover from.
            # Most likely the Twisted threadpool got into a deadlock while shutting down.
            import os, traceback
            print >> sys.stderr, "The test-suite locked up! Force quitting! Thread dump:"
            for tid, stack in sys._current_frames().items():
                if tid != threading.currentThread().ident:
                    print >> sys.stderr, "THREAD#%d" % tid
                    for line in traceback.format_list(traceback.extract_stack(stack)):
                        print >> sys.stderr, "|", line[:-1].replace('\n', '\n|   ')
            os._exit(1)
        t = threading.Thread(target=check_twisted)
        t.daemon = True
        t.start() 
Example 23
Project: HomeAutomation   Author: gs2671   File: visualstudio_py_debugger.py    (license) View Source Project 6 votes vote down vote up
def print_exception(exc_type, exc_value, exc_tb):
    # remove debugger frames from the top and bottom of the traceback
    tb = traceback.extract_tb(exc_tb)
    for i in [0, -1]:
        while tb:
            frame_file = path.normcase(tb[i][0])
            if not any(is_same_py_file(frame_file, f) for f in DONT_DEBUG):
                break
            del tb[i]

    # print the traceback
    if tb:
        print('Traceback (most recent call last):')
        for out in traceback.format_list(tb):
            sys.stderr.write(out)
    
    # print the exception
    for out in traceback.format_exception_only(exc_type, exc_value):
        sys.stdout.write(out) 
Example 24
Project: ndk-python   Author: gittor   File: code.py    (license) View Source Project 6 votes vote down vote up
def showtraceback(self):
        """Display the exception that just occurred.

        We remove the first stack item because it is our own code.

        The output is written by self.write(), below.

        """
        try:
            type, value, tb = sys.exc_info()
            sys.last_type = type
            sys.last_value = value
            sys.last_traceback = tb
            tblist = traceback.extract_tb(tb)
            del tblist[:1]
            list = traceback.format_list(tblist)
            if list:
                list.insert(0, "Traceback (most recent call last):\n")
            list[len(list):] = traceback.format_exception_only(type, value)
        finally:
            tblist = tb = None
        map(self.write, list) 
Example 25
Project: AutoDiff   Author: icewall   File: visualstudio_py_debugger.py    (license) View Source Project 6 votes vote down vote up
def print_exception():
    # count the debugger frames to be removed
    tb = traceback.extract_tb(sys.exc_info()[2])
    debugger_count = len(tb)
    while debugger_count:
        if is_same_py_file(tb[debugger_count - 1][0], __file__):
            break
        debugger_count -= 1
        
    # print the traceback
    tb = tb[debugger_count:]
    if tb:
        print('Traceback (most recent call last):')
        for out in traceback.format_list(tb):
            sys.stdout.write(out)
    
    # print the exception
    for out in traceback.format_exception_only(sys.exc_info()[0], sys.exc_info()[1]):
        sys.stdout.write(out) 
Example 26
Project: xidian-sfweb   Author: Gear420   File: visualstudio_py_debugger.py    (license) View Source Project 6 votes vote down vote up
def print_exception(exc_type, exc_value, exc_tb):
    # remove debugger frames from the top and bottom of the traceback
    tb = traceback.extract_tb(exc_tb)
    for i in [0, -1]:
        while tb:
            frame_file = path.normcase(tb[i][0])
            if not any(is_same_py_file(frame_file, f) for f in DONT_DEBUG):
                break
            del tb[i]

    # print the traceback
    if tb:
        print('Traceback (most recent call last):')
        for out in traceback.format_list(tb):
            sys.stderr.write(out)
    
    # print the exception
    for out in traceback.format_exception_only(exc_type, exc_value):
        sys.stdout.write(out) 
Example 27
Project: empyrion-python-api   Author: huhlig   File: code.py    (license) View Source Project 6 votes vote down vote up
def showtraceback(self):
        """Display the exception that just occurred.

        We remove the first stack item because it is our own code.

        The output is written by self.write(), below.

        """
        try:
            type, value, tb = sys.exc_info()
            sys.last_type = type
            sys.last_value = value
            sys.last_traceback = tb
            tblist = traceback.extract_tb(tb)
            del tblist[:1]
            list = traceback.format_list(tblist)
            if list:
                list.insert(0, "Traceback (most recent call last):\n")
            list[len(list):] = traceback.format_exception_only(type, value)
        finally:
            tblist = tb = None
        map(self.write, list) 
Example 28
Project: skojjt   Author: martin-green   File: visualstudio_py_debugger.py    (license) View Source Project 6 votes vote down vote up
def print_exception(exc_type, exc_value, exc_tb):
    # remove debugger frames from the top and bottom of the traceback
    tb = traceback.extract_tb(exc_tb)
    for i in [0, -1]:
        while tb:
            frame_file = path.normcase(tb[i][0])
            if not any(is_same_py_file(frame_file, f) for f in DONT_DEBUG):
                break
            del tb[i]

    # print the traceback
    if tb:
        print('Traceback (most recent call last):')
        for out in traceback.format_list(tb):
            sys.stderr.write(out)
    
    # print the exception
    for out in traceback.format_exception_only(exc_type, exc_value):
        sys.stdout.write(out) 
Example 29
Project: zenchmarks   Author: squeaky-pl   File: monitor.py    (license) View Source Project 6 votes vote down vote up
def _format_stack(task):
    '''
    Formats a traceback from a stack of coroutines/generators
    '''
    extracted_list = []
    checked = set()
    for f in _get_stack(task):
        lineno = f.f_lineno
        co = f.f_code
        filename = co.co_filename
        name = co.co_name
        if filename not in checked:
            checked.add(filename)
            linecache.checkcache(filename)
        line = linecache.getline(filename, lineno, f.f_globals)
        extracted_list.append((filename, lineno, name, line))
    if not extracted_list:
        resp = 'No stack for %r' % task
    else:
        resp = 'Stack for %r (most recent call last):\n' % task
        resp += ''.join(traceback.format_list(extracted_list))
    return resp 
Example 30
Project: aiomonitor   Author: aio-libs   File: utils.py    (license) View Source Project 6 votes vote down vote up
def _format_stack(task):
    extracted_list = []
    checked = set()
    for f in _get_stack(task):
        lineno = f.f_lineno
        co = f.f_code
        filename = co.co_filename
        name = co.co_name
        if filename not in checked:
            checked.add(filename)
            linecache.checkcache(filename)
        line = linecache.getline(filename, lineno, f.f_globals)
        extracted_list.append((filename, lineno, name, line))
    if not extracted_list:
        resp = 'No stack for %r' % task
    else:
        resp = 'Stack for %r (most recent call last):\n' % task
        resp += ''.join(traceback.format_list(extracted_list))
    return resp 
Example 31
Project: easypy   Author: weka-io   File: humanize.py    (license) View Source Project 6 votes vote down vote up
def format_thread_stack(frame, skip_modules=[threading]):
    stack = traceback.extract_stack(frame)
    if skip_modules:
        itr_stack = iter(stack)
        items = []
        fnames = {m.__file__ for m in ilistify(skip_modules)}
        # skip everything until after specified module
        for fname, *_ in itr_stack:
            if fname in fnames:
                items.append([fname] + _)
                for i, (fname, *_) in enumerate(itr_stack, 1):
                    if fname not in fnames:
                        if i > 1:
                            items.append([last_fname, "...(%s)" % i, "---", "---"])
                        break
                    last_fname = fname
            items.append([fname] + _)
        if len(items) <= 2:
            items = stack
    else:
        items = stack

    return ''.join(traceback.format_list(items)) 
Example 32
Project: Docker-XX-Net   Author: kuanghy   File: code.py    (license) View Source Project 6 votes vote down vote up
def showtraceback(self):
        """Display the exception that just occurred.

        We remove the first stack item because it is our own code.

        The output is written by self.write(), below.

        """
        try:
            type, value, tb = sys.exc_info()
            sys.last_type = type
            sys.last_value = value
            sys.last_traceback = tb
            tblist = traceback.extract_tb(tb)
            del tblist[:1]
            list = traceback.format_list(tblist)
            if list:
                list.insert(0, "Traceback (most recent call last):\n")
            list[len(list):] = traceback.format_exception_only(type, value)
        finally:
            tblist = tb = None
        map(self.write, list) 
Example 33
Project: w4py   Author: Cito   File: ThreadedAppServer.py    (license) View Source Project 6 votes vote down vote up
def threadDump(signum, frame):
    """Signal handler for dumping thread stack frames to stdout."""
    print
    print "App server has been signaled to attempt a thread dump."
    print
    print "Thread stack frame dump at", asclocaltime()
    sys.stdout.flush()
    frames = sys._current_frames()
    print
    print "-" * 79
    print
    for threadID in sorted(frames):
        frame = frames[threadID]
        print "Thread ID: %d (reference count = %d)" % (
            threadID, sys.getrefcount(frame))
        print ''.join(traceback.format_list(traceback.extract_stack(frame)))
    print "-" * 79
    sys.stdout.flush() 
Example 34
Project: DjangoWebProject   Author: wrkettlitz   File: visualstudio_py_debugger.py    (license) View Source Project 6 votes vote down vote up
def print_exception(exc_type, exc_value, exc_tb):
    # remove debugger frames from the top and bottom of the traceback
    tb = traceback.extract_tb(exc_tb)
    for i in [0, -1]:
        while tb:
            frame_file = path.normcase(tb[i][0])
            if not any(is_same_py_file(frame_file, f) for f in DONT_DEBUG):
                break
            del tb[i]

    # print the traceback
    if tb:
        print('Traceback (most recent call last):')
        for out in traceback.format_list(tb):
            sys.stderr.write(out)
    
    # print the exception
    for out in traceback.format_exception_only(exc_type, exc_value):
        sys.stdout.write(out) 
Example 35
Project: ApiRestPythonTest   Author: rvfvazquez   File: visualstudio_py_debugger.py    (license) View Source Project 6 votes vote down vote up
def print_exception(exc_type, exc_value, exc_tb):
    # remove debugger frames from the top and bottom of the traceback
    tb = traceback.extract_tb(exc_tb)
    for i in [0, -1]:
        while tb:
            frame_file = path.normcase(tb[i][0])
            if not any(is_same_py_file(frame_file, f) for f in DONT_DEBUG):
                break
            del tb[i]

    # print the traceback
    if tb:
        print('Traceback (most recent call last):')
        for out in traceback.format_list(tb):
            sys.stderr.write(out)
    
    # print the exception
    for out in traceback.format_exception_only(exc_type, exc_value):
        sys.stdout.write(out) 
Example 36
Project: kinect-2-libras   Author: inessadl   File: code.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def showtraceback(self):
        """Display the exception that just occurred.

        We remove the first stack item because it is our own code.

        The output is written by self.write(), below.

        """
        try:
            type, value, tb = sys.exc_info()
            sys.last_type = type
            sys.last_value = value
            sys.last_traceback = tb
            tblist = traceback.extract_tb(tb)
            del tblist[:1]
            list = traceback.format_list(tblist)
            if list:
                list.insert(0, "Traceback (most recent call last):\n")
            list[len(list):] = traceback.format_exception_only(type, value)
        finally:
            tblist = tb = None
        map(self.write, list) 
Example 37
Project: git-stacktrace   Author: pinterest   File: parse_trace.py    (license) View Source Project 5 votes vote down vote up
def format_lines(self):
        lines = self.traceback_format()
        return ''.join(traceback.format_list(lines)) 
Example 38
Project: ave   Author: sonyxperiadev   File: exceptions.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 5 votes vote down vote up
def format_trace(self):
        if self.has_trace():
            # convert trace entries back to tuples. the trace member was
            # set by the server side rpc mechanism. rpc messages cannot
            # contain tuples (incompatible with JSON) so the entries were
            # converted to lists.
            convert = []
            for entry in self.trace:
                convert.append(tuple(entry))
            formatted = traceback.format_list(convert)
            return ''.join(formatted)
        return '' 
Example 39
Project: ave   Author: sonyxperiadev   File: exceptions.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 5 votes vote down vote up
def format_trace(self):
        if self.has_trace():
            # convert trace entries back to tuples. the trace member was
            # set by the server side rpc mechanism. rpc messages cannot
            # contain tuples (incompatible with JSON) so the entries were
            # converted to lists.
            convert = []
            for entry in self.trace:
                convert.append(tuple(entry))
            formatted = traceback.format_list(convert)
            return ''.join(formatted)
        return '' 
Example 40
Project: abusehelper   Author: Exploit-install   File: config.py    (license) View Source Project 5 votes vote down vote up
def follow_config(path, poll_interval=1.0, force_interval=30.0):
    last_reload = -float("inf")
    last_mtime = None
    last_error_msg = None

    abspath = os.path.abspath(path)
    while True:
        now = time.time()
        if now < last_reload:
            last_reload = now

        mtime = os.path.getmtime(abspath)
        if now > last_reload + force_interval or last_mtime != mtime:
            try:
                configs = load_configs(abspath)
            except Exception:
                _, exc_value, exc_tb = sys.exc_info()

                stack = traceback.extract_tb(exc_tb)
                stack = stack[1:]  # Make the traceback flatter by discarding the current stack frame

                error_msg = "Could not load {path!r} (most recent call last):\n{stack}\n{exception}".format(
                    path=abspath,
                    stack="".join(traceback.format_list(stack)).rstrip(),
                    exception=utils.format_exception(exc_value)
                )

                if error_msg != last_error_msg:
                    yield idiokit.send(False, error_msg)
                    last_error_msg = error_msg
                    last_mtime = None
            else:
                yield idiokit.send(True, configs)
                last_error_msg = None
                last_mtime = mtime
                last_reload = now
        yield idiokit.sleep(poll_interval) 
Example 41
Project: bothub-sdk-python   Author: bothub-studio   File: utils.py    (license) View Source Project 5 votes vote down vote up
def traceback_to_string(exc, tb=None):
    _tb = tb or exc.__traceback__
    s = traceback.extract_stack()[:-3] + traceback.extract_tb(_tb)
    l = traceback.format_list(s)
    return ''.join(l) + '\\n  {} {}'.format(exc.__class__, exc) 
Example 42
Project: CodingDojo   Author: ComputerSocietyUNB   File: debug.py    (license) View Source Project 5 votes vote down vote up
def format_exception(self):
        """
        Return the same data as from traceback.format_exception.
        """
        import traceback
        frames = self.get_traceback_frames()
        tb = [(f['filename'], f['lineno'], f['function'], f['context_line']) for f in frames]
        list = ['Traceback (most recent call last):\n']
        list += traceback.format_list(tb)
        list += traceback.format_exception_only(self.exc_type, self.exc_value)
        return list 
Example 43
Project: hostapd-mana   Author: adde88   File: pywidgets.py    (license) View Source Project 5 votes vote down vote up
def console(self, message):
        self.set_point(self.get_length())
        self.freeze()
        previous_kind = None
        style = self.get_style()
        style_cache = {}
        try:
            for element in message:
                if element[0] == 'exception':
                    s = traceback.format_list(element[1]['traceback'])
                    s.extend(element[1]['exception'])
                    s = string.join(s, '')
                else:
                    s = element[1]

                if element[0] != previous_kind:
                    style = style_cache.get(element[0], None)
                    if style is None:
                        gtk.rc_parse_string(
                            'widget \"Manhole.*.Console\" '
                            'style \"Console_%s\"\n'
                            % (element[0]))
                        self.set_rc_style()
                        style_cache[element[0]] = style = self.get_style()
                # XXX: You'd think we'd use style.bg instead of 'None'
                # here, but that doesn't seem to match the color of
                # the backdrop.
                self.insert(style.font, style.fg[gtk.STATE_NORMAL],
                            None, s)
                previous_kind = element[0]
            l = self.get_length()
            diff = self.maxBufSz - l
            if diff < 0:
                diff = - diff
                self.delete_text(0,diff)
        finally:
            self.thaw()
        a = self.get_vadjustment()
        a.set_value(a.upper - a.page_size) 
Example 44
Project: pythonVSCode   Author: DonJayamanne   File: visualstudio_py_launcher_nodebug.py    (license) View Source Project 5 votes vote down vote up
def handle_exception(exc_type, exc_value, exc_tb):
    # Specifies list of files not to display in stack trace.
    do_not_debug = [__file__, _vspu.__file__]
    if sys.version_info >= (3, 3):
        do_not_debug.append('<frozen importlib._bootstrap>')
    if sys.version_info >= (3, 5):
        do_not_debug.append('<frozen importlib._bootstrap_external>')

    # Remove debugger frames from the top and bottom of the traceback.
    tb = traceback.extract_tb(exc_tb)
    for i in [0, -1]:
        while tb:
            frame_file = path.normcase(tb[i][0])
            if not any(is_same_py_file(frame_file, f) for f in do_not_debug):
                break
            del tb[i]

    # Print the traceback.
    if tb:
        sys.stderr.write('Traceback (most recent call last):')
        for out in traceback.format_list(tb):
            sys.stderr.write(out)
            sys.stderr.flush()

    # Print the exception.
    for out in traceback.format_exception_only(exc_type, exc_value):
        sys.stderr.write(out)
        sys.stderr.flush() 
Example 45
Project: Qyoutube-dl   Author: lzambella   File: YoutubeDL.py    (license) View Source Project 5 votes vote down vote up
def trouble(self, message=None, tb=None):
        """Determine action to take when a download problem appears.

        Depending on if the downloader has been configured to ignore
        download errors or not, this method may throw an exception or
        not when errors are found, after printing the message.

        tb, if given, is additional traceback information.
        """
        if message is not None:
            self.to_stderr(message)
        if self.params.get('verbose'):
            if tb is None:
                if sys.exc_info()[0]:  # if .trouble has been called from an except block
                    tb = ''
                    if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
                        tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
                    tb += encode_compat_str(traceback.format_exc())
                else:
                    tb_data = traceback.format_list(traceback.extract_stack())
                    tb = ''.join(tb_data)
            self.to_stderr(tb)
        if not self.params.get('ignoreerrors', False):
            if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
                exc_info = sys.exc_info()[1].exc_info
            else:
                exc_info = sys.exc_info()
            raise DownloadError(message, exc_info)
        self._download_retcode = 1 
Example 46
Project: watchmen   Author: lycclsltt   File: exceptions.py    (license) View Source Project 5 votes vote down vote up
def get_trace(self):
        '''This returns an abbreviated stack trace with lines that only concern
        the caller. In other words, the stack trace inside the Pexpect module
        is not included. '''

        tblist = traceback.extract_tb(sys.exc_info()[2])
        tblist = [item for item in tblist if ('pexpect/__init__' not in item[0])
                                           and ('pexpect/expect' not in item[0])]
        tblist = traceback.format_list(tblist)
        return ''.join(tblist) 
Example 47
Project: django-eraserhead   Author: dizballanze   File: queryset_storage.py    (license) View Source Project 5 votes vote down vote up
def _print_traceback(self):
        base_path = getattr(settings, 'ERASERHEAD_TRACEBACK_BASE_PATH', None)
        for trace_line in traceback.format_list(self._traceback):
            if base_path and (base_path not in trace_line):
                continue
            print("\t" + trace_line.strip().replace('\n', '\n\t')) 
Example 48
Project: pytest-ui   Author: martinsmid   File: ui.py    (license) View Source Project 5 votes vote down vote up
def set_test_result(self, test_id, result_state, output, when, outcome,
                        exc_type=None, exc_value=None, extracted_traceback=None, last_failed_exempt=None):
        if not test_id in self.test_data:
            self.test_data[test_id] = {
                'id': test_id
            }

        if extracted_traceback:
            output += ''.join(
                traceback.format_list(extracted_traceback) +
                [exc_value]
            )

        test_data = self.test_data[test_id]
        test_data['exc_type'] = exc_type
        test_data['exc_value'] = exc_value
        test_data['exc_tb'] = extracted_traceback
        if when == 'call' and last_failed_exempt is not None:
            test_data['last_failed_exempt'] = last_failed_exempt

        # Ignore success, except for the 'call' step
        # ignore successive failure, take only the first
        if (outcome != 'passed' or when == 'call') \
            and not test_data.get('result_state'):
            test_data['result_state'] = result_state
            test_data['output'] = output
            self.ui.update_test_result(test_data)

        if when == 'teardown':
            test_data['runstate'] = None
            self.ui.update_test_line(test_data) 
Example 49
Project: dataScryer   Author: Griesbacher   File: dataScryer.py    (license) View Source Project 5 votes vote down vote up
def warn(*args, **kwargs):
    tb = traceback.extract_stack()
    _old_warn(*args, **kwargs)
    print("".join(traceback.format_list(tb)[:-1])) 
Example 50
Project: youtube_downloader   Author: aksinghdce   File: YoutubeDL.py    (license) View Source Project 5 votes vote down vote up
def trouble(self, message=None, tb=None):
        """Determine action to take when a download problem appears.

        Depending on if the downloader has been configured to ignore
        download errors or not, this method may throw an exception or
        not when errors are found, after printing the message.

        tb, if given, is additional traceback information.
        """
        if message is not None:
            self.to_stderr(message)
        if self.params.get('verbose'):
            if tb is None:
                if sys.exc_info()[0]:  # if .trouble has been called from an except block
                    tb = ''
                    if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
                        tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
                    tb += encode_compat_str(traceback.format_exc())
                else:
                    tb_data = traceback.format_list(traceback.extract_stack())
                    tb = ''.join(tb_data)
            self.to_stderr(tb)
        if not self.params.get('ignoreerrors', False):
            if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
                exc_info = sys.exc_info()[1].exc_info
            else:
                exc_info = sys.exc_info()
            raise DownloadError(message, exc_info)
        self._download_retcode = 1