Reputation: 3
For my application, I am using python interface to read registers of a microcontroller. Sometimes, the read fails and causes an Exception. Ideally what I'd like to do is on an exception, I would like to go back to the same line that had an exception and redo it. This means, essentially go back to the statement that failed at reading a register. I can for a single read do the following:
while ReadSuccess == 0:
try:
readregister();
faultReadSuccess = 1
except (KeyboardInterrupt, SystemExit):
print "Program manually stopped through Ctrl-C"
raise
except:
faultReadSuccess = 0
print "Reading failure"
time.sleep(.5)
This essentially on a single read just repeats the read till it passes. However, I have several register read commands scattered through my program and these are flow-sensitive reads, and I can't just start at the beginning of the code or a section of code with the reads through a while loop or something. Rather, if a read fails, I need to directly redo that read again till it passes and then continue on.
However, I do no know how to do this without for each individual read, do the code mentioned above. I tried looking for a "jump to"/"go to" the previous line equivalent, but I cannot find anything. Is there something that would allow me to on exception just repeat the line that failed?
Upvotes: 0
Views: 815
Reputation: 4504
I suggest you create a new function to retry the read_register(), and pass a parameter to control how many times you'd like to retry. For example, to define a function like:
def read_retry(read_reg, n):
"""
"read_reg" is one of your read_register functions;
"n" is the retry times.
"""
i = 0 # i is the counter
while i < n:
try:
read_reg()
break # if success, then exit the loop
except:
print "Reading failure for {} time(s)".format(i+1)
time.sleep(0.5)
i = i + 1
Say, you want to retry read_register_1()
for 3 times. Just call read_retry(read_register_1, 3)
.
Upvotes: 2
Reputation: 10389
so you'll have to do something like this:
while True:
try:
read_register_1()
except:
time.sleep(0.5)
else:
break
while True:
try:
read_register_2()
except:
time.sleep(0.5)
else:
break
Upvotes: 0