标签:page range get super pre print requests put cep
利用python的线程实现简单生产者和消费者模式,这种模式在多线程编程时还是用的比较多吧,下面是源代码:
1 #!/usr/bin/python 2 # -*- coding: utf-8 -*- 3 import requests,time 4 import threading,queue 5 6 7 class mythread_1(threading.Thread): 8 def __init__(self,queue): 9 super(mythread_1,self).__init__() 10 self.queue = queue 11 def run(self): 12 try: 13 for i in range(5): 14 products = ‘http://www.mzitu.com/xinggan/page/‘+str(i) 15 self.queue.put(products) 16 time.sleep(1) 17 print(self.getName(),‘shengcan finish‘) 18 except: 19 print(‘field‘) 20 finally: 21 print(‘ok‘) 22 23 class mythread_2(threading.Thread): 24 def __init__(self,queue): 25 super(mythread_2,self).__init__() 26 self.queue = queue 27 28 def run(self): 29 try: 30 for i in range(5): 31 url = self.queue.get() 32 reponse = requests.get(url) 33 print(reponse.status_code) 34 time.sleep(1) 35 print(self.getName(),‘xiaofei finish‘) 36 except: 37 print(‘field‘) 38 finally: 39 print(‘ok‘) 40 def main(): 41 q = queue.Queue() 42 t1 = mythread_1(q) 43 t2 = mythread_2(q) 44 t1.start() 45 t2.start() 46 47 t1.join() 48 t2.join()
标签:page range get super pre print requests put cep
原文地址:http://www.cnblogs.com/Huangsh2017Come-on/p/7858109.html