Exceptions in micro python
-
try: 1/0 except Exception as e: sys.print_exception(e)produces
division by zero Traceback (most recent call last): File "<stdin>", line 4, in <module> ZeroDivisionError: division by zeroBut I'd like to be able to store the error and the line number that produced it in a file instead of printing it. Storing the error is easy enough
with open('ErrorFile', 'wb') as f: f.write(str(e))but I can't figure out a way to access & store the line number. Anyone out there in the pycom firmament mastered this trick?
-
@kjm in documentation function prototype is
sys.print_exception(exc, file=sys.stdout)Have you try to open a file and use it with sys.print_exception to see what happened inside the file?
(Sorry i have no module to test) -
@eric73 just tried thst on windows MP. If you open a file beforehand, you can use that file handle as second argument to sys.print_exception.
-
not on the gpy you can't!
-
@kjm I'll have to check that tonight. I have no device here at the moment.
-
Anybody out there manage to store traceback line numbers to a file on the gpy?
-
@kjm You could do as follows:
try: 1/0 except Exception as e: import sys with open("error.log", "a") as f: sys.print_exception(e, f)This works for me,
Pycom MicroPython 1.20.0.rc6 [8d824a0-dirty] on 2019-01-28; FiPy with ESP32 -
Ah, perfect! Tanks muchly.
-
Hey Robert I need to filter out the double inverted commas before I store in the error.log file I tried
err=sys.print_exception(e) err=err.replace('"',"")but I got AttributeError: 'NoneType' object has no attribute 'replace'
-
@kjm follow these steps. I just executed at the prompt:
>>> from uio import StringIO >>> import sys >>> s = StringIO() >>> try: ... 1/0 ... except Exception as e: ... sys.print_exception(e, s) ... >>> x=s.getvalue() >>> x 'Traceback (most recent call last):\n File "<stdin>", line 2, in <module>\nZeroDivisionError: divis ion by zero\n' >>> -
Thnx again Robert, for anyone else with a similar requirement I ended up with....
except Exception as e: import sys; from uio import StringIO s=StringIO(); sys.print_exception(e, s) s=s.getvalue(); s=s.split('\n') line=s[1].split(','); line=line[1]; error=s[2]; err=error+line; print(err) with open ('error.log', 'a') as f: f.write(err) -
This post is deleted!
Hello! It looks like you're interested in this conversation, but you don't have an account yet.
Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.
With your input, this post could be even better 💗
Register Login