在 class __exit__ 中获取错误号
Get errno in class __exit__
我有一个 class,可以在 __init__
中创建当前目录的备份,并在出现任何问题时恢复备份。我认为这对于上下文管理器来说是一项很好的工作:
class Directory:
def __init__(self):
self._create_backup()
...
def __enter__(self):
return self
def __exit__(self, exit_type, exit_value, exit_traceback):
if exit_type is KeyboardInterrupt:
self._restore_from_backup()
sys.exit("Caught system interrupt. Aborting.")
# This is actually more complicated, but for the sake of MCVE
# Handle other exceptions here
else:
self._delete_backup()
现在,我想获取异常的 errno
属性,以检查它是否匹配 errno.EPERM
,但我不知道如何。
我不想在 exit_value
.
上使用诸如正则表达式匹配之类的骇人听闻的解决方案
IOError
实例具有属性 errno
,因此您需要如下内容:
def __exit__(self, exit_type, exit_value, exit_traceback):
if exit_type is KeyboardInterrupt:
self._restore_from_backup()
sys.exit("Caught system interrupt. Aborting.")
# This is actually more complicated, but for the sake of MCVE
elif exit_type is IOError:
if exit_value.errno == errno.EPERM:
# Handle your desired case
# Handle other exceptions here
else:
self._delete_backup()
编辑: 我假设 OP 导入 errno
因为他在问题中提到使用它但是当然 errno
模块之前需要以下行可以用
import errno
exit_value
是 class exc_type
的实例。您应该能够执行以下操作:
if isinstance(exit_value, OSError):
print(exit_value.errno)
如果你想捕获碰巧定义 errno
:
的其他异常,你也可以做类似下面的事情
errno = getattr(exit_value, 'errno', None)
if errno is not None:
print(errno)
我可能会使用后者,因为任何定义名为 errno
的属性的异常都可以与 errno.E*
常量进行比较。
我有一个 class,可以在 __init__
中创建当前目录的备份,并在出现任何问题时恢复备份。我认为这对于上下文管理器来说是一项很好的工作:
class Directory:
def __init__(self):
self._create_backup()
...
def __enter__(self):
return self
def __exit__(self, exit_type, exit_value, exit_traceback):
if exit_type is KeyboardInterrupt:
self._restore_from_backup()
sys.exit("Caught system interrupt. Aborting.")
# This is actually more complicated, but for the sake of MCVE
# Handle other exceptions here
else:
self._delete_backup()
现在,我想获取异常的 errno
属性,以检查它是否匹配 errno.EPERM
,但我不知道如何。
我不想在 exit_value
.
IOError
实例具有属性 errno
,因此您需要如下内容:
def __exit__(self, exit_type, exit_value, exit_traceback):
if exit_type is KeyboardInterrupt:
self._restore_from_backup()
sys.exit("Caught system interrupt. Aborting.")
# This is actually more complicated, but for the sake of MCVE
elif exit_type is IOError:
if exit_value.errno == errno.EPERM:
# Handle your desired case
# Handle other exceptions here
else:
self._delete_backup()
编辑: 我假设 OP 导入 errno
因为他在问题中提到使用它但是当然 errno
模块之前需要以下行可以用
import errno
exit_value
是 class exc_type
的实例。您应该能够执行以下操作:
if isinstance(exit_value, OSError):
print(exit_value.errno)
如果你想捕获碰巧定义 errno
:
errno = getattr(exit_value, 'errno', None)
if errno is not None:
print(errno)
我可能会使用后者,因为任何定义名为 errno
的属性的异常都可以与 errno.E*
常量进行比较。