恰好最近在学习python,而python能够很方便的支持多线程。找了些资料,使用threading+queue的方式实现了“能者多劳”的多线程截图方式: php
#coding:utf-8 import threading,urllib2 import datetime,time import Queue import os class Webshot(threading.Thread): def __init__(self,queue): threading.Thread.__init__(self) self.queue=queue def run(self): while True: #若是队列为空,则退出,不然从队列中取出一条网址数据,并截图 if self.queue.empty(): break host=self.queue.get().strip('\n') shotcmd="DISPLAY=:0 cutycapt --url=http://"+host+" --max-wait=90000 --out="+host+".jpg" os.system(shotcmd) self.queue.task_done() time.sleep(1) def main(): queue=Queue.Queue() f=file('domain.txt','r') #往队列中填充数据 while True: line=f.readline() if len(line)==0: break queue.put(line) #生成一个 threads pool, 并把队列传递给thread函数进行处理,这里开启10个线程并发 for i in range(0,10): shot=Webshot(queue) shot.start() if __name__=="__main__": main()
程序描述以下:
一、建立一个Queue.Queue() 的实例,将domain.txt里的网站列表存入到该队列中
二、for循环生成10个线程并发
三、将队列实例传递给线程类Webshot,后者是经过继承 threading.Thread 的方式建立的
四、每次从队列中取出一个项目,并使用该线程中的数据和 run 方法以执行相应的工做
五、在完成这项工做以后,使用 queue.task_done() 函数向任务已经完成的队列发送一个信号 html
参考:
Python:使用threading模块实现多线程(转)
http://bkeep.blog.163.com/blog/static/1234142902012112210717682/
http://fc-lamp.blog.163.com/blog/static/17456668720127221363513/
http://www.pythonclub.org/python-network-application/observer-spider
http://www.phpno.com/python-threading-2.html python