What is a Python replacement for the PHP function error_get_last ()?

I need to implement a atexitPython function that will receive the last error object and check its type. If the python error type matches PHP E_ERROR, I have to save the error output to a file.

The PHP code I'm porting looks like this:

register_shutdown_function( "fatal_handler" );
function fatal_handler() {
  $error = error_get_last();
    if ($error != null && $error['type'] === E_ERROR)
        echo  "recordFatalError: {$error['message']}\n";
}

My code binding is as follows:

def fatal_handler():
   # How to get last error object?

atexit.register(fatal_handler)

I would be glad if someone explained to me how I can get the necessary functionality using python.

+4
source share
2 answers

I would use sys.last_valuefor this:

import atexit
import sys

def fatal_handler():
    try:
        e = sys.last_value
    except AttributeError: # no exception prior to execution of fatal_handler
        return

atexit.register(fatal_handler)

getattr(sys, 'last_value', None) EAFP . None, sys.last_value .

, , , , sys.excepthook:

import sys

def fatal_handler(type, value, traceback):
   e = value

sys.excepthook = fatal_handler
+2

, sys.excepthook . sys.stderr. , . atexit:

import atexit
import sys

class LastException:
    value     = None
    type      = None
    trackback = None

    @staticmethod
    def excepthook(type,value,trackback):
        LastException.type      = type
        LastException.value     = value
        LastException.trackback = trackback

    @staticmethod
    def register():
        sys.excepthook = LastException.excepthook

def fatal_handler():
   print('{0} {1}'.format( LastException.type, LastException.value))

LastException.register()
atexit.register(fatal_handler)

raise BaseException("I am an error") 
# should print: <class 'BaseException'> I am an error
+1

Source: https://habr.com/ru/post/1649690/


All Articles