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:
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)