单线程+异步协程(推荐):
-asyncio的一些关键字的说明:
- event_loop 事件循环:程序开启一个无限循环,把一些函数注册到事件循环上,当满足事件发生的时候,调用相应的协程函数
- coroutine 协程:协程对象,指一个使用async关键字定义的函数,它的调用不会立即执行函数,而是会返回一个协程对象。协程对象需要注册到事件循环,由事件循环调用。
- task 任务:一个协程对象就是一个原生可以挂起的函数,任务则是对协程进一步封装,其中包含了任务的各种状态
- async:async定义一个协程
- awati:await用于挂起阻塞方法执行。
测试1:
import asyncio async def do_something(sth): print("doing %s"%sth) print("done") c = do_something("eating")#该方法不会执行 返回一个协程对象 print(c) #结果 sys:1: RuntimeWarning: coroutine ‘do_something‘ was never awaited <coroutine object do_something at 0x0000014EE2EFD1C8>
测试2:
import asyncio async def do_something(sth): print("doing %s"%sth) print("done") c = do_something("eating")#该方法不会执行 loop = asyncio.get_event_loop()#创建loop loop.run_until_complete(c)#协程对象c 扔到loop中 触发执行 #结果 doing eating done
测试3(task的使用) 通过loop创建:
import asyncio async def do_something(sth): print("doing %s"%sth) print("done") c = do_something("eating") loop = asyncio.get_event_loop() task = loop.create_task(c) print(task) #pending 未执行 loop.run_until_complete(task) print(task) #finished 执行完毕 #结果 <Task pending coro=<do_something() running at C:/Users/86155/PycharmProjects/chapter_7/mybs4.py:48>> doing eating done <Task finished coro=<do_something() done, defined at C:/Users/86155/PycharmProjects/chapter_7/mybs4.py:48> result=None>
测试4(future的使用)通过 asynico创建:
import asyncio async def do_something(sth): print("doing %s"%sth) print("done") c = do_something("eating") loop = asyncio.get_event_loop() task = asyncio.ensure_future(c) print(task) loop.run_until_complete(task) print(task) #结果 <Task pending coro=<do_something() running at C:/Users/86155/PycharmProjects/chapter_7/mybs4.py:48>> doing eating done <Task finished coro=<do_something() done, defined at C:/Users/86155/PycharmProjects/chapter_7/mybs4.py:48> result=None>
测试5(回调)
import asyncioasync def do_something(sth): print(‘doing %s‘%sth) ##1 print(‘done‘) ##2 return sth #回调函数中的 result()def call_bask(task): print(task.result())c = do_something(‘running‘)loop = asyncio.get_event_loop()task = loop.create_task(c)#回调函数绑定任务对象task.add_done_callback(call_bask)loop.run_until_complete(task) #结果
doing running
done
running
原文地址:https://www.cnblogs.com/Jnhnsnow/p/11616547.html
时间: 2024-11-09 10:30:26