python 协程

python :用@asyncio.coroutine装饰器生成的对象是一个生成器对象 但不是协程对象

               用async 定义的函数对象不是一个生成器,但是一个协程对象

 

import asyncio
from collections.abc import Coroutine,Generator
@asyncio.coroutine
def fun():
    print('sssss')

async def fun1():
    #yield  10
    print('end')
if __name__=='__main__':
    fun=fun()
    fun1=fun1()
    print(type(fun))
    print(isinstance(fun, Generator))
    print(isinstance(fun,Coroutine))

    print(type(fun1))
    print(isinstance(fun1, Generator))
    print(isinstance(fun1,Coroutine))

##
<class 'generator'>
True
False
<class 'coroutine'>
False
True
import asyncio

async def fun(tm):
    await asyncio.sleep(tm)
    print('hello>>>>>>>>%s'%tm)
    return 'sleep %s second'%tm

def callback(future):
    print('result-----%s'%(future.result()))
    
if __name__=='__main__':
    fun=fun(2)
    loop=asyncio.get_event_loop()
    task=asyncio.ensure_future(fun)#loop.create_task(fun)
    task.add_done_callback(callback) ##此定义一个回调 接收协程执行结果 与最后一行功能一亲
    loop.run_until_complete(task)
    #print(task.result())
import asyncio

async def fun(tm):
    print('wait>>>>>>>>%s'%tm)
    await asyncio.sleep(tm)
    return 'sleep %s second'%tm

def callback(future):
    print('result-----%s'%(future.result()))

if __name__=='__main__':
    # fun=fun(2)
    # loop=asyncio.get_event_loop()
    # task=asyncio.ensure_future(fun)#loop.create_task(fun)
    # task.add_done_callback(callback) ##此定义一个回调 接收协程执行结果 与最后一行功能一亲
    # loop.run_until_complete(task)
    #print(task.result())
    loop = asyncio.get_event_loop()
    dolist=[asyncio.ensure_future(fun(i)) for i in range(2,6)]
    loop.run_until_complete(asyncio.wait(dolist))
    for tk in dolist:
        print(tk.result())

  

  

  

posted @ 2023-12-06 14:43  howhy  阅读(6)  评论(0编辑  收藏  举报