相思资源网 Design By www.200059.com
这篇文章主要介绍了Python 异步协程函数原理及实例详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
一、 asyncio
1.python3.4开始引入标准库之中,内置对异步io的支持
2.asyncio本身是一个消息循环
3.步骤:
(1)创建消息循环
(2)把协程导入
(3)关闭
4.举例:
import threading
# 引入异步io包
import asyncio
# 使用协程
@ asyncio.coroutine
def hello():
print("Hello World!(%s)" % threading.current_thread())
print("Start......(%s)" % threading.current_thread())
yield from asyncio.sleep(5)
print("Done.....(%s)" % threading.current_thread())
print("Hello again!(%s)" % threading.current_thread())
# 启动消息循环
loop = asyncio.get_event_loop()
# 定义任务
tasks = [hello(), hello()]
# asyncio使用wait等待task执行完毕
loop.run_until_complete(asyncio.wait(
tasks))
# 关闭消息循环
loop.close()
二、asyncio and await
1.为了更好的表示异步io
2.python3.5引入
3.让协程代码更加简洁
4.使用上,可以简单的进行替换
(1)用async来替换@asyncio,coroutine
(2)用await来替换yield from
按照上面这个语法可以来改写前面的例子,运行结果是完全一致的
三、aiohttp
1.asyncio实现单线程的并发io,在客户端用处不大
2.在服务端可以asyncio+coroutine配合,因为http是io操作
3.asyncio实现了tcp,udp,ssl等协议
4.aiohttp是基于asyncio实现的http框架
5.例子:
import asyncio
from aiohttp
import web
"<h1>Index</h1>")
"<h1>hello,%s!</h1>" % request.match_info[
"name"]
return web.Response(body = text.encode(
"utf-8"))
"GET", "/", index)
app.router.add_route("GET",
"/hellp/{name}", hello)
srv = await loop.create_server(app.make_handler(),
"127.0.0.1", 8000)
print(
"Server started at http://127.0.0.1:8000..."
)
return srv
"htmlcode">
import time
from concurrent.futures
import ThreadPoolExecutor
"hello")
f2 = pool.submit(return_future, "world")
time.sleep(1)
# 等待执行完毕
print(f1.done())
time.sleep(3)
print(f2.done())
# 结果
print(f1.result())
print(f2.result())
源码
d28_1_asynchronization_examples.py
https://github.com/ruigege66/Python_learning/blob/master/d28_1_asynchronization_examples.py
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
标签:
python,异步,协程,函数
相思资源网 Design By www.200059.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
相思资源网 Design By www.200059.com
暂无Python 异步协程函数原理及实例详解的评论...

