Mar*_*ata 20
简答(简化).获取一个文件
import urllib
urllib.urlretrieve("http://google.com/index.html", filename="local/index.html")
Run Code Online (Sandbox Code Playgroud)
如有必要,您可以弄清楚如何循环.
Ign*_*ams 19
不要这样做.使用urllib2或urlgrabber替代.
Ada*_*eld 10
如果您使用它os.system()来生成进程wget,它将阻塞直到wget完成下载(或退出并出现错误).因此,只需os.system('wget blah')在循环中调用,直到下载完所有文件为止.
或者,您可以使用urllib2或httplib.您将不得不编写一个非常重要的代码,但是您将获得更好的性能,因为您可以重用单个HTTP连接来下载许多文件,而不是为每个文件打开一个新连接.
没理由使用os.system.避免在Python中编写shell脚本,并使用urllib.urlretrieve或类似的东西.
编辑...要回答问题的第二部分,您可以使用标准库Queue类设置线程池.由于您正在进行大量下载,因此GIL应该不是问题.生成要下载的URL列表并将其提供给工作队列.它将处理对工作线程的推送请求.
我正在等待数据库更新完成,所以我把它快速地放在一起.
#!/usr/bin/python
import sys
import threading
import urllib
from Queue import Queue
import logging
class Downloader(threading.Thread):
def __init__(self, queue):
super(Downloader, self).__init__()
self.queue = queue
def run(self):
while True:
download_url, save_as = queue.get()
# sentinal
if not download_url:
return
try:
urllib.urlretrieve(download_url, filename=save_as)
except Exception, e:
logging.warn("error downloading %s: %s" % (download_url, e))
if __name__ == '__main__':
queue = Queue()
threads = []
for i in xrange(5):
threads.append(Downloader(queue))
threads[-1].start()
for line in sys.stdin:
url = line.strip()
filename = url.split('/')[-1]
print "Download %s as %s" % (url, filename)
queue.put((url, filename))
# if we get here, stdin has gotten the ^D
print "Finishing current downloads"
for i in xrange(5):
queue.put((None, None))
| 归档时间: |
|
| 查看次数: |
71739 次 |
| 最近记录: |