好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

发生异常重试的处理方案

这篇文章主要给大家介绍了在Python中异常重试的解决方案,文中介绍的非常详细,相信对大家学习或者使用python具有一定的参考学习价值,需要的朋友们下面随着小编一起来看看吧。

def crawl_page(url):
 pass
 
def log_error(url):
 pass
 
url = ""
try:
 crawl_page(url)
except:
 log_error(url) 
attempts = 0
success = False
while attempts < 3 and not success:
 try:
  crawl_page(url)
  success = True
 except:
  attempts += 1
  if attempts == 3:
   break 
import random
from retrying import retry
 
@retry
def do_something_unreliable():
 if random.randint(0, 10) > 1:
  raise IOError("Broken sauce, everything is hosed!!!111one")
 else:
  return "Awesome sauce!"
 
print do_something_unreliable() 
def retry_if_io_error(exception):
 return isinstance(exception, IOError)
 
@retry(retry_on_exception=retry_if_io_error)
def read_a_file():
 with open("file", "r") as f:
  return f.read() 
def retry_if_result_none(result):
 return result is None
 
@retry(retry_on_result=retry_if_result_none)
def get_result():
 return None 

在执行 get_result 成功后,会将函数的返回值通过形参 result 的形式传入 retry_if_result_none 函数中,如果返回值是 None 那么就进行 retry ,否则就结束并返回函数值。

总结

【相关推荐】

1. 特别推荐 : “php程序员工具箱”V0.1版本下载

2. Python免费视频教程

3. Python基础入门教程

以上就是发生异常重试的处理方案的详细内容,更多请关注Gxl网其它相关文章!

查看更多关于发生异常重试的处理方案的详细内容...

  阅读:39次