美文网首页
Python 3.5以上异步IO用法示例

Python 3.5以上异步IO用法示例

作者: GloriousFool | 来源:发表于2023-08-01 20:15 被阅读0次
import asyncio
import time


async def say_hello_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

# 正常执行,异步操作,总耗时4秒。
async def say_hello_await_without_parenthesis_task():
    print(f"starts at {time.strftime('%X')}")
    task1 = asyncio.create_task(say_hello_after(4, "without_parenthesis_1"))
    task2 = asyncio.create_task(say_hello_after(2, "without_parenthesis_2"))
    await task1
    await task2
    print(f"ends at {time.strftime('%X')}")


# 无法运行,会提示task1和task2不是callable。
# 原因:asyncio.create_task返回的是asyncio.Task类型,而该类型本来就不是callable的,所以会报错。
async def say_hello_await_with_parenthesis_task():
    print(f"starts at {time.strftime('%X')}")
    task1 = asyncio.create_task(say_hello_after(2, "with_parenthesis_1"))
    task2 = asyncio.create_task(say_hello_after(4, "with_parenthesis_2"))
    await task1()
    await task2()
    print(f"ends at {time.strftime('%X')}")

# 正常执行,两次say_hello_after会串行执行,总耗时6秒。
# 原因:当await直接用在协程上的时候,会等待其执行完再执行下一条指令,相当于串行执行。
async def say_hello_with_coro():
    print(f"starts at {time.strftime('%X')}")
    await say_hello_after(4, "without_parenthesis_1")
    await say_hello_after(2, "without_parenthesis_2")
    print(f"ends at {time.strftime('%X')}")


# 无法运行,会提示coroutine没有被awaited。
def say_hello_with_direct_call():
    print(f"starts at {time.strftime('%X')}")
    say_hello_after(4, "without_parenthesis_1")
    say_hello_after(2, "without_parenthesis_2")
    print(f"ends at {time.strftime('%X')}")


if __name__ == '__main__':
    asyncio.run(say_hello_await_without_parenthesis_task())

相关文章

  • Python最新管理工具--pipenv

    前言 之前学习异步asyncio库的时候,因为asyncio库支持Python3.5以上的版本,而我的Ubuntu...

  • Python新利器之pipenv

    前言 之前学习异步asyncio库的时候,因为asyncio库支持Python3.5以上的版本,而我的Ubuntu...

  • Netty EventLoop与IO模型整理

    netty示例 maven依赖 echo服务器示例 echo服务器测试 IO模型 BIO模型 伪异步IO NIO模...

  • Python3:让不支持async的函数实现异步操作

    asyncio是Python3引入的异步IO功能,主要是在语言层面上解决IO阻塞的问题。 常规的用法是在主函数中运...

  • Python 异步IO - asyncio

    python 异步IO 本文为个人学习python asyncio模块的内容,可以看为python异步编程的入门。...

  • python 后台应用项目搭建(aiohtpp)

    通过本文章,可能获得以下能力 python 异步关键词 async 的用法 python aiphttp 异步框架...

  • python3中异步IO

    python2中的gevent通过协程已经实现了异步IO,python3中专门有一个模块来处理异步IO,ascyi...

  • python 异步IO

    线程池的使用+requests模块+回调函数 进程池的使用+requests模块+回调函数 asyncio + a...

  • Python 异步IO

    一、协程 执行结果 注意到consumer函数是一个generator,把一个consumer传入produce后...

  • Python 异步IO

    异步IO CPU的速度远远快于磁盘、网络等IO。在一个线程中,CPU执行代码的速度极快,然而,一旦遇到IO操作,如...

网友评论

      本文标题:Python 3.5以上异步IO用法示例

      本文链接:https://www.haomeiwen.com/subject/wzlupdtx.html