event_loop:事件循环,相当于一个无限循环,我们可以把一些函数注册到这个事件循环上,当满足某些条件的时候,函数就会被循环执行coroutine:协程对象,我们可以将协程对象注册到事件循环中,他会被事件循环调用。我们可以使用 async 关键字来定义一个方法,这个方法在调用时不会立即被执行,而是返回一个协程对象task:任务,它是对协程对象的进一步封装,包含了任务的各个状态。future:代表将来执行或还没有执行的任务,实际和 task 没有本质区别。async:定义一个协程。await:用来挂起阻塞方法的执行。
import requests
import re
import time
from lxml
import etree
from multiprocessing
.dummy
import Pool
import asyncio
async def request(url
):
print('正在请求的url是: ', url
)
print('请求成功', url
)
return url
c
= request
('www.baidu.com')
'''
# 创建一个事件循环对象
loop = asyncio.get_event_loop()
# 将协程对象注册到loop中,然后启动loop
loop.run_until_complete(c)
'''
'''
# task的使用
loop = asyncio.get_event_loop()
task = loop.create_task(c)
# task的状态
print(task)
# 执行协程并启动
loop.run_until_complete(task)
print(task)
'''
'''
# future的使用
loop = asyncio.get_event_loop()
task = asyncio.ensure_future(c)
print(task)
loop.run_until_complete(task)
print(task)
'''
def callback_func(task
):
print(task
.result
())
loop
= asyncio
.get_event_loop
()
task
= asyncio
.ensure_future
(c
)
task
.add_done_callback
(callback_func
)
loop
.run_until_complete
(task
)
代码2
import requests
import re
import time
from lxml
import etree
from multiprocessing
.dummy
import Pool
import asyncio
async def request(url
):
print('正在下载: ', url
)
await asyncio
.sleep
(2)
print('下载完毕: ', url
)
start
= time
.time
()
urls
= {
'www.baidu.com',
'www.xiecheng.com',
'www.goubanjia.com'
}
stasks
= []
for url
in urls
:
c
= request
(url
)
task
= asyncio
.ensure_future
(c
)
stasks
.append
(task
)
loop
= asyncio
.get_event_loop
()
loop
.run_until_complete
(asyncio
.wait
(stasks
))
print(time
.time
()-start
)
转载请注明原文地址:https://tech.qufami.com/read-16925.html