def log(o, t, e=None):
if e is None:
print("{}: {}".format(type(o).__name__, t))
else:
print("{}: {} Exception:{!r}".format(type(o).__name__, t, e))
import sys
if hasattr(sys, 'print_exception'):
sys.print_exception(e)
else:
import traceback
traceback.print_exception(type(e), e, sys.exc_info()[2])
python类print_exception()的实例源码
def read(self):
d = None
if self.config['dht_type'] == 11:
d = dht.DHT22(machine.Pin(self.config["gpio"]))
else:
d = dht.DHT11(machine.Pin(self.config["gpio"]))
try:
d.measure()
payload = { 'temperature': str(d.temperature()), "humidity": str(d.humidity()) }
return payload
except Exception as e:
Util.log(self,"DHT type: {}, failed to measure pin: '{}'".format(self.config["dht_type"], self.config["gpio"]))
import sys
sys.print_exception(e)
def run(self, reset_on_exception):
""" Run the program. This blocks until the program is finished.
:param reset_on_exception: If true the :func:`machine.reset` is called
if an exeption other than
:class:`KeyboardInterrupt` if raised.
:type reset_on_exception: bool
:raises Exception: If the program fails for some reason.
"""
try:
with self:
self.clean()
self.scheduler.handle()
self.clean()
except KeyboardInterrupt:
pass
except Exception as err:
sys.print_exception(err) # pylint: disable=no-member
if reset_on_exception:
machine.reset()
raise
def loop(self) :
if self._verbose :
logging.info("TaskBase: loop starting.")
while self.isRunning() :
if not self.disabled :
result = None
try :
result = self.perform()
except Exception as e :
logging.info("An error occurred performing {}: {}".format(self, e))
sys.print_exception(e)
if not result:
break
else :
await uasyncio.sleep_ms(self.sleep_ms)
else :
await uasyncio.sleep_ms(914)
self.state = STATE_STOPPED
if self._verbose :
logging.info("TaskBase: loop terminated.")
return
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 {}
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)
def publish(self, payload):
if payload is None:
return
if self.config["publish_changes_only"] is False or payload != self.last_payload:
try:
self.gateway.publish(self.topic, json.dumps(payload))
except Exception as e:
import sys
sys.print_exception(e)
self.last_payload = payload
def run_app(path):
import buttons
import ugfx
import sys
buttons.init()
ugfx.init()
ugfx.clear()
if not buttons.has_interrupt("BTN_MENU"):
buttons.enable_menu_reset()
try:
# Make libraries shipped by the app importable
app_path = '/flash/' + '/'.join(path.split('/')[:-1])
sys.path.append(app_path)
mod = __import__(path)
if "main" in dir(mod):
mod.main()
except Exception as e:
import sys
import uio
import ugfx
s = uio.StringIO()
sys.print_exception(e, s)
ugfx.clear()
ugfx.set_default_font(ugfx.FONT_SMALL)
w=ugfx.Container(0,0,ugfx.width(),ugfx.height())
ugfx.Label(0,0,ugfx.width(),ugfx.height(),s.getvalue(),parent=w)
w.show()
raise(e)
import stm
stm.mem8[0x40002850] = 0x9C
import pyb
pyb.hard_reset()
def run():
loader = Loader()
kabuki.poll_input(loader)
sw = pyb.Switch()
sw.callback(loader.queue_reload)
while True:
try:
kabuki.run()
except Exception as exc:
sys.print_exception(exc)
_install_police_lights(loader)
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))
def stacktrace(e):
import uio
buf = uio.BytesIO()
sys.print_exception(e, buf)
return buf.getvalue()
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