Python重试的多重方法

栏目: Python · 发布时间: 7年前

内容简介:重试方法 (๑• . •๑)没人能保证自己的的程序没BUG,所以重试非常有必要。
这是崔斯特的第八十二篇原创文章

重试方法 (๑• . •๑)

Python重试的多重方法

没人能保证自己的的程序没BUG,所以重试非常有必要。

下面说下我知道的几种 Python 重试方法。

装饰器

这是最最简单的重试方法,而且有现成的轮子,推荐两个:

  1. retrying
  2. tenacity

两种用法比较类似,我经常用后者,看下

import random
from tenacity 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())

用法非常简单,直接加上装饰器。当然也可以有各种自定义。

from tenacity import *

@retry(stop=(stop_after_delay(10) | stop_after_attempt(5)), wait=wait_fixed(2))
def stop_after_10_s_or_5_retries():
    print("Stopping after 10 seconds or 5 retries")
    raise Exception

以上是重试5次,每次间隔10秒,重试前等待2秒。

捕获异常

这种方法更常见

def func():
    pass

for _ in range(0,100):
    while True:
        try:
            func()
        except SomeSpecificException:
            continue
        break

这里一定不要写成 except 或者 except Exception ,一定要指定异常,让别的错误打印出来,然后看日志再修改爬虫,或者会出现意想不到的情况。

举一个例:

def verify_url(url):
    import requests
    try:
        requests.get(url, timeout=10)
        return True
    except requests.exceptions.ConnectTimeout:
        return False


def main():
    for _ in range(5):
        try:
            if verify_url(''):
                return
            else:
                continue
        except KeyError:
            continue


if __name__ == '__main__':
    main()

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Agile Web Development with Rails 4

Agile Web Development with Rails 4

Sam Ruby、Dave Thomas、David Heinemeier Hansson / Pragmatic Bookshelf / 2013-10-11 / USD 43.95

Ruby on Rails helps you produce high-quality, beautiful-looking web applications quickly. You concentrate on creating the application, and Rails takes care of the details. Tens of thousands of deve......一起来看看 《Agile Web Development with Rails 4》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

MD5 加密
MD5 加密

MD5 加密工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换