[Python] python threads, how to store results from a multithread code
Manlio Perillo
manlio.perillo a gmail.com
Sab 10 Dic 2011 17:58:26 CET
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Il 09/12/2011 21:18, Massimo Di Stefano ha scritto:
> Ciao,
>
> sto provando ad imparare ad usare la libreria thread … ma ho dei problemi :-(
>
> il mio obiettivo e' il download di alcuni file da internet con urlib
> salvarli in un file temporaneo
> e scrivere in una lista il path di tali file.
>
> is codice di seguito, e' scarica i file e li salva come file temporanei
> … ma non riesco a capire come salvarne una lista dei path.
>
> ########################################################################################
> # thread test
>
> import threading
> import urllib
> from tempfile import NamedTemporaryFile
>
> class download(threading.Thread):
> def __init__(self, sitecode):
> threading.Thread.__init__(self)
> self.sitecode = sitecode
> self.status = -1
>
> def run(self):
> #global filelist
> #filelist = []
> url = 'http://waterdata.usgs.gov/nwis/monthly?referred_module=sw&site_no='
> url += self.sitecode
> url += '&PARAmeter_cd=00060&partial_periods=on&format=rdb&submitted_form=parameter_selection_list'
> tmp = NamedTemporaryFile(delete=False)
> urllib.urlretrieve(url, tmp.name)
> print 'loaded Monthly data for sitecode : ', self.sitecode
> #filelist.append(tmp.name)
> #return filelist
>
>
>
> sitecodelist = ['01046500', '01018500', '01010500', '01034500', '01059000', '01066000', '01100000']
>
> for k in sitecodelist:
> get_data = download(k)
> get_data.start()
>
Se preferisci restituire filelist dal thread, allora devi fare il join
di ciascun thread:
tasks = []
for k in sitecodelist:
thread = download(k)
tasks.append(thread)
thread.start()
filelist = [thread.join() for thread in tasks]
print filelist
> [...]
Ciao Manlio
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.10 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/
iEYEARECAAYFAk7jj7IACgkQscQJ24LbaUSs/QCfTj8qxHR+et3OSYiAMlLP99jF
MJcAn0qmt3yIXSiAdb6gWbo0Bg+u+Kcr
=njSp
-----END PGP SIGNATURE-----
Maggiori informazioni sulla lista
Python