小编Sha*_*rku的帖子

实现重试例程

我有以下想法。是否可以在python中实现重试例程?这是我所做的一个简单示例。我想要一个更灵活的解决方案。独立于功能。因此,将 removeFile 与任何其他函数切换并摆脱 main 中的 while 循环。

import os
import time

def removeFile(file):

    try:
        os.remove(file)
        print("removed : "+file)
        return True
    except PermissionError:
        print("could not delete file "+file+" ; will try again")
        return False


if __name__ == "__main__":
    file = "some_path/file.ext"

    sucess = False
    maxCount = 5
    count = 0
    while not sucess:
        sucess = removeFile(file)
        count += 1
        if count == maxCount:
            sucess = True
            print("could not delete file "+file+" ; permission denied.")
        time.sleep(5)
Run Code Online (Sandbox Code Playgroud)

python python-3.x

2
推荐指数
1
解决办法
4204
查看次数

标签 统计

python ×1

python-3.x ×1