Fundamentals 5 min read

Using Tenacity: A Python Retry Library – Installation, Unlimited Retries, Stop Conditions, Intervals, and Logging

This article introduces the Tenacity Python library, explains how to install it, and demonstrates various retry strategies such as unlimited retries, stopping after success, limiting attempts or time, combining stop conditions, setting fixed or random wait intervals, and adding pre‑ and post‑retry logging with complete code examples.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Using Tenacity: A Python Retry Library – Installation, Unlimited Retries, Stop Conditions, Intervals, and Logging

Tenacity is an Apache‑2.0 licensed, Python‑based generic retry library that simplifies adding retry behavior to many tasks, such as re‑running test cases, crawling scripts, or ticket‑booking attempts.

Installation

<code>pip install Tenacity</code>

Unlimited Retry

<code>from tenacity import retry

@retry()
def test_retry():
    print('失败重试中')
    raise Exception

test_retry()</code>

Stop After Success

<code>from tenacity import retry
import random

@retry()
def test_retry():
    if random.randint(0, 10) > 1:
        print('失败重试中')
        raise Exception
    else:
        print('成功')

test_retry()</code>

Limit Number of Attempts

<code>from tenacity import retry, stop_after_attempt
import random

@retry(stop=stop_after_attempt(7))
def test_retry():
    print('失败重试中')
    raise Exception

test_retry()</code>

Limit Total Retry Time

<code>from tenacity import retry, stop_after_delay
import random, time

@retry(stop=stop_after_delay(3))
def test_retry():
    time.sleep(1)
    print('失败重试中')
    raise Exception

test_retry()</code>

Combine Stop Conditions

<code>from tenacity import retry, stop_after_attempt, stop_after_delay
import random, time

@retry(stop=stop_after_delay(3) | stop_after_attempt(2))
def test_retry():
    time.sleep(1)
    print('失败重试中')
    raise Exception

test_retry()</code>

Fixed Retry Interval

<code>from tenacity import retry, wait_fixed
import random, time

@retry(wait=wait_fixed(2))
def test_retry():
    print('失败重试中')
    print(time.ctime())
    raise Exception

test_retry()</code>

Random Retry Interval

<code>from tenacity import retry, wait_random
import random, time

@retry(wait=wait_random(min=1, max=2))
def test_retry():
    print('失败重试中')
    print(time.ctime())
    raise Exception

test_retry()</code>

Log Before Each Retry

<code>from tenacity import retry, stop_after_attempt, before_log
import logging, sys

logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
logger = logging.getLogger(__name__)

@retry(stop=stop_after_attempt(3), before=before_log(logger, logging.DEBUG))
def test_retry():
    print('失败重试中')
    raise Exception('Fail')

test_retry()</code>

Log After Each Retry

<code>from tenacity import retry, stop_after_attempt, after_log
import logging, sys

logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
logger = logging.getLogger(__name__)

@retry(stop=stop_after_attempt(3), after=after_log(logger, logging.DEBUG))
def test_retry():
    print('失败重试中')
    raise Exception('Fail')

test_retry()</code>

The article concludes with a disclaimer that the content is collected from the internet and the original author retains copyright.

Exception HandlingLoggingretryCode Examplebackofftenacity
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.