0

[ Python ]如何取回生成器的返回值

 2 years ago
source link: https://www.v2ex.com/t/803110
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  Python

[ Python ]如何取回生成器的返回值

  MiketsuSmasher · 4 小时 16 分钟前 · 163 次点击

以下是一个校验文件的函数,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返回的校验结果?


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK