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 zero
    

    But 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?


  • Banned

    This post is deleted!


  • 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) 
    


  • @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'
    >>>
    


  • 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'



  • Ah, perfect! Tanks muchly.



  • @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



  • Anybody out there manage to store traceback line numbers to a file on the gpy?



  • @kjm I'll have to check that tonight. I have no device here at the moment.



  • not on the gpy you can't!



  • @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.



  • @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)


Log in to reply
 

Pycom on Twitter