skip to Main Content

I’m having an hard time figuring out how to implement a simple retry function in Python, where my code should have to try to send a message to telegram for a fixed amount of times, and if after tot times it will still fail, print an error. Instead, if it succeeds, break and go on.

So i have the following array:

Retries = [1, 2, 3]

Which means that, if it fails, wait one second, and if it fails again wait 2 seconds and then 3 seconds.

Then i have the following code:

for x in Retries:
    try:
        updater.bot.send_message(chat_id='myid', text='TEST')
    except Exception as e:
        time.sleep(x)

This code will try three times and wait 1, 2, 3, seconds between each try, but the problem is that:

  1. Even if the message will be sent, it will still keep trying, while it needs to break
  2. If it will fail for three times, it should print an error, i don’t know how to do that

I found this library, but i think it’s overkill for such a simple task. Can anyone help me out on this?

2

Answers


  1. Use a break in the try block after sending the message like this –

    for x in Retries:
        try:
            print('Hi there')
            break #Add a break here
        except Exception as e:
            time.sleep(x)
    
    Hi there
    
    Login or Signup to reply.
  2. I recommend using pythons arcane but useful else clause for for loops:

    for x in Retries:
        try:
            updater.bot.send_message(chat_id='myid', text='TEST')
        except Exception as e:
            time.sleep(x)
        else:
            break
    else:
        # raise the real error here
    

    If the function call succeeds, your code will break out of the loop and not trigger the else clause. The else clause is only triggered if the loop completes without a break.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search