gpt4 book ai didi

python - while 循环装饰器

转载 作者:行者123 更新时间:2023-11-30 22:49:32 26 4
gpt4 key购买 nike

我正在使用ftp库,它在下载一堆文件时非常挑剔。大约每 20 次尝试就会出错一次:

ftp.cwd(locale_dir)

所以,我解决这个问题的方法是:

while True:
try:
ftp.cwd(locale_dir)
except:
continue
break

我如何编写一个 python 装饰器来执行此操作,因为我必须在脚本中对大约 10 个 ftp 命令执行上述操作。如果我能有这样的东西那就太好了:

retry_on_failure(ftp.cwd(locale_dir))

最佳答案

您可以将装饰器创建为:

def retry_on_failure(count=10): # <- default count as 10
def retry_function(function):
def wrapper(*args, **kwargs):
while count > 0:
try:
func_response = function(view, request, *args, **kwargs)
break # <- breaks the while loop if success
except:
count -= 1
func_response = None
return func_response
return wrapper
return retry_function

现在使用此装饰器创建文件下载功能:

@retry_on_failure(count=20)  # <- will make attempts upto 20 times if unable to downlaod 
def download_file(file_name):
ftp.cwd(file_namee)

您可以将此装饰器与任何函数一起使用,在出现任何异常时需要重试(不仅仅是文件下载函数)。这就是装饰器的美妙之处,它们是任何函数都可以通用的;)

为了调用download_file功能,只需执行以下操作:

download_file(file_name)

关于python - while 循环装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39733131/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com