Ejemplo n.º 1
0
 def get_track_back(limit=2, chain=True):
     res = ""
     _, value, tb = sys.exc_info()
     for line in TracebackException(type(value), value, tb,
                                    limit=limit).format(chain=chain):
         res = res + line + "\n"
     return res
Ejemplo n.º 2
0
 def _run_test(self, node: Test, fixtures: Set[Fixture]):
     self.visits.append(node)
     if self.verbosity >= 1:
         self.write('Running %s (%s) ... ', node.name, node.lineage_str())
     try:
         result = node.run(fixtures)
     except Exception:
         traceback = TracebackException(*sys.exc_info())
         self.fails.append((node, traceback))
         if self.verbosity == 0:
             self.write('F', color='red')
         elif self.verbosity >= 1:
             self.writeln('FAILED', color='red')
         else:
             assert False
     else:
         assert result is None, 'Tests should not return anything'
         self.passes.append(node)
         if self.verbosity == 0:
             self.write('.')
         elif self.verbosity >= 1:
             self.writeln('PASSED', color='green')
         else:
             assert False
     assert len(node.children) == 0
Ejemplo n.º 3
0
def resize_wrapper(stdscr, child = None, redraw = None):
    if child is None:
        child = draw_menu
    noerror = None
    while True:
        try:
            noerror = child(stdscr)
        except curses.error:
            pass
        except TypeError as e:
            import inspect
            import traceback
            exc_type, exc_obj, exc_tb = sys.exc_info()
            stdscr.clear()
            traceback.format_exc()
            i = 0
            for line in TracebackException(
                    type(exc_type), exc_obj, exc_tb, limit=None).format(chain=True):
                curses_safe_addstr(stdscr, i, 0, str(line))
                i += 1
            curses_safe_addstr(stdscr, 2, 0, str(e))
            stdscr.getch()
        if not noerror is None:
            break
        k = stdscr.getch()
        if not k == curses.KEY_RESIZE:
            break
        stdscr.erase()
        if not redraw is None:
            redraw(stdscr)
Ejemplo n.º 4
0
 def formatException(self, e: Exception) -> str:
     trace = None
     if (hasattr(e, "__traceback__")):
         trace = e.__traceback__
     tbe = TracebackException(type(e), e, trace, limit=None)
     lines = list(self._format(tbe))
     return'\n%s' % ''.join(lines)
Ejemplo n.º 5
0
    def __init__(self, exc_type, exc_value, tb):
        self.exc_type = exc_type
        self.exc_value = exc_value
        if not isinstance(exc_type, str):
            exception_type = exc_type.__name__
            if exc_type.__module__ not in ('__builtin__', 'exceptions'):
                exception_type = exc_type.__module__ + '.' + exception_type
        else:
            exception_type = exc_type
        self.exception_type = exception_type
        self.te = TracebackException(exc_type, exc_value, tb)

        def get_ext_frames(ext_expt, ext_expt_value):
            ext_tb = ext_expt.exc_traceback
            ext_exc_type = ext_expt.exc_type
            self.ext_frames = []
            while ext_tb:
                self.ext_frames.append(Frame(ext_exc_type, ext_expt_value, ext_tb))
                ext_tb = ext_tb.tb_next

        if self.te.__cause__ is not None:
            get_ext_frames(self.te.__cause__, exc_value.__cause__)
        elif self.te.__context__ is not None and \
                not self.te.__suppress_context__:
            get_ext_frames(self.te.__context__, exc_value.__context__)
            
        # we only add frames to the list that are not hidden.  This follows
        # the the magic variables as defined by paste.exceptions.collector
        self.frames = []
        while tb:
            self.frames.append(Frame(exc_type, exc_value, tb))
            tb = tb.tb_next
Ejemplo n.º 6
0
async def on_command_error(context, error):
    if isinstance(error, MissingRequiredArgument):
        # missing arguments should not be that noisy and can be reported to the user
        LOGGER.info(f"Missing parameter {error.param.name} reported to user.")
        await context.send(f"`{error.param.name}` is a required argument that is missing.")
    else:
        LOGGER.error(f"!!! Exception caught in {context.command} command !!!")
        LOGGER.info("".join(TracebackException(type(error), error, error.__traceback__, limit=None).format(chain=True)))
Ejemplo n.º 7
0
def tb_to_str(tb: tuple):
    try:
        _ = ""
        for line in TracebackException(type(tb[0]), tb[1],
                                       tb[2]).format(chain=True):
            _ += line
        return _
    except AttributeError:
        return None
Ejemplo n.º 8
0
def register_issue(err_cls, err, issues=Inject('trace/issues')):
    tr_exc = TracebackException(err_cls, err, None)
    issue_id = len(issues)
    if isinstance(err, MultiAlternativeError):
        issue = f"{err_cls.__name__}: {tr_exc}\n"
    else:
        issue = f"{err_cls.__name__}: [{issue_id}], {tr_exc}\n"
        issues.append(err)

    return issue
Ejemplo n.º 9
0
def main():
    x = XiHuSportsReserceTicker(14, 22, 1, [0])
    global message
    message = []
    try:
        x.run()
    except Exception:
        t = TracebackException(*sys.exc_info(), limit=None).format(chain=True)
        msg = ''.join(t)
        print(msg)
        send_email(msg, type_=0)
Ejemplo n.º 10
0
 def from_exc_info(cls, artifact_name, exc_info):
     te = TracebackException(*exc_info)
     # NB: we have dropped werkzeug's support for Paste's __traceback_hide__
     # frame local.
     return cls(
         {
             "artifact": artifact_name,
             "exception": "".join(te.format_exception_only()).strip(),
             "traceback": "".join(te.format()).strip(),
         }
     )
Ejemplo n.º 11
0
def parse_exception(exc, extra_msg=''):
    if not exc:
        return []
    exc_list = exc
    if isinstance(exc, Exception):
        tbe = TracebackException(type(exc), exc, exc.__traceback__)
        exc_list = tbe.format()
    lines = []
    for l in exc_list:
        lines.extend(l.split('\n'))
    lines.append(extra_msg)
    return list(map(lambda x: x.strip(), filter(lambda x: x, lines)))
Ejemplo n.º 12
0
def error_trace(e):
    # from traceback.print_exc
    limit = None
    chain = True
    tb = e.__traceback__
    value = e
    etype = type(e)
    out = []
    for line in TracebackException(type(value), value, tb,
                                   limit=limit).format(chain=chain):
        out += [line.strip("\n")]
    return '; '.join(out[-2:])
Ejemplo n.º 13
0
def report_error(exc, val, tb):
    from traceback import TracebackException

    log = Path(Path().cwd(), "as.txt")

    with open(log, "a") as log:
        log.write("Exception in Tkinter callback")
        sys.last_type = exc
        sys.last_value = val
        sys.last_traceback = tb
        for line in TracebackException(type(val), val, tb,
                                       limit=None).format(chain=True):
            log.write(line)
        log.write("\n")
Ejemplo n.º 14
0
def format_exc(exc=None):
    """Format an exception to be printed"""
    from sys import exc_info
    from traceback import TracebackException
    from itertools import chain
    if exc is None:
        exc = exc_info()
    tbe = TracebackException(*exc, limit=None, capture_locals=True)
    itr = chain.from_iterable(
        lin.split('\n') for lin in tbe.format(chain=None))
    title = (next(itr), '  Globals:')  # pylint: disable=R1708
    globals_ = exc[2].tb_frame.f_globals
    globals_ = ('    {} = {}'.format(k, v) for k, v in globals_.items())
    yield from chain(title, globals_, (i for i in itr if i != ''))
Ejemplo n.º 15
0
    def report_end_result(self):
        StatTrackingReporter.report_end_result(self)

        result = "\n"
        for message in self.failure_messages:
            if isinstance(message, Exception):
                for line in TracebackException(type(message),
                                               message,
                                               message.__traceback__,
                                               limit=None).format(chain=True):
                    result += line
            else:
                print(message)
        result += "\n"
        return self._printable(result)
Ejemplo n.º 16
0
def construct_user_code_exc(function, lineno, executed_code, exc_type,
                            exc_value, exc_traceback):
    """ Not generic enough to make it a real class constructor """
    exc_traceback = exc_traceback.tb_next.tb_next

    exc = TracebackException(exc_type, exc_value, exc_traceback)
    exc.stack[0]._line = executed_code

    first = FrameSummary(
        inspect.getfile(function),
        docs_start_lineno(function) + lineno,
        function.__name__,
        lookup_line=False,
    )
    exc.stack.insert(0, first)

    return UserCodeException(exc)
Ejemplo n.º 17
0
def mprint_exc(scrub_exc_msg=True, file=sys.stderr):
    '''Print exception to StdErr of AEther client.
    By defaut, it scrub exception message, print traceback and exception type.
    :param bool scrub_exc_msg: wheather scrub exception message.
    '''
    tb_exc = TracebackException(*sys.exc_info())
    if scrub_exc_msg:
        tb_exc = scrub_exc_message(tb_exc)
    exc_list = list(tb_exc.format())
    for exc in exc_list:
        if "return function(*matrix_args, **matrix_kwargs)" in exc:
            # dow not show Traceback for compliant_handle
            continue
        lines = exc.splitlines()
        for line in lines:
            timestamp = datetime.datetime.strftime(datetime.datetime.now(),
                                                   '%Y-%m-%d %H:%M:%S')
            print("SystemLog: [%s] %s" % (timestamp, line), file=file)
Ejemplo n.º 18
0
    def __init__(self, exc_obj, exc_tb, varsSoFar={}, execTime=0):
        # skip arepl traceback - the user should just see their own error
        exc_tb = exc_tb.tb_next

        self.traceback_exception = TracebackException(type(exc_obj), exc_obj,
                                                      exc_tb)
        self.friendly_message = "".join(self.traceback_exception.format())
        self.varsSoFar = pickle_user_vars(varsSoFar,
                                          get_settings().default_filter_vars,
                                          get_settings().default_filter_types)
        self.execTime = execTime

        # stack is empty in event of a syntax error
        # This is problematic because frontend has to handle syntax/regular error differently
        # to make it easier populate stack so frontend can handle them the same way
        if self.traceback_exception.exc_type is SyntaxError:
            self.traceback_exception.stack.append(
                FrameSummary(self.traceback_exception.filename,
                             int(self.traceback_exception.lineno), ""))
Ejemplo n.º 19
0
Archivo: utils.py Proyecto: Irmitya/zpy
    def print_exception(etype, value, tb, limit=None, file=None, chain=True):
        if file is None:
            file = stderr
        on_line = False
        for line in TracebackException(type(value), value, tb,
                                       limit=limit).format(chain=chain):
            end = ""
            tb = exc_info()[2]
            if line.startswith('Traceback'):
                line = f"Error in "
            elif line.startswith('  File "') and __package__ in line:
                filename = __package__ + line.split('  File "')[1].split(
                    '"')[0].split(__package__)[1]
                (line_no, function) = line.split(f' line ')[1], ''
                if ', ' in line_no:
                    (line_no, function) = line_no.split(', ', 1)
                line = f"{filename}\nline #{line_no} {function}"

            print(line, file=file, end="")
        print(*logs)
Ejemplo n.º 20
0
def traceback(printMsg:bool=False):
    (etype, value, tb) = sys.exc_info()
    for line in TracebackException(type(value), value, tb, limit=None).format(chain=True):
        warning(line, printMsg)
Ejemplo n.º 21
0
async def on_error(event, *args, **kwargs):
    LOGGER.error(f'!!! EXCEPTION CAUGHT IN {event} !!!')
    error, value, tb = sys.exc_info()
    LOGGER.info("".join(TracebackException(type(value), value, tb, limit=None).format(chain=True)))