Ask Your Question
1

Python: How can I retry a command several times in case of an Exceptions with a Sleep?

asked 2023-04-25 20:00:00 +0000

wagner gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-04-25 20:01:00 +0000

wagner gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

1 follower

Stats

Asked: 2023-04-25 20:00:00 +0000

Seen: 25 times

Last updated: Apr 25 '23