Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can use a combination of a for loop and a try-except block to retry a command in Python. Here's an example of how you can do it for 5 retries with a sleep of 5 seconds between each retry:

import time

for i in range(5):
    try:
        # Your command goes here
        # For example, let's say you want to open a file named "example.txt"
        with open("example.txt", "r") as f:
            data = f.read()
        # If the command succeeds, break out of the loop
        break
    except Exception as e:
        # If the command fails, print the error message and wait for 5 seconds
        print(f"An exception occurred: {e}")
        time.sleep(5)
else:
    # If the command fails after 5 retries, print an error message
    print("Failed after 5 retries")

In this example, we're using a for loop to execute the command up to 5 times. If the command succeeds, we break out of the loop. If it fails, we catch the exception and print the error message. We then wait for 5 seconds using the time.sleep(5) function and try the command again.