How to display last traceback
-
I'm looking for a way to display the latest traceback. I have a wipy that runs a script for a long time so I disconnect it from the REPL, which means that when an error occurs I can't see the line number where it occurred. Definitely makes debugging difficult! I know that
sys.exc_info()
gives the exception that occurred but I also need to know where it occurred. Ideally, I'd like to just display the last traceback in the REPL when I reconnect to the device and to avoid try/catch statements because the code is long. Any ideas?
-
@crumble Not a bad work around! Thanks for your help.
-
You can write the output of print_exception() into a file
import sys try: raise ValueError('Hellas ', 1, 2, 3) except Exception as e: f2 = open('/sd/exceptions.txt', 'a') f2.write('\nException at: ' + str(rtc.now())) sys.print_exception(e, f2) f2.close()
reading it from REPL is not nice, but you can write a method for the UX
f2 = open('/sd/exceptions.txt', 'a') e = f2.read() print(e) f2.close()
The result will look like:
Exception at: (2019, 2, 19, 19, 46, 19, 620384, None)Traceback (most recent call last): File "main.py", line 101, in <module> ValueError: ('Hellas ', 1, 2, 3) Exception at: (2019, 2, 19, 19, 54, 55, 351626, None)Traceback (most recent call last): File "main.py", line 101, in <module> ValueError: ('Hellas ', 1, 2, 3)
I found an implementation of pickle, but it was not able to load string. So you can use only the output.
-
@crumble Thanks for the quick reply. Unfortunately the try/except method doesn't work after the error has occurred. If the device isn't connected to the REPL when the error occurs you cannot retrieve the traceback. I know you can save the exception to a file but I'd like to just print it in the REPL but after the error occurs.
-
import sys [...] except Exception as e: sys.print_exception(e)