• 技术文章 >Python技术 >Python基础教程

    python之asyncio三种应用方法

    尤及尤及2020-06-01 17:30:06转载2541

    python之asyncio三种应用方法:

    1、直接使用asyncio.run方法

    1

    2

    3

    4

    5

    6

    7

    import asyncio

    #第一种

    async def aa():   

        print("我们的门又坏了")   

        await asyncio.sleep(2)   

        print("怎么办啊")

    asyncio.run(aa())

    2、同步的效果,用await调用函数

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    async def fun1():

        print("增强体育锻炼,提高免疫力")

        await asyncio.sleep(3)

        print("才能保证身体健康,诸事顺利")

    async def fun2():

        await asyncio.sleep(5)

        print("这个周末天气不错")

        await asyncio.sleep(8)

        print("可是你就是不想出去")

    async def min():

        await fun1()

        await fun2()if __name__ == "__main__":

        asyncio.run(min())

    3、创建任务(asyncio.create_task),并发运行任务(await asyncio.gather)

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    arr = []

    async def produce():

        for i in range(100):

            await asyncio.sleep(1)

            arr.append(i)

            print("小明放了一个鱼丸,现在锅里还有%s个鱼丸"%len(arr))

    async def consumer():

        while True:

            await asyncio.sleep(2)   #很关键

            if len(arr)>=10:  #各一个判断条件

                arr.pop()

                print("mony吃了一个鱼丸,现在锅里还有%s个鱼丸"%len(arr))

    async def main():

        t1 = asyncio.create_task(produce())   #创建任务

        t2 = asyncio.create_task(consumer())

        await asyncio.gather(t1,t2) #并发运行任务asyncio.run(main())  #调用函数main()

    专题推荐:python
    上一篇:四个python小练习 下一篇:python如何随机生成数组

    相关文章推荐

    • python的注释为什么报错• python中的if判断语句怎么写• Python中的gbk怎么转化成utf• python一个数组六个数字如何分别调用• python输出怎么不要空格• 四个python小练习

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网