python queue 多线程取,Python - 非常简单的多线程并行URL提取(没有队列)

I spent a whole day looking for the simplest possible multithreaded URL fetcher in Python, but most scripts I found are using queues or multiprocessing or complex libraries.

Finally I wrote one myself, which I am reporting as an answer. Please feel free to suggest any improvement.

I guess other people might have been looking for something similar.

解决方案

Simplifying your original version as far as possible:

import threading

import urllib2

import time

start = time.time()

urls = ["http://www.google.com", "http://www.apple.com", "http://www.microsoft.com", "http://www.amazon.com", "http://www.facebook.com"]

def fetch_url(url):

urlHandler = urllib2.urlopen(url)

html = urlHandler.read()

print "'%s\' fetched in %ss" % (url, (time.time() - start))

threads = [threading.Thread(target=fetch_url, args=(url,)) for url in urls]

for thread in threads:

thread.start()

for thread in threads:

thread.join()

print "Elapsed Time: %s" % (time.time() - start)

The only new tricks here are:

Keep track of the threads you create.

Don't bother with a counter of threads if you just want to know when they're all done; join already tells you that.

If you don't need any state or external API, you don't need a Thread subclass, just a target function.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值