Python sys.print_exception() Examples

The following are 30 code examples of sys.print_exception(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sys , or try the search function .
Example #1
Source File: ush.py    From esp8266 with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def run(self):
        try:
            print("Welcome to ush-{}.  Type 'help' for help.  ^D to exit".format(VERSION))
            while True:
                line = Ush.prompt().strip()
                if line:
                    tokens = line.split()
                    cmd = tokens[0]
                    if cmd in self._handlers:
                        handler = self._handlers[cmd]
                        try:
                            handler.handle_command(tokens[1:])
                        except Exception as e:
                            sys.print_exception(e)
                    else:
                        print("Unknown command: {}".format(cmd))
        except Exception as e:
            print(e) 
Example #2
Source File: flash.py    From specter-diy with MIT License 6 votes vote down vote up
def load_state(self):
        """Verify file and load PIN state from it"""
        try:
            # verify that the pin file is ok
            _, data = self.load_aead(self.path+"/pin", self.secret)
            # load pin object
            data = json.loads(data.decode())
            self.pin = unhexlify(data["pin"]) if data["pin"] is not None else None
            self._pin_attempts_max = data["pin_attempts_max"]
            self._pin_attempts_left = data["pin_attempts_left"]
        except Exception as e:
            self.wipe(self.path)
            sys.print_exception(e)
            raise CriticalErrorWipeImmediately(
                "Something went terribly wrong!\nDevice is wiped!\n%s" % e
            ) 
Example #3
Source File: console_sink.py    From esp8266 with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def log(self, message) :
        try :
            print("{} [{}] {}: {}".format(
                message['datetime'], 
                message['level'], 
                message['name'], 
                message['message'])
            )
        except Exception as e :
            print("Error printing message:")
            sys.print_exception(e)
            print("begin message ==>")
            print(message['datetime'])
            print(message['level'])
            print(message['name'])
            print(message['message'])
            print("<=== end message") 
Example #4
Source File: main.py    From rshell with MIT License 6 votes vote down vote up
def board_name(default):
    """Returns the boards name (if available)."""
    try:
        import board
        try:
            name = board.name
        except AttributeError:
            # There was a board.py file, but it didn't have an name attribute
            # We also ignore this as an error
            name = default
    except ImportError:
        # No board.py file on the pyboard - not an error
        name = default
    except BaseException as err:
        print('Error encountered executing board.py')
        import sys
        sys.print_exception(err)
        name = default
    return repr(name) 
Example #5
Source File: __init__.py    From esp8266 with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def load_sinks(self, config) :
        if 'sinks' in config :
            ret = {}
            sink_configs = config['sinks']
            for name, config in sink_configs.items() :
                try :
                    sink_name = name + "_sink"
                    mod = __import__(sink_name, globals(), locals(), ['Sink'], 0)
                    ret[name] = mod.Sink(config)
                    print("loaded sink {}".format(name))
                except Exception as e :
                    print("Error: failed to load sink {} with config {}.  Error: {}".format(name, config, e))
                    sys.print_exception(e)
            return ret
        else :
            return {} 
Example #6
Source File: string_exc.py    From upy-examples with MIT License 5 votes vote down vote up
def foo():
    try:
        bar()
    except Exception as err:
        print("Recording error")
        sys.print_exception(err, output)
        print('output = ', output.getvalue()) 
Example #7
Source File: task.py    From esp8266 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def loop(self) :
        if self._verbose :
            logging.info("TaskBase: loop starting.")
        while self.isRunning() :
            if not self.disabled :
                try :
                    self.num_calls += 1
                    start_ticks_us = utime.ticks_us()
                    result = self.perform()
                    self.ticks_us += utime.ticks_diff(utime.ticks_us(), start_ticks_us)
                    if not result:
                        return
                    self.last_retry_ms = None
                except Exception as e :
                    if not self.last_retry_ms :
                        self.last_retry_ms = 500
                    else :
                        self.last_retry_ms = min(self.sleep_ms, self.last_retry_ms * 2)
                    self.num_failures += 1
                    logging.info("An error occurred performing {}: {}".format(self, e))
                    sys.print_exception(e)
                await uasyncio.sleep_ms(self.sleep_ms if not self.last_retry_ms else self.last_retry_ms)
            else :
                await uasyncio.sleep_ms(914)
        self.state = TaskBase.STOPPED
        if self._verbose :
            logging.info("TaskBase: loop terminated.")
        return 
Example #8
Source File: microdot.py    From microdot with MIT License 5 votes vote down vote up
def print_exception(exc):
        traceback.print_exc() 
Example #9
Source File: logging.py    From uble with MIT License 5 votes vote down vote up
def exc(self, e, msg, *args): 
        self.log(ERROR, msg, *args)
        sys.print_exception(e, _stream) 
Example #10
Source File: logging.py    From micropython-wifimanager with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def exc(self, e, msg, *args):
        self.log(ERROR, msg, *args)
        sys.print_exception(e, _stream) 
Example #11
Source File: server.py    From webthing-upy with MIT License 5 votes vote down vote up
def print_exc(func):
    """Wrap a function and print an exception, if encountered."""
    def wrapper(*args, **kwargs):
        try:
            # log.debug('Calling {}'.format(func.__name__))
            ret = func(*args, **kwargs)
            # log.debug('Back from {}'.format(func.__name__))
            return ret
        except Exception as err:
            sys.print_exception(err)
    return wrapper 
Example #12
Source File: __init__.py    From esp8266 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def handle_receive(self, reader, writer, tcp_request):
        try:
            done, response = yield from self._handler.handle_request(reader, writer, tcp_request)
            if response and len(response) > 0:
                yield from writer.awrite(response)
            if done:
                return False
            else:
                return True
        except Exception as e:
            sys.print_exception(e)
            return False 
Example #13
Source File: print_exc.py    From upy-examples with MIT License 5 votes vote down vote up
def foo():
    try:
        bar()
    except Exception as err:
        print("Recording error")
        sys.print_exception(err, log_file)
        log_file.flush() 
Example #14
Source File: compat.py    From terkin-datalogger with GNU Affero General Public License v3.0 5 votes vote down vote up
def monkeypatch_exceptions():

    import traceback

    def print_exception(exc, file=sys.stdout):
        traceback.print_exception(exc, exc, exc.__traceback__)

    sys.print_exception = print_exception 
Example #15
Source File: compat.py    From terkin-datalogger with GNU Affero General Public License v3.0 5 votes vote down vote up
def monkeypatch_logging():

    import io
    import logging

    def exc(self, e, msg, *args):
        buf = io.StringIO()
        sys.print_exception(e, buf)
        self.log(logging.ERROR, msg + "\n" + buf.getvalue(), *args)

    logging.Logger.exc = exc 
Example #16
Source File: util.py    From terkin-datalogger with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_last_stacktrace():
    """ """
    buf = uio.StringIO()
    exc = sys.exc_info()[1]
    sys.print_exception(exc, buf)
    return buf.getvalue() 
Example #17
Source File: micropython.py    From terkin-datalogger with GNU Affero General Public License v3.0 5 votes vote down vote up
def monkeypatch_exceptions():

    def print_exception(exc, file=sys.stdout):
        # file.write(str(exc))
        raise exc

    sys.print_exception = print_exception 
Example #18
Source File: micropython.py    From terkin-datalogger with GNU Affero General Public License v3.0 5 votes vote down vote up
def monkeypatch_logging():
    import io
    import logging

    def exc(self, e, msg, *args):
        buf = io.StringIO()
        sys.print_exception(e, buf)
        self.log(logging.ERROR, msg + "\n" + buf.getvalue(), *args)

    logging.Logger.exc = exc 
Example #19
Source File: usb.py    From specter-diy with MIT License 5 votes vote down vote up
def update(self):
        if self.manager == None:
            return await asyncio.sleep_ms(100)
        if self.usb is None:
            return await asyncio.sleep_ms(100)
        if not platform.usb_connected():
            return await asyncio.sleep_ms(100)
        res = self.read_to_file()
        # if we got a filename - line is ready
        if res is not None:
            # first send the host that we are processing data
            self.usb.write(self.ACK)
            # open again for reading and try to process content
            try:
                with open(self.path+"/data", "rb") as f:
                    await self.process_command(f)
            # if we fail with host error - tell the host why we failed
            except HostError as e:
                self.respond(b"error: %s" % e)
                sys.print_exception(e)
            # for all other exceptions - send back generic message
            except Exception as e:
                self.respond(b"error: Unknown error")
                sys.print_exception(e)
            self.cleanup()

        # wait a bit
        await asyncio.sleep_ms(10) 
Example #20
Source File: __init__.py    From esp8266 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def internal_server_error(writer, e):
        sys.print_exception(e)
        error_message = "Internal Server Error: {}".format(e)
        return (yield from Server.error(writer, 500, error_message, e)) 
Example #21
Source File: __init__.py    From esp8266 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def do_log(self, sink, message) :
        try :
            sink.log(message)
        except Exception as e :
            sys.print_exception(e) 
Example #22
Source File: __init__.py    From esp8266 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def log(self, level, format_str, *args) :
        if level in self._levels :
            try :
                message = self.create(level, format_str, *args)
            except Exception :
                print("WARNING: Error formatting log message.  Log will be delivered unformatted.")
                sys.print_exception(e)
                message = (level, format_str, args)
            for name, sink in self._sinks.items() :
                self.do_log(sink, message) 
Example #23
Source File: logging.py    From iot-core-micropython with Apache License 2.0 5 votes vote down vote up
def exc(self, e, msg, *args):
        self.log(ERROR, msg, *args)
        sys.print_exception(e, _stream) 
Example #24
Source File: ulogging.py    From micropython-samples with MIT License 5 votes vote down vote up
def exc(self, e, msg, *args):
        self.log(ERROR, msg, *args)
        sys.print_exception(e, _stream) 
Example #25
Source File: __init__.py    From micropython-iot with MIT License 5 votes vote down vote up
def set_global_exception():
    def _handle_exception(loop, context):
        import sys
        sys.print_exception(context["exception"])
        sys.exit()
    loop = asyncio.get_event_loop()
    loop.set_exception_handler(_handle_exception) 
Example #26
Source File: s_qos_fast.py    From micropython-iot with MIT License 5 votes vote down vote up
def _handle_exception(loop, context):
    print('Global handler')
    sys.print_exception(context["exception"])
    sys.exit() 
Example #27
Source File: s_qos_cp.py    From micropython-iot with MIT License 5 votes vote down vote up
def _handle_exception(loop, context):
    print('Global handler')
    sys.print_exception(context["exception"])
    sys.exit()  # Drastic - loop.stop() does not work when used this way 
Example #28
Source File: specter.py    From specter-diy with MIT License 5 votes vote down vote up
def host_exception_handler(self, e):
        try:
            raise e
        except HostError as ex:
            msg = "%s" % ex
        except:
            b = BytesIO()
            sys.print_exception(e, b)
            msg = b.getvalue().decode()
        res = await self.gui.error(msg, popup=True) 
Example #29
Source File: specter.py    From specter-diy with MIT License 5 votes vote down vote up
def handle_exception(self, exception, next_fn):
        """
        Handle exception, show proper error message
        and return next function to call and await
        """
        try:
            raise exception
        except CriticalErrorWipeImmediately as e:
            # wipe all wallets
            self.wallet_manager.wipe()
            # show error
            await self.gui.error("%s" % e)
            # TODO: actual reboot here
            return self.setup
        # catch an expected error
        except BaseError as e:
            # show error
            await self.gui.alert(e.NAME, "%s" % e)
            # restart
            return next_fn
        # show trace for unexpected errors
        except Exception as e:
            print(e)
            b = BytesIO()
            sys.print_exception(e, b)
            await self.gui.error("Something unexpected happened...\n\n%s" % b.getvalue().decode())
            # restart
            return next_fn 
Example #30
Source File: microdot.py    From microdot with MIT License 4 votes vote down vote up
def dispatch_request(self, sock, addr):
        if not hasattr(sock, 'readline'):  # pragma: no cover
            stream = sock.makefile("rwb")
        else:
            stream = sock

        req = Request.create(stream, addr)
        f = self.find_route(req)
        try:
            res = None
            if f:
                for handler in self.before_request_handlers:
                    res = handler(req)
                    if res:
                        break
                if res is None:
                    res = f(req, **req.url_args)
                if isinstance(res, tuple):
                    res = Response(*res)
                elif not isinstance(res, Response):
                    res = Response(res)
                for handler in self.after_request_handlers:
                    res = handler(req, res) or res
            elif 404 in self.error_handlers:
                res = self.error_handlers[404](req)
            else:
                res = 'Not found', 404
        except Exception as exc:
            print_exception(exc)
            res = None
            if exc.__class__ in self.error_handlers:
                try:
                    res = self.error_handlers[exc.__class__](req, exc)
                except Exception as exc2:  # pragma: no cover
                    print_exception(exc2)
            if res is None:
                if 500 in self.error_handlers:
                    res = self.error_handlers[500](req)
                else:
                    res = 'Internal server error', 500
        if isinstance(res, tuple):
            res = Response(*res)
        elif not isinstance(res, Response):
            res = Response(res)
        res.write(stream)
        stream.close()
        if stream != sock:  # pragma: no cover
            sock.close()
        if self.debug:  # pragma: no cover
            print('{method} {path} {status_code}'.format(
                method=req.method, path=req.path,
                status_code=res.status_code))