ddnomad ddnomad - 2 months ago 6x
Python Question

What is Python replacement for PHP's error_get_last() function?

I need to implement an

Python function that would get the last error object and check for it's type. If the type of python error corresponds to PHP's
I should save the error's output to a file.

The PHP code I'm porting looks like so:

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 snap are as follows:

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


I would be glad if somebody explained me how can I get the necessary functionality with python.


I would use sys.last_value for this:

import atexit
import sys

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


You may choose to use getattr(sys, 'last_value', None) in place of the EAFP approach above. It returns None if sys.last_value isn't available.

Alternatively, if there's just one function you want to run only when the interpreter shutdown is caused by an exception, you could use sys.excepthook:

import sys

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

sys.excepthook = fatal_handler