How to print traceback of last unhandled exception when reaching Micropython prompt #13593
Replies: 4 comments 7 replies
-
Why not put the sys.print_exception in your program?
|
Beta Was this translation helpful? Give feedback.
-
If I have the Python REPL open during program execution and an unhandled exception occurs, the traceback will already be printed on the console so I know exactly where in the code the exception occurred. But if the exception happens without the REPL open, then the traceback printout will be lost. So I am looking for a way to access the traceback opening the REPL after the exception has occured and the program has stopped. |
Beta Was this translation helpful? Give feedback.
-
What - exactly - is your specific problem with a catch-all exception handler ? If you want to see the exception (without constantly monitoring REPL output), catch it and save it somewhere (global variable, file, wherever) and (maybe) print it in parallel. In my opinion, the difference to other environments is minimal in this regard. If you want monitoring of your services, you will most likely need to add instrumentation to your code (e.g. logfiles, print to stdout/stderr, ...). Larger systems might give you some post-mortem analyzation possibilites (e.g. core dumps, docker logfiles, ...). Do you really expect this kind of features on a microcontroller with a few 100kB of memory ? |
Beta Was this translation helpful? Give feedback.
-
You can try logging your exceptions to a log file and setting a limit on the number of logs. It is best to write the log to a file on an SDcard, you can then read the card on your PC. import time, machine, sys
class ERR(Exception):
def __init__(self, n):
super().__init__()
self.n = n
self.c = 0
def log(self, error):
self.c += 1
if self.c < self.n:
with open('err.log', 'a+') as f:
f.write(f'{time.time()}: ')
sys.print_exception(error, f)
else:
machine.soft_reset() # or whatever you need And you can use it like this: >>> import exc
>>> err = exc.ERR(10)
>>> while 1:
... try:
... m = 23/0
... except Exception as e:
... err.log(e)
...
MPY: soft reboot
MicroPython v1.22.0 ....
>>> |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Suppose my Micropython program stops because it hits an unhandled exception. How can I print the traceback of this exception from the Micropython prompt ?
I found
sys.print_exception()
but it takes the exception value as argument andsys.last_exc
which should contain tha last exception value is not available in Micropython.Thanks, Ondrej
Beta Was this translation helpful? Give feedback.
All reactions