【发布时间】:2014-01-22 07:25:30
【问题描述】:
我在数据库中有一些我想并行下载的链接。我试着连续做,但花了太多时间。我有大约 1877 个链接。
我尝试使用此代码并行运行下载,但它引发错误:失败:'tuple' object has no attribute 'read'
#!/usr/bin/env python
import urllib
from stream import ThreadPool
URLs = [
'http://www.cnn.com/',
'http://www.bbc.co.uk/',
'http://www.economist.com/',
'http://nonexistant.website.at.baddomain/',
'http://slashdot.org/',
'http://reddit.com/',
'http://news.ycombinator.com/'
]
def retrieve(urls):
for url in urls:
print url,' '
res = urllib.urlretrieve(url).read()
yield url, res
if __name__ == '__main__':
retrieved = URLs >> ThreadPool(retrieve, poolsize=7)
for url, content in retrieved:
print '%r is %d bytes' % (url, len(content))
for url, exception in retrieved.failure:
print '%r failed: %s' % (url, exception)
我也试过了:
import urllib
import tldextract
from multiprocessing.pool import ThreadPool
URLs = [
'http://www.cnn.com/',
'http://www.bbc.co.uk/',
'http://www.economist.com/',
'http://nonexistant.website.at.baddomain/',
'http://slashdot.org/',
'http://reddit.com/',
'http://news.ycombinator.com/'
]
def dwld(url):
print url
res = urllib.urlopen(url).read()
filename = tldextract.extract(url)
with open(filename.domain, 'wb') as fh:
fh.write(res)
return url
pool = ThreadPool(processes = 4)
pool.map(dwld, URLs)
给我 回溯(最近一次通话最后): 文件“dwld_thread.py”,第 26 行,在 pool.map(dwld,网址) 文件“/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/multiprocessing/pool.py”,第 148 行,在地图中 return self.map_async(func, iterable, chunksize).get() 文件“/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/multiprocessing/pool.py”,第 422 行,在 get 提高自我价值 IOError: [Errno socket error] [Errno 8] nodename or servname provided, or not known
【问题讨论】:
-
您使用的“流”库是什么?
-
我认为您的第二个版本的问题是您想调用
pool.close()和pool.join()(或者,更好的是,只需使用with语句,如果这适用于您的版本......我忘记多处理Pools 何时成为上下文管理器)。
标签: python