Like print_exc() but return a string. Backport for Python 2.3.
973879
def format_exc(limit=None):
    """"""
    try:
        etype, value, tb = sys.exc_info()
        return ''.join(traceback.format_exception(etype, value, tb, limit))
    finally:
        etype = value = tb = None
357188
def print_stack(sig, frame):
    """"""
    if _debug: print_stack._debug("print_stack %r %r", sig, frame)
    global running, deferredFns, sleeptime

    sys.stderr.write("==== USR1 Signal, %s\n" % time.strftime("%d-%b-%Y %H:%M:%S"))

    sys.stderr.write("---------- globals\n")
    sys.stderr.write("    running: %r\n" % (running,))
    sys.stderr.write("    deferredFns: %r\n" % (deferredFns,))
    sys.stderr.write("    sleeptime: %r\n" % (sleeptime,))

    sys.stderr.write("---------- stack\n")
    traceback.print_stack(frame)

    # make a list of interesting frames
    flist = []
    f = frame
    while f.f_back:
        flist.append(f)
        f = f.f_back

    # reverse the list so it is in the same order as print_stack
    flist.reverse()
    for f in flist:
        sys.stderr.write("---------- frame: %s\n" % (f,))
        for k, v in f.f_locals.items():
            sys.stderr.write("    %s: %r\n" % (k, v))

    sys.stderr.flush()
764276
def _print_result_info(traces, events):
    
    print_v('Returning %i traces:'%len(traces))
    for r in sorted(traces.keys()):
        x = traces[r]
        print_v('  %s (%s): %s -> %s (min: %s, max: %s, len: %i)'%(r, type(x), x[0],x[-1],min(x),max(x),len(x)))
    print_v('Returning %i events:'%len(events))
    for r in sorted(events.keys()):
        x = events[r]
        print_v('  %s: %s -> %s (len: %i)'%(r, x[0] if len(x)>0 else '-',x[-1] if len(x)>0 else '-',len(x)))
990373
def printy(s):
    """"""
    if hasattr(s, 'as_utf8'):
        if hasattr(sys.stdout, 'buffer'):
            sys.stdout.buffer.write(s.as_utf8)
            sys.stdout.buffer.write(b"\n")
        else:
            sys.stdout.write(s.as_utf8)
            sys.stdout.write(b"\n")
    else:
        print(s)
569474
def execute(self):
        
        if self.skip:
            return None

        result = self.pre_execute()
        if result is None:
            try:
                result = self.do_execute()
            except Exception as e:
                result = traceback.format_exc()
                print(self.full_name + "\n" + result)
        if result is None:
            result = self.post_execute()
        return result
726220
def log_fault_exc_str (exc, # pylint: disable=W0613
                       message = "", level = logging.CRITICAL,
                       traceback = False):
  
  return log_fault_info_str (sys.exc_info (), message = message,
                             level = level, traceback = traceback)
395108
def excepthook(exc_type, exc_value, tracebackobj):
    
    separator = "-" * 80
    notice = "The following error was triggered:"

    now = datetime.now().strftime("%Y-%m-%d, %H:%M:%S")

    info = StringIO()
    traceback.print_tb(tracebackobj, None, info)
    info.seek(0)
    info = info.read()

    errmsg = f"{exc_type}\t \n{exc_value}"
    sections = [now, separator, errmsg, separator, info]
    msg = "\n".join(sections)

    print(''.join(traceback.format_tb(tracebackobj)))
    print('{0}: {1}'.format(exc_type, exc_value))

    QtWidgets.QMessageBox.warning(None, notice, traceback.format_exc())
1060460
def get_last_traceback():
    """"""
    import traceback
    from StringIO import StringIO
    tb = StringIO()
    traceback.print_exc(file=tb)
    return to_unicode(tb.getvalue())
376763
def print_exc_plus(stream=sys.stdout):
    ''''''
    # code of this mothod is mainly from <Python Cookbook>
    write = stream.write    # assert the mothod exists
    flush = stream.flush
    tp, value, tb = sys.exc_info()
    while tb.tb_next:
        tb = tb.tb_next
    stack = list()
    f = tb.tb_frame
    while f:
        stack.append(f)
        f = f.f_back
    stack.reverse()
    try:
        traceback.print_exc(None, stream)
    except BaseException as e:
        write(u("FAILED PRINTING TRACE\n\n"))
        write(u(str(value)))
        write(u('\n\n'))
    finally:
        flush()

    write(u('Locals by frame, innermost last\n'))
    for frame in stack:
        write(u('\nFrame %s in %s at line %s\n' % (frame.f_code.co_name,
                                                   frame.f_code.co_filename,
                                                   frame.f_lineno)))
    for key, value, in frame.f_locals.items():
        write(u('\t%20s = ' % key))
        try:
            write(u('%s\n' % value))
        except BaseException:
            write(u('<ERROR WHILE PRINTING VALUE>\n'))
    flush()
1230087
def tostring(self, root=None, doctype=None, pretty_print=True):
        """"""
        if root is None:
            root = self.root
        return etree.tounicode(
            root, doctype=doctype or self.info.doctype, pretty_print=pretty_print
        )
950444
def exc_info(hide_calls = 0):
    ''''''
    ErrorType, thrownError, traceback = sys.exc_info()
    for i in range(hide_calls):
        if traceback.tb_next:
            traceback = traceback.tb_next
    err = withTracebackPrint(ErrorType, thrownError, traceback)
    return type(err), err, traceback
1096943
def backtrace(exc, level_meth = :error)
      return unless show_backtraces
      send(level_meth, "#{exc.class.class_name}: #{exc.message}")
      send(level_meth, "Stack trace:" +
        exc.backtrace[0..5].map {|x| "\n\t#{x}" }.join + "\n")
    end
1125645
def print_tree(self) -> str:
        

        if self.ast:
            return self.ast.print_tree(ast_obj=self.ast)
        else:
            return ""
1174367
def dump(self, src, length=16, start=0, preffix=""):
        """"""
        FILTER = \
            "".join([(len(repr(chr(x)))==3) and chr(x) or '.' \
                for x in xrange(256)])

        result = list()

        for i in xrange(0, len(src), length):
            s           = src[i : i + length]
            hexa        = " ".join(["%02X" % ord(x) for x in s])
            printable   = s.translate(FILTER)

            result.append("%s%08X   %-*s   %s\n" % \
                (preffix, start + i, length * 3, hexa, printable))

        return ''.join(result)
686404
def traceback_string():
    
    tb_string = None
    exc_type, exc_value, exc_traceback = traceback.sys.exc_info()
    if exc_type is not None:
        display_lines_list = [str(exc_value)] + traceback.format_tb(exc_traceback)
        tb_string = "\n".join(display_lines_list)
    return tb_string
334948
def cmd_print(self):
        """"""
        if not self._valid_lines:
            return ''
        return '\n'.join([line.raw_line for line in self._valid_lines]) + '\n'
759250
def error(cls, message, prefix=True, traceflag=False):
        
        # print (message, prefix)
        message = message or ""
        if prefix:
            text = "ERROR: "
        else:
            text = ""
        if cls.color:
            cls.cprint('FAIL', text, str(message))
        else:
            print(cls.txt_msg(text + str(message)))

        if traceflag and cls.debug:
            trace = traceback.format_exc().strip()
            if trace:
                print()
                print("Trace:")
                print("\n    ".join(str(trace).splitlines()))
                print()