I've been poking about with threads for my first time, and came up with something that seems to work nicely, and not be horrid, as follows:
PHP Code:
import thread
import os
import urllib
import tempfile
def downloader(string_download, dict_return, int_retries = 5, string_path = False):
if string_path:
file_download = file(string_path +
string_download.split("/")[-1], "wb")
errors = 0
while True:
try:
file_temp = tempfile.NamedTemporaryFile("r+b")
file_http = urllib.urlopen(string_download)
file_temp.write(file_http.read())
endpos = file_temp.tell()
file_temp.seek(0)
file_download.write(file_temp.read(endpos))
file_download.close()
file_temp.close()
break #Not reached if urlerror
except:
errors += 1
if errors == int_retries:
dict_return[string_download] = False
else:
errors = 0
while True:
try:
file_temp = tempfile.NamedTemporaryFile("r+b")
file_temp.write(urllib.urlopen(string_download).read())
endpos = file_temp.tell()
file_temp.seek(0)
dict_return[string_download] = file_temp.read(endpos)
file_temp.close()
break #Also not reached if urlerror
except:
errors += 1
if errors == int_retries:
dict_return[string_download] = False
break
Ignoring the lines >80 characters long, and general lack of finesse or comments, I thought it was fairly good. If I call it in some sort of loop it works nicely, for instance:
PHP Code:
a=["www.google.com","www.bing.com","www.yahoo.com"]
b={}
for i in a:
thread.start_new_thread(downloader, (i,b))
And I get some fillings in b, and it all looks nice.
The thing is, I read this post on stackoverflow, on code quite similar to mine:
-1 for threads and suggesting the thread module and not doing any locking or even using the Queue module. You're just going to add way more complexity and locking overhead for no gain if you use threads. Even if this wasn't true, your code demonstrates that you don't really know how to use threads. –
And it worried me, 'cause mine works fine, and I like it.
(The code in question did some weird global variable messing instead of passing in the dictionary to "return" to, but apart from that, very similar.)
Should I be worried?
Bookmarks