我在使用 Beautiful Soup 迭代链接时遇到了类似的情况。这是我为此编写的代码:
class suppressed_iterator:
def __init__(self, wrapped_iter, skipped_exc = Exception):
self.wrapped_iter = wrapped_iter
self.skipped_exc = skipped_exc
def __next__(self):
while True:
try:
return next(self.wrapped_iter)
except StopIteration:
raise
except self.skipped_exc:
pass
class suppressed_generator:
def __init__(self, wrapped_obj, skipped_exc = Exception):
self.wrapped_obj = wrapped_obj
self.skipped_exc = skipped_exc
def __iter__(self):
return suppressed_iterator(iter(self.wrapped_obj), self.skipped_exc)
一个例子:
class IHateThirteen:
''' Throws exception while iterating on value 13 '''
def __init__(self, iterable):
self.it = iter(iterable)
def __iter__(self):
return self
def __next__(self):
v = next(self.it)
if v == 13:
raise ValueError('I hate 13!')
return v
# Outputs [10, 11, 12, 14, 15]
exception_at_thirteen = IHateThirteen([10, 11, 12, 13, 14, 15])
print(list(suppressed_generator(exception_at_thirteen)))
# Raises ValueError
exception_at_thirteen = IHateThirteen([10, 11, 12, 13, 14, 15])
print(list(exception_at_thirteen))
您可以使用上面的代码来修复您的代码:
for subdir, dirs, files in suppressed_generator(os.walk(path)):
do something...
如果需要,上面的代码可以扩展为每个跳过的异常类型都有回调,但在这种情况下使用iCodez's answer 可能更符合pythonic。