[英]What is Python replacement for PHP's error_get_last() function?
I need to implement an atexit
Python function that would get the last error object and check for it's type.我需要实现一个
atexit
Python 函数来获取最后一个错误对象并检查它的类型。 If the type of python error corresponds to PHP's E_ERROR
I should save the error's output to a file.如果 python 错误的类型对应于 PHP 的
E_ERROR
我应该将错误的输出保存到一个文件中。
The PHP code I'm porting looks like so:我正在移植的 PHP 代码如下所示:
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?
atexit.register(fatal_handler)
I would be glad if somebody explained me how can I get the necessary functionality with python.如果有人向我解释如何使用 python 获得必要的功能,我会很高兴。
I would usesys.last_value
for this:我会为此使用
sys.last_value
:
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)
You may choose to use getattr(sys, 'last_value', None)
in place of the EAFP approach above.您可以选择使用
getattr(sys, 'last_value', None)
代替上面的EAFP 方法。 It returns None
if sys.last_value
isn't available.如果
sys.last_value
不可用,则返回None
。
Alternatively, if there's just one function you want to run only when the interpreter shutdown is caused by an exception, you could usesys.excepthook
:或者,如果您只想在解释器关闭是由异常引起的时候运行一个函数,您可以使用
sys.excepthook
:
import sys
def fatal_handler(type, value, traceback):
e = value
sys.excepthook = fatal_handler
When an exception is raised and uncaught, the interpreter calls sys.excepthook with info about the exception.当异常被引发并未被捕获时,解释器调用sys.excepthook并提供有关异常的信息。 The default function prints out a given traceback and exception to sys.stderr.
默认函数将给定的回溯和异常打印到 sys.stderr。 You can replace this function with a function which save this data.
您可以用保存此数据的函数替换此函数。 Later you can use this data in your atexit handler:
稍后您可以在 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.