python线程池的实现实例

yipeiwu_com6年前Python基础

直接上代码:

复制代码 代码如下:

# -*- coding: utf-8 -*-
import Queue
import threading
import urllib
import urllib2
import os

def down(url,n):
    print 'item '+str(n)+' start '
    filename=urllib2.unquote(url).decode('utf8').split('/')[-1]
    urllib.urlretrieve(url, filename)
    print 'item '+str(n)+' finish '


def worker():
    while True:
        i = q.get()
        url=i[0]
        n=i[1]
        down(url,n)
        q.task_done()


if __name__=="__main__":

    num_worker_threads=100

    f=open('url.txt')
    l=f.readlines()
    q = Queue.Queue()
    for i in range(num_worker_threads):
        t = threading.Thread(target=worker)
        t.daemon = True
        t.start()

    for i in range(0,len(l)):
        q.put((l[i],i))

    q.join()

相关文章

python调用新浪微博API项目实践

python调用新浪微博API项目实践

因为最近接触到调用新浪微博开放接口的项目,所以就想试试用python调用微博API。 SDK下载地址:http://open.weibo.com/wiki/SDK 代码不多十几K,完全可...

Python Matplotlib库安装与基本作图示例

Python Matplotlib库安装与基本作图示例

本文实例讲述了Python Matplotlib库安装与基本作图。分享给大家供大家参考,具体如下: 不论是数据挖掘还是数据建模,都免不了数据可视化的问题。对于Python来说,Matpl...

python创建临时文件夹的方法

本文实例讲述了python创建临时文件夹的方法。分享给大家供大家参考。具体实现方法如下: import tempfile, os tempfd, tempname = tempfi...

python 实现selenium断言和验证的方法

最近在学习自动化测试,网上资料是挺多的,但是都是很基础的,想深入一点了解就没有资料了。于是开始自己研究。 这两天在看selenium验证和断言方面的资料。 断言就是判断是否跟预期结果一致...

Django将默认的SQLite更换为MySQL的实现

1、注释默认的SQLite3配置: blogproject/settings.py ''' DATABASES = { 'default': { 'ENGINE': 'djan...