Function: Random Countdown for waiting in Python

I've waited enough to write this function.

Table of Contents

After writing too many times ad-hoc code for a random wait time, I decided to write a function for it, with nice output.

I'm using this function for example to generate random countdowns between pages visits for web scraping.

Code

import random
import time

wait_from = 7.8
wait_to = 9.7

def wait(wait_from, wait_to):
    wait_seconds = random.uniform(wait_from, wait_to)

    # sleep for the remaining decimal part of the seconds
    time.sleep(wait_seconds - int(wait_seconds)) 

    count_left = wait_seconds
    for w in range(int(wait_seconds), -1, -1):
        # rolling countdown
        print(f"\r{int(w)}", end='', flush=True)
        time.sleep(1)
        count_left -= 1

    # Clear the printed countdown
    print("\r", " " * len(str(int(wait_seconds))), end="\r", flush=True)

wait(wait_from, wait_to)

Demo

Explanation

As the function enable to wait for a random float number of seconds (ie with decimals), it starts by waiting for the decimal amount of time (eg. .39s if random number is 8.39s): time.sleep(wait_seconds - int(wait_seconds)).

Then it starts a countdown from the integer part of the random number (eg. 8s if random number is 8.39s) with int(wait_seconds).

For printing in place, using print(f"\r{int(w)}", end='').

And print("\r", " " * len(str(int(wait_seconds))), end="\r", flush=True) clears the countdown line when done.

Usage

It's also now added to my my_utils.py library my-utils

So I can easily import it and use it in other scripts as follows:

from my_utils import wait

wait_from = 7.8
wait_to = 9.7

wait(wait_from, wait_to)

links

social