Example #1
0
 def debugex(f, *args, **kw):
     try:
         return f(*args, **kw)
     except Exception, e:
         print e
         print inspect.trace()
         raise e
Example #2
0
def exception_error():
    error_message = ""
    for i in range(len(inspect.trace())):
        error_line = u"""
File:      %s - [%s]
Function:  %s
Statement: %s
-------------------------------------------------------------------------------------------""" % (
            inspect.trace()[i][1],
            inspect.trace()[i][2],
            inspect.trace()[i][3],
            inspect.trace()[i][4],
        )

        error_message = "%s%s" % (error_message, error_line)

    error_message = """Error!
%s
%s
======================================== Error Message ====================================%s

======================================== Error Message ======================================================""" % (
        sys.exc_info()[0],
        sys.exc_info()[1],
        error_message,
    )

    return error_message
Example #3
0
        def handler(signum, frame):
            import inspect

            print inspect.getframeinfo(frame)
            print inspect.trace()
            while 1:
                s = raw_input(
                    """
 
 Enter sense switch.

    sol:  Print current best solution.
    cont: Continue calculation.
    call: Executes sigint_callback [%s].
    exit: Exits with current best solution.

 >>> """
                    % sigint_callback
                )
                if s.lower() == "sol":
                    print self.bestSolution
                elif s.lower() == "cont":
                    return
                elif s.lower() == "call":
                    # sigint call_back
                    if sigint_callback is not None:
                        sigint_callback(self.bestSolution)
                elif s.lower() == "exit":
                    self._EARLYEXIT = True
                    return
                else:
                    print "unknown option : %s" % s
            return
Example #4
0
def class_from_module(path, defaultpaths=None):
    """
    Return a class from a module, given the module's path. This is
    primarily used to convert db_typeclass_path:s to classes.

    Args:
        path (str): Full Python dot-path to module.
        defaultpaths (iterable, optional): If a direc import from `path` fails,
            try subsequent imports by prepending those paths to `path`.

    Returns:
        class (Class): An uninstatiated class recovered from path.

    Raises:
        ImportError: If all loading failed.

    """
    cls = None
    if defaultpaths:
        paths = [path] + ["%s.%s" % (dpath, path) for dpath in make_iter(defaultpaths)] if defaultpaths else []
    else:
        paths = [path]

    for testpath in paths:
        if "." in path:
            testpath, clsname = testpath.rsplit(".", 1)
        else:
            raise ImportError("the path '%s' is not on the form modulepath.Classname." % path)
        try:
            mod = import_module(testpath, package="evennia")
        except ImportError:
            if len(trace()) > 2:
                # this means the error happened within the called module and
                # we must not hide it.
                exc = sys.exc_info()
                raise exc[1], None, exc[2]
            else:
                # otherwise, try the next suggested path
                continue
        try:
            cls = getattr(mod, clsname)
            break
        except AttributeError:
            if len(trace()) > 2:
                # AttributeError within the module, don't hide it
                exc = sys.exc_info()
                raise exc[1], None, exc[2]
    if not cls:
        err = "Could not load typeclass '%s'" % path
        if defaultpaths:
            err += "\nPaths searched:\n    %s" % "\n    ".join(paths)
        else:
            err += "."
        raise ImportError(err)
    return cls
Example #5
0
def main(argv=None):
    """This is our main function"""
    # Do argv default this way, as doing it in the functional
    # declaration sets it at compile time.
    if argv is None:
        argv = sys.argv

    print DIV
    print "Part One: stack() and trace() demonstrations\n"
    print "Printing stack() from inside main():"
    print_records(inspect.stack())
    print "Printing trace() from inside main(): (will be empty)"
    print_records(inspect.trace())

    try:
        eval("raise_exception()")
    except Exception as ex:
        print "\nTraceback from inside exception handler:"
        print_traceback(sys.exc_info()[2])
        print DIV
        print "Printing stack() from inside exception handler:"
        print_records(inspect.stack())
        print "\nPrinting trace() from inside exception handler:"
        print "    (Will be the almost the same as traceback)"
        print_records(inspect.trace())

    print DIV
    print "Part two: inspect a function.\n"
    print_function(demo_function)

    print DIV
    print "Part three: modifying an exception"
    print "    (Really nothing to do with inspect directly)\n"
    try:
        exception_changer(raise_exception)
    except Exception as ex:
        traceback.print_exc()

    print "\nNow using a decorator:"
    try:
        exception_raiser_two()
    except Exception as ex:
        traceback.print_exc()

    print DIV
    print "Demonstrate returning the docstring of a caller.\n"
    print "My docstring is: ", get_docstring()

    print "\n\nThat's all folks.\n"
Example #6
0
def RunWithExpandedTrace(closure):
    try:
        return closure()
    except (SystemExit, KeyboardInterrupt):
        raise
    except:
        import inspect
        import sys
        import traceback

        # Save trace and exception now. These calls look at the most recently
        # raised exception. The code that makes the report might trigger other
        # exceptions.
        original_trace = inspect.trace(3)[1:]
        formatted_exception = traceback.format_exception_only(*(sys.exc_info()[:2]))

        dashes = "%s\n" % ("-" * 60)
        dump = []
        dump.append(dashes)
        dump.extend(MakeExpandedTrace(original_trace))

        dump.append("".join(formatted_exception))

        print "".join(dump)
        print
        print dashes
        sys.exit(127)
Example #7
0
 def process_exception(self, request, exception):
     exc_info = sys.exc_info()
     print "######################## Exception #############################"
     print "\n".join(traceback.format_exception(*(exc_info or sys.exc_info())))
     print "----------------------------------------------------------------"
     pprint(inspect.trace()[-1][0].f_locals)
     print "################################################################"
Example #8
0
    def write_error(self, status_code, **kwargs):
        import traceback
        import inspect
        from cgi import escape

        exc_info = kwargs["exc_info"]
        trace_info = "".join(["%s<br/>" % escape(line) for line in traceback.format_exception(*exc_info)])
        locals_info = "<br>".join(
            [":".join(map(escape, map(str, v))) for v in inspect.trace()[-1][0].f_locals.iteritems()]
        )
        request_info = "".join(
            [
                "<strong>%s</strong>: %s<br/>" % (escape(k), escape(str(self.request.__dict__[k])))
                for k in self.request.__dict__.keys()
            ]
        )
        error = exc_info[1]
        self.write(
            self.render_engine.render_error(
                error=error,
                status_code=status_code,
                trace_info=trace_info,
                locals_info=locals_info,
                request_info=request_info,
            )
        )
        self.finish()
Example #9
0
    def update_room(self, roomid, listeners, upvotes, downvotes):
        try:
            cursor = self.cnx.cursor(mdb.cursors.DictCursor)
            cursor.execute("SET NAMES utf8;")
            cursor.execute("SET CHARACTER SET utf8;")
            cursor.execute("SET character_set_connection=utf8;")

            cursor.execute(
                "SELECT * FROM rooms WHERE roomid = '%s' LIMIT 1" % mdb.escape_string(roomid.encode("utf-8"))
            )
            room_exists = int(cursor.rowcount)
            if room_exists > 0:
                db_room_id = cursor.fetchone()["id"]
                cursor.execute(
                    "UPDATE rooms SET \
                                             listeners=%s, \
                                             downvotes=%s, \
                                             upvotes=%s \
                            WHERE id='%s'"
                    % (
                        "%s" % ("'%s'" % (int(listeners)) if listeners != None else "NULL"),
                        "%s" % ("'%s'" % (int(downvotes)) if downvotes != None else "0"),
                        "%s" % ("'%s'" % (int(upvotes)) if upvotes != None else "0"),
                        int(db_room_id),
                    )
                )
            else:
                cursor.close()
                raise Exception("Room id does not exists. (update_room)")
            cursor.close()
            return db_room_id
        except Exception, e:
            f, file, line, fn_name, lines, n = inspect.trace()[-1]
            log(sender, e, {"log": True, "file": file, "line": line, "command": "DB UPDATE_ROOM"})
Example #10
0
    def loadModuleFromSourceString_functionName_profile_(self, source, func, profile):
        try:
            kdemodule = imp.new_module("kdemodule")
            exec source in kdemodule.__dict__
            realfunc = getattr(kdemodule, func, None)
            if realfunc is not None:
                profiler = None
                if profile is True:
                    profiler = cProfile.Profile()
                    profiler.enable()

                realfunc()

                if profiler is not None:
                    reportProfileStats(profiler)

        except Exception as e:
            tb = inspect.trace()[-1]
            fileName = tb[1]
            lineNumber = tb[2]
            functionName = tb[3]
            py80.context.reportExceptionType_description_filePath_function_lineNumber_(
                type(e).__name__, str(e), fileName, functionName, lineNumber
            )
        finally:
            return NO

        return YES
Example #11
0
def install_failed_import_handler():
    """
        Custom __import__ function that records failed imports
        Useful if say you're using werkzeug auto reloader
        This way, failed imports are still checked for changes
    """
    original_import = __builtin__.__import__

    def new_import(name, *args, **kwargs):
        # Naively cope with the situation where this is called as a method
        if type(name) not in (str, unicode) and len(args) > 0:
            args = list(args)
            name = args.pop(0)

        failed = None
        try:
            return original_import(name, *args, **kwargs)

        except SyntaxError, s:
            # Record failed import and propogate error
            failed = (name, s.filename)
            raise

        except Exception, i:
            if not isinstance(i, ImportError):
                # ImportError is probably a legitimate fail
                failed = (name, inspect.trace()[-1][1])
            raise
Example #12
0
def print_debug():
    import traceback
    import pdb
    import inspect
    import platform
    import sys
    import os
    import copy

    def print_err(x):
        print >> sys.stderr, x

    print_err("An error has occurred. Please see below for debugging information.")
    print_err("")
    print_err("Python executable: %s" % sys.executable)
    print_err("Platform: %s" % str(platform.uname()))
    print_err("Linux: %s" % str(platform.linux_distribution()))
    print_err("Windows: %s" % str(platform.win32_ver()))
    print_err("Mac: %s" % str(platform.mac_ver()))
    print_err("Library paths: ")
    for path in sys.path:
        print_err(".. %s" % path)
    print_err("Executing in: %s" % str(os.getcwd()))
    print_err("Called by: %s" % str(sys.argv[0]))
    print_err("")
    traceback.print_exc(file=sys.stderr)
    print_err("")
    for t in inspect.trace():
        print_err("Frame: %s" % str(" ".join(map(str, t[1:]))))
        for local, value in dict(t[0].f_locals).iteritems():
            value = str(value).replace(os.linesep, "")
            print_err("  %s : %s ..." % (local, value[0:120]))
Example #13
0
    def toString(self, structure):
        filename = "<input>"
        symbol = "single"
        localVars = {"self": structure, "RETURN": ""}
        inter = InteractiveInterpreter(localVars)

        # if isinstance(source, types.UnicodeType):
        #    import IOBinding
        #    try:
        #        source = source.encode(IOBinding.encoding)
        #    except UnicodeError:
        console = InteractiveConsole(localVars, filename)

        try:
            code_object = compile(self.data, "<string>", "exec")
            exec code_object in localVars
        except Exception as e:
            print ("-  ERR --Kind:%s---------------------------------------" % (self.template.kind))
            InteractiveInterpreter.showsyntaxerror(console, filename)
            frames = inspect.trace()
            lineNumber = frames[1][2]
            print "At line %s" % lineNumber
            print ("- /ERR -----------------------------------------")

            print ("-  CODE -----------------------------------------")
            lines = self.data.split("\n")
            for i in range(0, lineNumber):
                print lines[i]
            print "^" * 20

            print ("- /CODE -----------------------------------------")
            print ("")

        return localVars["RETURN"]
Example #14
0
    def serve(self, callback):
        try:
            while not self._killed:
                try:
                    data = self.ws.recv()
                    # Answer the heartbeat
                    is_heartbeat = re.match("~m~[0-9]+~m~(~h~[0-9]+)", data)
                    if is_heartbeat:
                        self._heartbeat(is_heartbeat.group(1))
                        log(self, "HB: %s" % is_heartbeat.group(1))
                        self.last_heartbeat = datetime.now()
                        continue

                    self.last_activity = datetime.now()

                    data = json.loads(data[data.index("{") :])
                    for i in range(0, len(self.cmds)):
                        id, clb = self.cmds[i]
                        if id == data.get("msgid", None):
                            if clb:
                                clb(self, data)
                            del self.cmds[i]
                            break

                    if callback:
                        callback(self, data)
                except Exception, e:
                    if str(e) == "Bad file descriptor":
                        self.kill()

                    time.sleep(1)
                    f, file, line, fn_name, lines, n = inspect.trace()[-1]
                    log(self, e, {"log": True, "file": file, "line": line, "command": "BOT SERVE"})
            self.ws.close()
Example #15
0
def DumpStack(e):

    exc_type, exc_value, exc_traceback = sys.exc_info()
    str = traceback.format_exception(exc_type, exc_value, exc_traceback)
    str = "".join(str)
    # str=str.replace('\n', '\n*\t')

    trace = inspect.trace()
    lastframe = trace[-1][0]

    locals = DumpDict(lastframe.f_locals)
    globals = DumpDict(lastframe.f_globals)

    return """
ERROR MESSAGE:
   %s
%s-------------------------------------------------------------------------------
globals=>
%s
locals =>
%s
""" % (
        e.__str__(),
        str,
        globals,
        locals,
    )
Example #16
0
    def debug(self, err):
        import IPython

        ec, ev, tb = err
        stdout = sys.stdout
        sys.stdout = sys.__stdout__
        sys.stderr.write("\n- TRACEBACK --------------------------------------------------------------------\n")
        traceback.print_exception(*err)
        sys.stderr.write("--------------------------------------------------------------------------------\n")
        try:
            # The IPython API changed a bit so we should
            # support the new version
            if hasattr(IPython, "InteractiveShell"):
                shell = IPython.InteractiveShell()
                ip = IPython.core.ipapi.get()
                p = IPython.core.debugger.Pdb(ip.colors)
            # and keep support for older versions
            else:
                shell = IPython.Shell.IPShell(argv=[""])
                ip = IPython.ipapi.get()
                p = IPython.Debugger.Pdb(ip.options.colors)

            p.reset()
            # inspect.trace() returns a list of frame information from this
            # frame to the one that raised the exception being treated
            frame, filename, line, func_name, ctx, idx = inspect.trace()[-1]
            p.interaction(frame, tb)
        finally:
            sys.stdout = stdout
Example #17
0
    def wrapped(element):
        global FULL_TRACEBACK
        optstate = StoreOptions.state(element)
        try:
            html = fn(
                element, max_frames=OutputMagic.options["max_frames"], max_branches=OutputMagic.options["max_branches"]
            )

            # Only want to add to the archive for one display hook...
            disabled_suffixes = ["png_display", "svg_display"]
            if not any(fn.__name__.endswith(suffix) for suffix in disabled_suffixes):
                notebook_archive.add(element, html=html)
            filename = OutputMagic.options["filename"]
            if filename:
                Store.renderers[Store.current_backend].save(element, filename)

            return html
        except Exception as e:
            StoreOptions.state(element, state=optstate)
            frame = inspect.trace()[-1]
            mod = inspect.getmodule(frame[0])
            module = (mod.__name__ if mod else frame[1]).split(".")[0]
            backends = Store.renderers.keys()
            abbreviate = isinstance(e, BackendError) or module in backends
            if ABBREVIATE_TRACEBACKS and abbreviate:
                AutoTB = AutoFormattedTB(mode="Verbose", color_scheme="Linux")
                buff = io.StringIO()
                AutoTB(out=buff)
                buff.seek(0)
                FULL_TRACEBACK = buff.read()
                info = dict(name=type(e).__name__, message=str(e).replace("\n", "<br>"))
                msg = "<i> [Call ipython.show_traceback() for details]</i>"
                return "<b>{name}</b>{msg}<br>{message}".format(msg=msg, **info)
            else:
                traceback.print_exc()
Example #18
0
    def run_suite(self, case):
        # Initialize the test class
        suite = case()

        # check test environment setup
        environ = TestEnviron(suite)

        methods = get_methods(suite, self.method_name)
        if not methods:
            return

        # Name the class
        class_name = suite.__class__.__name__
        self.writer.out_case(class_name)

        # Are we skipping?
        if safe_skip_call(environ.set_skip_if):
            self.writer.skipping()
            return

        let_map = get_let_attrs(suite)

        # Set before all if any
        self.safe_environ_call(environ.set_before_all)

        for test in methods:
            test_start_time = StopWatch(raw=True)
            suite = set_let_attrs(suite, let_map)
            self.total_cases += 1

            # Set before each if any
            self.safe_environ_call(environ.set_before_each)

            try:
                getattr(suite, test)()
                test_elapsed_time = Decimal(str(test_start_time.elapsed()))
                self.writer.green_spec(test)

            except BaseException, e:
                test_elapsed_time = Decimal(str(test_start_time.elapsed()))
                trace = inspect.trace()[-1]
                self.total_failures += 1
                self.writer.red_spec(test)
                self.failures.append(dict(failure=sys.exc_info(), trace=trace, exc_name=e.__class__.__name__))

                is_assert_error = isinstance(e, AssertionError)
                if is_assert_error and self.config.get("pdb_on_fail"):
                    pdb_post_postmortem()
                elif not is_assert_error and self.config.get("pdb"):
                    pdb_post_postmortem()

                if self.config.get("first_fail"):
                    raise KoniraFirstFail

            # Save profiling info
            self.profiles.append((test_elapsed_time, test, class_name))

            # Set after each if any
            self.safe_environ_call(environ.set_after_each)
Example #19
0
def collect_log(logtype, head, msg, umplog, e=None, more=True):
    errlog = ""
    fname = logtype
    umplog = umplog.split("\n")
    umplog = "\r\n".join(umplog[::-1])
    if not e is None:
        import inspect
        import traceback

        frm = inspect.trace()[-1]
        mod = inspect.getmodule(frm[0])
        modname = mod.__name__ if mod else frm[1]
        errtype = e.__class__.__name__
        fname += "_" + errtype
        errlog = errtype + "\r\n" + traceback.format_exc().replace("\n", "\r\n")
    import os
    from third import logviewer

    logmodule = logviewer.Logmodule()
    kodilog = logmodule.getcontent()
    from datetime import datetime

    fname += "_" + datetime.utcnow().strftime("%Y%m%d+%H%M%S")
    import platform

    localdata = "PLATFORM        : " + os.name
    fname += "_" + os.name
    localdata += "\r\nRELEASE         : " + platform.release()
    fname += "_" + platform.release()
    localdata += "\r\nENVIRONMENT     : " + str(os.environ)
    import xbmc

    localdata += "\r\nXBMC VERSION    : " + xbmc.getInfoLabel("System.BuildVersion")
    fname += "_" + xbmc.getInfoLabel("System.BuildVersion")
    localdata += "\r\nPYTHON VERSION  : " + platform.python_version()
    fname += "_" + platform.python_version()
    localdata += "\r\n"
    fname = fname.replace(" ", "_").replace("/", "-").replace(":", "-").replace("?", "-").replace(".", "-")
    fname += ".log"
    from ump import defs

    extra = ""
    if more:
        others = {
            "working_xml": os.path.join(defs.addon_ddir, "settings.xml"),
            "addon_xml": defs.addon_setxml,
            "addon_prefs": defs.addon_preffile,
            "addon_cookies": defs.addon_cookfile,
            "kodi_advanced": defs.kodi_setxml,
            "guisettings": defs.kodi_guixml,
        }
        for k, v in others.iteritems():
            if os.path.exists(v):
                f = open(v)
                extra += "\r\n%s : \r\n %s" % (k.upper(), f.read().replace("\n", "\r\n"))
                f.close()
            else:
                extra += "\r\n%s : %s does not exist" % (k.upper(), v)
    upload_log(head, msg, fname, localdata, errlog, kodilog, umplog, extra)
Example #20
0
def class_from_module(path, defaultpaths=None):
    """
    Return a class from a module, given the module's path. This is
    primarily used to convert db_typeclass_path:s to classes.

    if a list of `defaultpaths` is given, try subsequent runs by
    prepending those paths to the given `path`.
    """
    cls = None
    if defaultpaths:
        paths = [path] + ["%s.%s" % (dpath, path) for dpath in make_iter(defaultpaths)] if defaultpaths else []
    else:
        paths = [path]

    for testpath in paths:
        if "." in path:
            testpath, clsname = testpath.rsplit(".", 1)
        else:
            raise ImportError("the path '%s' is not on the form modulepath.Classname." % path)
        try:
            mod = import_module(testpath, package="evennia")
        except ImportError:
            if len(trace()) > 2:
                # this means the error happened within the called module and
                # we must not hide it.
                exc = sys.exc_info()
                raise exc[1], None, exc[2]
            else:
                # otherwise, try the next suggested path
                continue
        try:
            cls = getattr(mod, clsname)
            break
        except AttributeError:
            if len(trace()) > 2:
                # AttributeError within the module, don't hide it
                exc = sys.exc_info()
                raise exc[1], None, exc[2]
    if not cls:
        err = "Could not load typeclass '%s'" % path
        if defaultpaths:
            err += "\nPaths searched:\n    %s" % "\n    ".join(paths)
        else:
            err += "."
        raise ImportError(err)
    return cls
Example #21
0
 def _callTestWrapper(self, testMethod):
     try:
         testMethod()
     except PyTestFailure:
         pass
     except Exception, e:
         PyTest.tracker.failTest("Exception thrown from test <%s>" % e, trace())
         PyTest.tracker.caughtException(exc_info()[2])
Example #22
0
def stacktrace():
    s = ""
    for frame in inspect.trace():
        s = "".join([s, " ", frame[1], ": line ", str(frame[2]), " in ", frame[3]])
        if frame[4]:
            s = ": ".join([s, frame[4][0].strip()])
        s = "".join([s, ";"])
    return s
Example #23
0
 def _tearDownWrapper(self):
     try:
         self.tearDown()
     except PyTestFailure:
         pass
     except Exception, e:
         PyTest.tracker.failTest("Exception thrown from test <%s>" % e, trace())
         PyTest.tracker.caughtException(exc_info()[2])
Example #24
0
def load_plugin(path):
    try:
        plugin = import_module(path)
    except ImportError:
        if len(trace()) > 2:
            exc = sys.exc_info()
            raise exc[1], None, exc[2]
    return plugin
Example #25
0
 def notify_error(self, e, silent=True):
     frm = inspect.trace()[-1]
     mod = inspect.getmodule(frm[0])
     modname = mod.__name__ if mod else frm[1]
     errtype = e.__class__.__name__
     if not silent:
         self.dialog.notification("ERROR", "%s : %s" % (modname, errtype))
     if not errtype == "killbill":
         print traceback.format_exc()
Example #26
0
def recv_room_info(sender, data):
    try:
        log(sender, "RECV ROOM INFO")

        roomid = data["room"]["roomid"]
        name = data["room"]["name"]
        created = datetime.fromtimestamp(data["room"]["created"])
        description = data["room"].get("description", "")
        shortcut = data["room"]["shortcut"]
        current_dj = data["room"]["metadata"].get("current_dj", None)
        try:
            db_current_dj = sender.db.get_user_id(current_dj)
        except Exception, e:
            db_current_dj = None
        listeners = data["room"]["metadata"].get("listeners", None)
        downvotes = data["room"]["metadata"].get("downvotes", 0)
        upvotes = data["room"]["metadata"].get("upvotes", 0)
        current_song = data["room"]["metadata"].get("current_song", None)
        starttime = None
        if current_song != None:
            starttime = current_song.get("starttime", None)
        if starttime != None:
            starttime = datetime.fromtimestamp(starttime)

        sender.current_song["id"] = current_song.get("_id", None)
        sender.current_song["starttime"] = starttime
        sender.current_song["current_dj"] = current_dj

        db_room_id = sender.db.register_room(
            roomid,
            name,
            created,
            description,
            shortcut,
            db_current_dj,
            listeners,
            downvotes,
            upvotes,
            starttime,
            song_id=None,
        )

        for user in data["users"]:
            try:
                userid = user["userid"]
                fbid = user.get("fbid", None)
                name = user["name"]
                laptop = user["laptop"]
                acl = user["acl"]
                fans = user["fans"]
                points = user["points"]
                avatarid = user["avatarid"]
                sender.db.register_user(userid, fbid, name, laptop, acl, fans, points, avatarid)
            except Exception, e:
                f, file, line, fn_name, lines, n = inspect.trace()[-1]
                log(sender, e, {"log": True, "file": file, "line": line, "command": "RECV_ROOM_INFO 1"})
Example #27
0
def main():

    try:
        # set up and parse arguments
        parser = argparse.ArgumentParser(description="Mozilla Powertool")
        parser.add_argument(
            "-d",
            "--device",
            type=str,
            default=["mozilla", "yocto"],
            choices=["yocto", "mozilla"],
            action="append",
            help="specify ammeter device to use",
        )
        parser.add_argument(
            "-p", "--path", type=str, default=None, help="specify path to ammeter device (e.g. /dev/ttyACM0)"
        )
        parser.add_argument(
            "-u", "--ui", type=str, default="tk", choices=["tk", "cli", "web"], help="specify which UI to use"
        )
        parser.add_argument("-f", "--file", type=str, default=None, help="test run config file")
        parser.add_argument("-o", "--out", type=str, default=None, help="output data file")
        parser.add_argument("-s", "--show", type=str, default="current", help="name of the sample source to display")
        args = parser.parse_args()

        # create the sample source
        source = SampleSource.create(args.device, args.path)

        # create the test suite
        suite = TestSuite.create(args.file)

        # add the sample source
        suite.addSource(source)

        # create the saver
        saver = TestSuiteSaver.create(args.out)

        # create the displayer
        ui = UI.create(args.ui, suite, args.show)

        # run the app
        ui.run()

        # save the data
        saver.save(suite)

        # shut down the sample source
        source.close()

        sys.exit(0)

    except Exception, e:
        frame = inspect.trace()[-1]
        print >>sys.stderr, "\nException:\n from %s, line %d:\n %s\n" % (frame[1], frame[2], e)
        parser.print_help()
        sys.exit(1)
Example #28
0
 def wrapped(self):
     if "result" not in self.__dict__:
         self.results = []
     try:
         result = f(self)
     except Exception as e:
         self.results[f.__name__] = {"success": False, "locals": inspect.trace()[-1][0].f_locals}
         raise e
     self.results[f.__name__] = {"success": True, "result": result}
     return result
Example #29
0
def return_exception_trace():
    """
    For testing purposes we need some valid
    tracebacks created for assertions.
    """
    try:
        assert False
    except Exception, e:
        trace = inspect.trace()
        return dict(failure=sys.exc_info(), trace=trace, exc_name=e.__class__.__name__)
Example #30
0
def debug(func, *args, **kwargs):
    # evaluate and print local vars in case of exception
    try:
        return func(*args, **kwargs)
    except:
        import inspect

        v = inspect.trace()[-1][0].f_locals
        pprint(v)
        raise