python已协程方式处理任务实现过程

yipeiwu_com5年前Python基础

这篇文章主要介绍了python已协程方式处理任务实现过程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

#从genent中导入monky模块①
from gevent import monkey
#把程序变成协程的方式运行②
monkey.patch_all()
import gevent,requests,time
#导入requests和time
start = time.time()
#记录程序开始时间
 
url_list = ['https://www.baidu.com/',
'https://www.sina.com.cn/',
'http://www.sohu.com/',
'https://www.qq.com/',
'https://www.163.com/',
'http://www.iqiyi.com/',
'https://www.tmall.com/',
'http://www.ifeng.com/']
#把8个网站封装成列表
 
def get_data(url):
  r = requests.get(url)
  # 用requests.get()函数爬取网站
  print(url, time.time()-start,r.status_code)
 
task_list=[]
# 创建一个空列表
for url in url_list:
  # 用gevent里面的spawn函数创建任务 get_data是方法名,url是参数③
  task=gevent.spawn(get_data,url)
  # 将创建的任务添加到task_list④
  task_list.append(task)
#执行任务列表中的所有任务⑤
gevent.joinall(task_list)
 
end = time.time()
#记录程序结束时间
print(end-start)
#end-start是结束时间减去开始时间,就是最终所花时间。

使用队列,代码如下:

#从genent中导入monky模块①
from gevent import monkey
#把程序变成协程的方式运行②
monkey.patch_all()
import gevent,requests,time
#从gevent库里导入queue模块
from gevent.queue import Queue
#导入requests和time
start = time.time()
#记录程序开始时间
 
url_list = ['https://www.baidu.com/',
'https://www.sina.com.cn/',
'http://www.sohu.com/',
'https://www.qq.com/',
'https://www.163.com/',
'http://www.iqiyi.com/',
'https://www.tmall.com/',
'http://www.ifeng.com/']
#把8个网站封装成列表
#创建队列对象,并赋值给work。
work=Queue()
for url in url_list:
  # 用put_nowait()函数可以把网址都放进队列里。
  work.put_nowait(url)
 
 
def get_data():
  # 当队列不是空的时候,就执行下面的程序。
  while not work.empty():
    # 用get_nowait()函数可以把队列里的网址都取出。
    url=work.get_nowait()
    r = requests.get(url)
    # 用requests.get()函数爬取网站 qsize队列长度
    print(url, work.qsize(),r.status_code)
 
task_list=[]
# 创建一个空列表
# 创建了2个爬虫
for x in range(2):
  # 用gevent里面的spawn函数创建任务 get_data是方法名
  task=gevent.spawn(get_data)
  # 将创建的任务添加到task_list④
  task_list.append(task)
#执行任务列表中的所有任务⑤
gevent.joinall(task_list)
 
end = time.time()
#记录程序结束时间
print(end-start)
#end-start是结束时间减去开始时间,就是最终所花时间。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python清除字符串中间空格的实例讲解

1、使用字符串函数replace >>> a = 'hello world' >>> a.replace(' ', '') 'helloworld...

python中的线程threading.Thread()使用详解

python中的线程threading.Thread()使用详解

1. 线程的概念: 线程,有时被称为轻量级进程(Lightweight Process,LWP),是程序执行流的最小单元。一个标准的线程由线程ID,当前指令指针(PC),寄存器集合和堆栈...

python中的格式化输出用法总结

本文实例总结了python中的格式化输出用法。分享给大家供大家参考,具体如下: Python一共有两种格式化输出语法。 一种是类似于C语言printf的方式,称为 Formatting...

python调用java的jar包方法

如下所示: from jpype import * jvmPath = getDefaultJVMPath() jars = ["./Firstmaven-1.0-SNAPSHO...

在OpenCV里使用特征匹配和单映射变换的代码详解

在OpenCV里使用特征匹配和单映射变换的代码详解

前面已经学习特征查找和对应匹配,接着下来在特征匹配之后,再使用findHomography函数来找出对应图像的投影矩阵。首先使用一个查询图片,然后在另外一张图片里找到目标对象,其实就是想...