Answer the question
In order to leave comments, you need to log in
How to implement multithreading and exceptions?
Let's say we have the following code:
import re
from urllib2 import urlopen
startId = 5700
finalId = 6300
count = 0
totalWins = 0
pattern = "title=\'Fir\-tree defense\. Victories\: ([0-9]{1,2})"
for Id in range(startId, finalId):
print Id
try:
u = urlopen("http://site.com/pl.php?id="+str(Id))
data = u.read()
arr = re.findall(pattern, data)
if (len(arr) != 0):
count = count + 1
totalWins = totalWins + int(arr[0])
print Id, " ", arr[0]
except:
Id = Id - 1
print "Total players involved: ", count
print "Total wins: ", totalWins
u.close()
Answer the question
In order to leave comments, you need to log in
Use Grab . It is more functional and in the settings you can specify how many times to try to open the site with different errors.
Copes with multithreading with a bang.
If you want to repeat an action until it completes without throwing an exception, then you need to run an additional nested loop. In it, do break on else at the try construct. + here you can easily make a limited number of attempts.
p.s. catching exceptions without specifying the exception type is a very bad practice
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question