Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error trying to add +1 second of sleep for a retry

In this example I try to activate main() again in case there is an error in one():

from random import randrange
import sys
import time

def one():
    number = randrange(2)
    1/number

def main():
    try:
        one()
    except:
        sleep_time = 0
        while True:
            print('Error')
            sleep_time += 1
            print('Next attempt in: '+ str(sleep_time) + ' second(s)')
            time.sleep(sleep_time)
            main()
            sys.exit(1)

    print('Continue')

main()

When two errors occur in a row, it keeps giving a 1 second pause:

Error
Next attempt in: 1 second(s)
Error
Next attempt in: 1 second(s)
Continue

What I’m actually looking for would be an answer like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Error
Next attempt in: 1 second(s)
Error
Next attempt in: 2 second(s)
Continue

How should I proceed?

>Solution :

You are overwriting sleep_time back to zero with every recursive call to main Assign it as a param of the function

def main(sleep_time=0):
    try:
        one()
    except:
        while True:
            print('Error')
            sleep_time += 1
            print('Next attempt in: '+ str(sleep_time) + ' second(s)')
            time.sleep(sleep_time)
            main(sleep_time=sleep_time)
            sys.exit(1)

    print('Continue')

out

Error
Next attempt in: 1 second(s)
Error
Next attempt in: 2 second(s)
Error
Next attempt in: 3 second(s)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading