以下是一个校验文件的函数,algorithm_name
是哈希类型的名称,checksum
是已知的校验码。
def iter_check(filepath: str | bytes | os.PathLike[str | bytes], algorithm_name: str, checksum: str):
algorithm = get_algorithm(algorithm_name)
with open(filepath, mode='rb') as file:
algorithm_instance = algorithm()
for block in iter(partial(file.read, 1024), b''):
yield block
algorithm_instance.update(block)
return algorithm_instance.hexdigest() == checksum
其本质上是一个生成器,每一次迭代都会yield
一个block
。那么,能否取回最后由return
返回的校验结果?
1
chenstack 2021-09-21 00:58:04 +08:00
生成器迭代结束后会生成一个 StopIteration,返回值就是这个 StopIteration 的 value
def iter_check(): for i in range(5): yield i return 10 checker = iter_check() while True: try: print(next(checker)) except StopIteration as e: print("result: ", e.value) break |
2
BBCCBB 2021-09-21 09:41:01 +08:00
for 循环, 或者看一下 next 函数的用法.
|
3
O5oz6z3 2021-09-25 06:53:40 +08:00
基本原理已经被楼上说完了,至于你的需求可以很容易想到一个简单的实现,不知道有没有现成的:
class wrapiter: ... def __init__(self, _iter): ... ... self.iter = iter(_iter) ... ... self.val = None ... def __iter__(self): ... ... return self ... def __next__(self): ... ... try: ... ... ... return next(self.iter) ... ... except StopIteration as e: ... ... ... self.val = e.value ... ... ... raise it = wrapiter(range(9)) print([x for x in it]) print(it.val) |