My Python wait function

11 Apr 2023

I have plenty of scripts where I need to wait (eg visiting throttled websites, scraping runs, etc..) and like to see a countdown of that wait to monitor my script.

Here is the function I use across all my scripts. Added to my utils my-utils

import random
import time

def wait(wait_from, wait_to=0, start=False):
    # Enable to pass only an exact number of seconds to wait, with only passing `wait_from`
    if wait_to == 0:
        wait_to = wait_from

    # To avoid waiting if function in last iteration of a loop
    if not start:
        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): # stop at 0 if you want 1 to be the last countdown number printed, else -1 for 0
        # rolling countdown
        if w < 10:
            countdown_str = f"\r0{int(w)}"
            countdown_str = f"\r{int(w)}"
        print(countdown_str, end='', flush=True)
        count_left -= 1

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