Python sys 模块,last_traceback() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sys.last_traceback()

项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def verifyStderr(self, method, successRe) :
        """
        Call method() while capturing sys.stderr output internally and
        call self.fail() if successRe.search() does not match the stderr
        output.  This is used to test for uncatchable exceptions.
        """
        stdErr = sys.stderr
        sys.stderr = StringIO()
        try:
            method()
        finally:
            temp = sys.stderr
            sys.stderr = stdErr
            errorOut = temp.getvalue()
            if not successRe.search(errorOut) :
                self.fail("unexpected stderr output:\n"+errorOut)
        if sys.version_info < (3, 0) :  # XXX: How to do this in Py3k ???
            sys.exc_traceback = sys.last_traceback = None
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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)
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
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)
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
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)
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def debugger(self,force=False):
        """Call the pdb debugger.

        Keywords:

          - force(False): by default, this routine checks the instance call_pdb
            flag and does not actually invoke the debugger if the flag is false.
            The 'force' option forces the debugger to activate even if the flag
            is false.
        """

        if not (force or self.call_pdb):
            return

        if not hasattr(sys,'last_traceback'):
            error('No traceback has been produced, nothing to debug.')
            return

        self.InteractiveTB.debugger(force=True)

    #-------------------------------------------------------------------------
    # Things related to IPython's various namespaces
    #-------------------------------------------------------------------------
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def print_exception():
    import linecache
    linecache.checkcache()
    flush_stdout()
    efile = sys.stderr
    typ, val, tb = excinfo = sys.exc_info()
    sys.last_type, sys.last_value, sys.last_traceback = excinfo
    tbe = traceback.extract_tb(tb)
    print('Traceback (most recent call last):', file=efile)
    exclude = ("run.py", "rpc.py", "threading.py", "queue.py",
               "RemoteDebugger.py", "bdb.py")
    cleanup_traceback(tbe, exclude)
    traceback.print_list(tbe, file=efile)
    lines = traceback.format_exception_only(typ, val)
    for line in lines:
        print(line, end='', file=efile)
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def verifyStderr(self, method, successRe) :
        """
        Call method() while capturing sys.stderr output internally and
        call self.fail() if successRe.search() does not match the stderr
        output.  This is used to test for uncatchable exceptions.
        """
        stdErr = sys.stderr
        sys.stderr = StringIO()
        try:
            method()
        finally:
            temp = sys.stderr
            sys.stderr = stdErr
            errorOut = temp.getvalue()
            if not successRe.search(errorOut) :
                self.fail("unexpected stderr output:\n"+errorOut)
        if sys.version_info < (3, 0) :  # XXX: How to do this in Py3k ???
            sys.exc_traceback = sys.last_traceback = None
项目:oil    作者:oilshell    | 项目源码 | 文件源码
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)
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def _stack_viewer(parent):  # htest #
    root = tk.Tk()
    root.title("Test StackViewer")
    width, height, x, y = list(map(int, re.split('[x+]', parent.geometry())))
    root.geometry("+%d+%d"%(x, y + 150))
    flist = PyShellFileList(root)
    try: # to obtain a traceback object
        intentional_name_error
    except NameError:
        exc_type, exc_value, exc_tb = sys.exc_info()

    # inject stack trace to sys
    sys.last_type = exc_type
    sys.last_value = exc_value
    sys.last_traceback = exc_tb

    StackBrowser(root, flist=flist, top=root, tb=exc_tb)

    # restore sys to original state
    del sys.last_type
    del sys.last_value
    del sys.last_traceback
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def verifyStderr(self, method, successRe) :
        """
        Call method() while capturing sys.stderr output internally and
        call self.fail() if successRe.search() does not match the stderr
        output.  This is used to test for uncatchable exceptions.
        """
        stdErr = sys.stderr
        sys.stderr = StringIO()
        try:
            method()
        finally:
            temp = sys.stderr
            sys.stderr = stdErr
            errorOut = temp.getvalue()
            if not successRe.search(errorOut) :
                self.fail("unexpected stderr output:\n"+errorOut)
        if sys.version_info < (3, 0) :  # XXX: How to do this in Py3k ???
            sys.exc_traceback = sys.last_traceback = None
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
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)
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def _stack_viewer(parent):  # htest #
    root = tk.Tk()
    root.title("Test StackViewer")
    width, height, x, y = list(map(int, re.split('[x+]', parent.geometry())))
    root.geometry("+%d+%d"%(x, y + 150))
    flist = PyShellFileList(root)
    try: # to obtain a traceback object
        intentional_name_error
    except NameError:
        exc_type, exc_value, exc_tb = sys.exc_info()

    # inject stack trace to sys
    sys.last_type = exc_type
    sys.last_value = exc_value
    sys.last_traceback = exc_tb

    StackBrowser(root, flist=flist, top=root, tb=exc_tb)

    # restore sys to original state
    del sys.last_type
    del sys.last_value
    del sys.last_traceback
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def verifyStderr(self, method, successRe) :
        """
        Call method() while capturing sys.stderr output internally and
        call self.fail() if successRe.search() does not match the stderr
        output.  This is used to test for uncatchable exceptions.
        """
        stdErr = sys.stderr
        sys.stderr = StringIO()
        try:
            method()
        finally:
            temp = sys.stderr
            sys.stderr = stdErr
            errorOut = temp.getvalue()
            if not successRe.search(errorOut) :
                self.fail("unexpected stderr output:\n"+errorOut)
        if sys.version_info < (3, 0) :  # XXX: How to do this in Py3k ???
            sys.exc_traceback = sys.last_traceback = None
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
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)
项目:of    作者:OptimalBPM    | 项目源码 | 文件源码
def step_impl(context):
    """

    :type context behave.runner.Context

    """

    _json_data = json_load_file(os.path.join(script_location, "../data/bad_json.json"))

    try:

        context.schema_tools.apply(_json_data)
    except Exception as e:
        if str(e)[:32] == "'canRead' is a required property":
            ok_(True)
        else:
            if hasattr(sys, "last_traceback"):
                _traceback = traceback.print_tb(sys.last_traceback)
            else:
                _traceback = "Not available"

            ok_(False, "Error: " + str(e) + "\nTraceback:" + _traceback)
项目:specto    作者:mrknow    | 项目源码 | 文件源码
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)
项目:specto    作者:mrknow    | 项目源码 | 文件源码
def showsyntaxerror(self, filename=None):
        """Display the syntax error that just occurred."""
        #Override for avoid using sys.excepthook PY-12600
        type, value, tb = sys.exc_info()
        sys.last_type = type
        sys.last_value = value
        sys.last_traceback = tb
        if filename and type is SyntaxError:
            # Work hard to stuff the correct filename in the exception
            try:
                msg, (dummy_filename, lineno, offset, line) = value.args
            except ValueError:
                # Not the format we expect; leave it alone
                pass
            else:
                # Stuff in the right filename
                value = SyntaxError(msg, (filename, lineno, offset, line))
                sys.last_value = value
        list = traceback.format_exception_only(type, value)
        sys.stderr.write(''.join(list))
项目:specto    作者:mrknow    | 项目源码 | 文件源码
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))
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
def post_mortem(t=None):
    if t is None:
        t = sys.exc_info()[2] # Will be valid if we are called from an except handler.
    if t is None:
        try:
            t = sys.last_traceback
        except AttributeError:
            print "No traceback can be found from which to perform post-mortem debugging!"
            print "No debugging can continue"
            return
    p = _GetCurrentDebugger()
    if p.frameShutdown: return # App closing
    # No idea why I need to settrace to None - it should have been reset by now?
    sys.settrace(None)
    p.reset()
    while t.tb_next != None: t = t.tb_next
    p.bAtPostMortem = 1
    p.prep_run(None)
    try:
        p.interaction(t.tb_frame, t)
    finally:
        t = None
        p.bAtPostMortem = 0
        p.done_run()
项目:xxNet    作者:drzorm    | 项目源码 | 文件源码
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)
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
def post_mortem(t=None):
    if t is None:
        t = sys.exc_info()[2] # Will be valid if we are called from an except handler.
    if t is None:
        try:
            t = sys.last_traceback
        except AttributeError:
            print("No traceback can be found from which to perform post-mortem debugging!")
            print("No debugging can continue")
            return
    p = _GetCurrentDebugger()
    if p.frameShutdown: return # App closing
    # No idea why I need to settrace to None - it should have been reset by now?
    sys.settrace(None)
    p.reset()
    while t.tb_next != None: t = t.tb_next
    p.bAtPostMortem = 1
    p.prep_run(None)
    try:
        p.interaction(t.tb_frame, t)
    finally:
        t = None
        p.bAtPostMortem = 0
        p.done_run()
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def debugger(self,force=False):
        """Call the pdb debugger.

        Keywords:

          - force(False): by default, this routine checks the instance call_pdb
            flag and does not actually invoke the debugger if the flag is false.
            The 'force' option forces the debugger to activate even if the flag
            is false.
        """

        if not (force or self.call_pdb):
            return

        if not hasattr(sys,'last_traceback'):
            error('No traceback has been produced, nothing to debug.')
            return

        self.InteractiveTB.debugger(force=True)

    #-------------------------------------------------------------------------
    # Things related to IPython's various namespaces
    #-------------------------------------------------------------------------
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def showsyntaxerror(self, filename=None):
        """Display the syntax error that just occurred.

        This doesn't display a stack trace because there isn't one.

        If a filename is given, it is stuffed in the exception instead
        of what was there before (because Python's parser always uses
        "<string>" when reading from a string).
        """
        etype, value, last_traceback = self._get_exc_info()

        if filename and issubclass(etype, SyntaxError):
            try:
                value.filename = filename
            except:
                # Not the format we expect; leave it alone
                pass

        stb = self.SyntaxTB.structured_traceback(etype, value, [])
        self._showtraceback(etype, value, stb)

    # This is overridden in TerminalInteractiveShell to show a message about
    # the %paste magic.
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def _stack_viewer(parent):
    root = tk.Tk()
    root.title("Test StackViewer")
    width, height, x, y = list(map(int, re.split('[x+]', parent.geometry())))
    root.geometry("+%d+%d"%(x, y + 150))
    flist = PyShellFileList(root)
    try: # to obtain a traceback object
        intentional_name_error
    except NameError:
        exc_type, exc_value, exc_tb = sys.exc_info()

    # inject stack trace to sys
    sys.last_type = exc_type
    sys.last_value = exc_value
    sys.last_traceback = exc_tb

    StackBrowser(root, flist=flist, top=root, tb=exc_tb)

    # restore sys to original state
    del sys.last_type
    del sys.last_value
    del sys.last_traceback
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
def print_exception():
    import linecache
    linecache.checkcache()
    flush_stdout()
    efile = sys.stderr
    typ, val, tb = excinfo = sys.exc_info()
    sys.last_type, sys.last_value, sys.last_traceback = excinfo
    tbe = traceback.extract_tb(tb)
    print>>efile, '\nTraceback (most recent call last):'
    exclude = ("run.py", "rpc.py", "threading.py", "Queue.py",
               "RemoteDebugger.py", "bdb.py")
    cleanup_traceback(tbe, exclude)
    traceback.print_list(tbe, file=efile)
    lines = traceback.format_exception_only(typ, val)
    for line in lines:
        print>>efile, line,
项目:empyrion-python-api    作者:huhlig    | 项目源码 | 文件源码
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)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def _stack_viewer(parent):
    root = tk.Tk()
    root.title("Test StackViewer")
    width, height, x, y = list(map(int, re.split('[x+]', parent.geometry())))
    root.geometry("+%d+%d"%(x, y + 150))
    flist = PyShellFileList(root)
    try: # to obtain a traceback object
        intentional_name_error
    except NameError:
        exc_type, exc_value, exc_tb = sys.exc_info()

    # inject stack trace to sys
    sys.last_type = exc_type
    sys.last_value = exc_value
    sys.last_traceback = exc_tb

    StackBrowser(root, flist=flist, top=root, tb=exc_tb)

    # restore sys to original state
    del sys.last_type
    del sys.last_value
    del sys.last_traceback
项目:python-xdis    作者:rocky    | 项目源码 | 文件源码
def test_dis_traceback(self):
            self.skipTest('Fix up ability to disassemble straceback')
            return
            try:
                del sys.last_traceback
            except AttributeError:
                pass

            try:
                1/0
            except Exception as e:
                tb = e.__traceback__
                sys.last_traceback = tb

            tb_dis = self.get_disassemble_as_string(tb.tb_frame.f_code, tb.tb_lasti)
            self.do_disassembly_test(None, tb_dis)
项目:python-xdis    作者:rocky    | 项目源码 | 文件源码
def test_dis_traceback(self):
            self.skipTest('Fix up ability to disassemble straceback')
            return
            try:
                del sys.last_traceback
            except AttributeError:
                pass

            try:
                1/0
            except Exception as e:
                tb = e.__traceback__
                sys.last_traceback = tb

            tb_dis = self.get_disassemble_as_string(tb.tb_frame.f_code, tb.tb_lasti)
            self.dis_disassembly34(None, tb_dis)
项目:GSM-scanner    作者:yosriayed    | 项目源码 | 文件源码
def test_store_except_info_on_eror():
    """ Test that upon test failure, the exception info is stored on
    sys.last_traceback and friends.
    """
    # Simulate item that raises a specific exception
    class ItemThatRaises:
        def runtest(self):
            raise IndexError('TEST')
    try:
        runner.pytest_runtest_call(ItemThatRaises())
    except IndexError:
        pass
    # Check that exception info is stored on sys
    assert sys.last_type is IndexError
    assert sys.last_value.args[0] == 'TEST'
    assert sys.last_traceback
项目:Docker-XX-Net    作者:kuanghy    | 项目源码 | 文件源码
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)
项目:blender    作者:gastrodia    | 项目源码 | 文件源码
def debugger(self,force=False):
        """Call the pdb debugger.

        Keywords:

          - force(False): by default, this routine checks the instance call_pdb
            flag and does not actually invoke the debugger if the flag is false.
            The 'force' option forces the debugger to activate even if the flag
            is false.
        """

        if not (force or self.call_pdb):
            return

        if not hasattr(sys,'last_traceback'):
            error('No traceback has been produced, nothing to debug.')
            return

        self.InteractiveTB.debugger(force=True)

    #-------------------------------------------------------------------------
    # Things related to IPython's various namespaces
    #-------------------------------------------------------------------------
项目:blender    作者:gastrodia    | 项目源码 | 文件源码
def showsyntaxerror(self, filename=None):
        """Display the syntax error that just occurred.

        This doesn't display a stack trace because there isn't one.

        If a filename is given, it is stuffed in the exception instead
        of what was there before (because Python's parser always uses
        "<string>" when reading from a string).
        """
        etype, value, last_traceback = self._get_exc_info()

        if filename and issubclass(etype, SyntaxError):
            try:
                value.filename = filename
            except:
                # Not the format we expect; leave it alone
                pass

        stb = self.SyntaxTB.structured_traceback(etype, value, [])
        self._showtraceback(etype, value, stb)

    # This is overridden in TerminalInteractiveShell to show a message about
    # the %paste magic.
项目:yatta_reader    作者:sound88    | 项目源码 | 文件源码
def debugger(self,force=False):
        """Call the pdb debugger.

        Keywords:

          - force(False): by default, this routine checks the instance call_pdb
            flag and does not actually invoke the debugger if the flag is false.
            The 'force' option forces the debugger to activate even if the flag
            is false.
        """

        if not (force or self.call_pdb):
            return

        if not hasattr(sys,'last_traceback'):
            error('No traceback has been produced, nothing to debug.')
            return

        self.InteractiveTB.debugger(force=True)

    #-------------------------------------------------------------------------
    # Things related to IPython's various namespaces
    #-------------------------------------------------------------------------
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def pm():
    post_mortem(sys.last_traceback)


# Main program for testing
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def print_last(limit=None, file=None):
    """This is a shorthand for 'print_exception(sys.last_type,
    sys.last_value, sys.last_traceback, limit, file)'."""
    if not hasattr(sys, "last_type"):
        raise ValueError("no last exception")
    if file is None:
        file = sys.stderr
    print_exception(sys.last_type, sys.last_value, sys.last_traceback,
                    limit, file)
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def distb(tb=None):
    """Disassemble a traceback (default: last traceback)."""
    if tb is None:
        try:
            tb = sys.last_traceback
        except AttributeError:
            raise RuntimeError, "no last traceback to disassemble"
        while tb.tb_next: tb = tb.tb_next
    disassemble(tb.tb_frame.f_code, tb.tb_lasti)
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def showsyntaxerror(self, filename=None):
        """Display the syntax error that just occurred.

        This doesn't display a stack trace because there isn't one.

        If a filename is given, it is stuffed in the exception instead
        of what was there before (because Python's parser always uses
        "<string>" when reading from a string).

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

        """
        type, value, sys.last_traceback = sys.exc_info()
        sys.last_type = type
        sys.last_value = value
        if filename and type is SyntaxError:
            # Work hard to stuff the correct filename in the exception
            try:
                msg, (dummy_filename, lineno, offset, line) = value
            except:
                # Not the format we expect; leave it alone
                pass
            else:
                # Stuff in the right filename
                value = SyntaxError(msg, (filename, lineno, offset, line))
                sys.last_value = value
        list = traceback.format_exception_only(type, value)
        map(self.write, list)
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
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)
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
def __call__(self, *args):
        ## Start by extending recursion depth just a bit. 
        ## If the error we are catching is due to recursion, we don't want to generate another one here.
        recursionLimit = sys.getrecursionlimit()
        try:
            sys.setrecursionlimit(recursionLimit+100)


            ## call original exception handler first (prints exception)
            global original_excepthook, callbacks, clear_tracebacks
            try:
                print("===== %s =====" % str(time.strftime("%Y.%m.%d %H:%m:%S", time.localtime(time.time()))))
            except Exception:
                sys.stderr.write("Warning: stdout is broken! Falling back to stderr.\n")
                sys.stdout = sys.stderr

            ret = original_excepthook(*args)

            for cb in callbacks:
                try:
                    cb(*args)
                except Exception:
                    print("   --------------------------------------------------------------")
                    print("      Error occurred during exception callback %s" % str(cb))
                    print("   --------------------------------------------------------------")
                    traceback.print_exception(*sys.exc_info())


            ## Clear long-term storage of last traceback to prevent memory-hogging.
            ## (If an exception occurs while a lot of data is present on the stack, 
            ## such as when loading large files, the data would ordinarily be kept
            ## until the next exception occurs. We would rather release this memory 
            ## as soon as possible.)
            if clear_tracebacks is True:
                sys.last_traceback = None

        finally:
            sys.setrecursionlimit(recursionLimit)
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
def __call__(self, *args):
        ## Start by extending recursion depth just a bit. 
        ## If the error we are catching is due to recursion, we don't want to generate another one here.
        recursionLimit = sys.getrecursionlimit()
        try:
            sys.setrecursionlimit(recursionLimit+100)


            ## call original exception handler first (prints exception)
            global original_excepthook, callbacks, clear_tracebacks
            try:
                print("===== %s =====" % str(time.strftime("%Y.%m.%d %H:%m:%S", time.localtime(time.time()))))
            except Exception:
                sys.stderr.write("Warning: stdout is broken! Falling back to stderr.\n")
                sys.stdout = sys.stderr

            ret = original_excepthook(*args)

            for cb in callbacks:
                try:
                    cb(*args)
                except Exception:
                    print("   --------------------------------------------------------------")
                    print("      Error occurred during exception callback %s" % str(cb))
                    print("   --------------------------------------------------------------")
                    traceback.print_exception(*sys.exc_info())


            ## Clear long-term storage of last traceback to prevent memory-hogging.
            ## (If an exception occurs while a lot of data is present on the stack, 
            ## such as when loading large files, the data would ordinarily be kept
            ## until the next exception occurs. We would rather release this memory 
            ## as soon as possible.)
            if clear_tracebacks is True:
                sys.last_traceback = None

        finally:
            sys.setrecursionlimit(recursionLimit)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def pm():
    post_mortem(sys.last_traceback)


# Main program for testing
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def print_last(limit=None, file=None):
    """This is a shorthand for 'print_exception(sys.last_type,
    sys.last_value, sys.last_traceback, limit, file)'."""
    if not hasattr(sys, "last_type"):
        raise ValueError("no last exception")
    if file is None:
        file = sys.stderr
    print_exception(sys.last_type, sys.last_value, sys.last_traceback,
                    limit, file)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def pytest_runtest_call(item):
    try:
        item.runtest()
    except Exception:
        # Store trace info to allow postmortem debugging
        type, value, tb = sys.exc_info()
        tb = tb.tb_next  # Skip *this* frame
        sys.last_type = type
        sys.last_value = value
        sys.last_traceback = tb
        del tb  # Get rid of it in this namespace
        raise
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def distb(tb=None):
    """Disassemble a traceback (default: last traceback)."""
    if tb is None:
        try:
            tb = sys.last_traceback
        except AttributeError:
            raise RuntimeError, "no last traceback to disassemble"
        while tb.tb_next: tb = tb.tb_next
    disassemble(tb.tb_frame.f_code, tb.tb_lasti)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def showsyntaxerror(self, filename=None):
        """Display the syntax error that just occurred.

        This doesn't display a stack trace because there isn't one.

        If a filename is given, it is stuffed in the exception instead
        of what was there before (because Python's parser always uses
        "<string>" when reading from a string).

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

        """
        type, value, sys.last_traceback = sys.exc_info()
        sys.last_type = type
        sys.last_value = value
        if filename and type is SyntaxError:
            # Work hard to stuff the correct filename in the exception
            try:
                msg, (dummy_filename, lineno, offset, line) = value
            except:
                # Not the format we expect; leave it alone
                pass
            else:
                # Stuff in the right filename
                value = SyntaxError(msg, (filename, lineno, offset, line))
                sys.last_value = value
        list = traceback.format_exception_only(type, value)
        map(self.write, list)
项目:devsecops-example-helloworld    作者:boozallen    | 项目源码 | 文件源码
def print_last(limit=None, file=None, chain=True):
    """This is a shorthand for 'print_exception(sys.last_type,
    sys.last_value, sys.last_traceback, limit, file)'."""
    if not hasattr(sys, "last_type"):
        raise ValueError("no last exception")
    print_exception(sys.last_type, sys.last_value, sys.last_traceback,
                    limit, file, chain)

#
# Printing and Extracting Stacks.
#
项目:deb-python-traceback2    作者:openstack    | 项目源码 | 文件源码
def print_last(limit=None, file=None, chain=True):
    """This is a shorthand for 'print_exception(sys.last_type,
    sys.last_value, sys.last_traceback, limit, file)'."""
    if not hasattr(sys, "last_type"):
        raise ValueError("no last exception")
    print_exception(sys.last_type, sys.last_value, sys.last_traceback,
                    limit, file, chain)

#
# Printing and Extracting Stacks.
#
项目:Craft-Clash    作者:Derpyface-Development-Co    | 项目源码 | 文件源码
def report_callback_exception(self, exc, val, tb):
        """Report callback exception on sys.stderr.

        Applications may want to override this internal function, and
        should when sys.stderr is None."""
        import traceback
        print("Exception in Tkinter callback", file=sys.stderr)
        sys.last_type = exc
        sys.last_value = val
        sys.last_traceback = tb
        traceback.print_exception(exc, val, tb)
项目:Craft-Clash    作者:Derpyface-Development-Co    | 项目源码 | 文件源码
def report_callback_exception(self, exc, val, tb):
        """Report callback exception on sys.stderr.

        Applications may want to override this internal function, and
        should when sys.stderr is None."""
        import traceback
        print("Exception in Tkinter callback", file=sys.stderr)
        sys.last_type = exc
        sys.last_value = val
        sys.last_traceback = tb
        traceback.print_exception(exc, val, tb)