我有一个代码,我尝试访问资源但有时它不可用,并导致异常。我尝试使用上下文管理器实现重试引擎,但我无法处理__enter__
上下文表单上下文管理器中调用者引发的异常。
class retry(object):
def __init__(self, retries=0):
self.retries = retries
self.attempts = 0
def __enter__(self):
for _ in range(self.retries):
try:
self.attempts += 1
return self
except Exception as e:
err = e
def __exit__(self, exc_type, exc_val, traceback):
print 'Attempts', self.attempts
这是一些只引发异常(我希望处理的异常)的例子
>>> with retry(retries=3):
... print ok
...
Attempts 1
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
NameError: name 'ok' is not defined
>>>
>>> with retry(retries=3):
... open('/file')
...
Attempts 1
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
IOError: [Errno 2] No such file or directory: '/file'
有没有办法拦截这个异常并在上下文管理器中处理它?</ p>
答案 0 :(得分:18)
引用__exit__
,
如果提供了异常,并且该方法希望抑制异常(即阻止其传播),则应返回真值。否则,异常将在退出此方法时正常处理。
默认情况下,如果您没有从函数中显式返回值,Python将返回None
,这是一个虚假值。在您的情况下,__exit__
返回None
,这就是为什么允许exeception流过__exit__
。
所以,返回一个真实的价值,就像这个
class retry(object):
def __init__(self, retries=0):
...
def __enter__(self):
...
def __exit__(self, exc_type, exc_val, traceback):
print 'Attempts', self.attempts
print exc_type, exc_val
return True # or any truthy value
with retry(retries=3):
print ok
输出将是
Attempts 1
<type 'exceptions.NameError'> name 'ok' is not defined
如果您想拥有重试功能,可以使用生成器实现,例如
def retry(retries=3):
left = {'retries': retries}
def decorator(f):
def inner(*args, **kwargs):
while left['retries']:
try:
return f(*args, **kwargs)
except NameError as e:
print e
left['retries'] -= 1
print "Retries Left", left['retries']
raise Exception("Retried {} times".format(retries))
return inner
return decorator
@retry(retries=3)
def func():
print ok
func()
答案 1 :(得分:8)
要处理__enter__
方法中的异常,最简单(也不那么令人惊讶)的事情就是将with
语句本身包装在try-except子句中,并简单地提出异常 -
但是,with
块被定义为不能像这样工作 - 本身就是“可重复的” - 这里有一些误解:
def __enter__(self):
for _ in range(self.retries):
try:
self.attempts += 1
return self
except Exception as e:
err = e
在那里返回self
后,上下文__enter__
运行不再存在 - 如果with
块内发生错误,它将自然地流向__exit__
} 方法。不,无论如何,__exit__
方法都无法使执行流程返回到with
块的开头。
你可能想要更像这样的东西:
class Retrier(object):
max_retries = 3
def __init__(self, ...):
self.retries = 0
self.acomplished = False
def __enter__(self):
return self
def __exit__(self, exc, value, traceback):
if not exc:
self.acomplished = True
return True
self.retries += 1
if self.retries >= self.max_retries:
return False
return True
....
x = Retrier()
while not x.acomplished:
with x:
...
答案 2 :(得分:2)
我认为这个很容易,而其他人似乎在过度思考它。只需将资源提取代码放在__enter__
中,然后尝试返回,而不是self
,但是获取了资源。在代码中:
def __init__(self, retries):
...
# for demo, let's add a list to store the exceptions caught as well
self.errors = []
def __enter__(self):
for _ in range(self.retries):
try:
return resource # replace this with real code
except Exception as e:
self.attempts += 1
self.errors.append(e)
# this needs to return True to suppress propagation, as others have said
def __exit__(self, exc_type, exc_val, traceback):
print 'Attempts', self.attempts
for e in self.errors:
print e # as demo, print them out for good measure!
return True
现在尝试一下:
>>> with retry(retries=3) as resource:
... # if resource is successfully fetched, you can access it as `resource`;
... # if fetching failed, `resource` will be None
... print 'I get', resource
I get None
Attempts 3
name 'resource' is not defined
name 'resource' is not defined
name 'resource' is not defined