A
A
Andrew2013-12-27 17:30:57
Python
Andrew, 2013-12-27 17:30:57

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

Will it reload the page if it didn't load the first time?
How to make multithreading for this program?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Stepan, 2013-12-27
@L3n1n

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.

A
Andrew, 2013-12-27
@Wertz

And how to solve this problem without the help of a third-party library?

Y
Yuri Shikanov, 2013-12-27
@dizballanze

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 question

Ask a Question

731 491 924 answers to any question