一段代码理解Python异步函数async的基本用法

异步函数的使用规则

正常情况下我们的函数时串行的运行的,这里称之为主函数.

异步函数:与主函数并行运行.

Python异步函数即async必须在普通函数的命名前加上async

示例:

async def case_b():
    print('start', get_time(), 'case_b')
    await asyncio.sleep(1)
    print('end', get_time(), 'case_b')

执行async函数

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

async函数内等待:只阻塞当前async函数

await asyncio.sleep(2)

async函数的代码示例

m_mock安装

import asyncio
import time

from x_mock.m_mock import m_mock


def get_time():
    return m_mock.mock('@time("%H:%M:%S.%f")')


async def case_a():
    print('start', get_time(), 'case_a')
    await asyncio.sleep(2)  # 只阻塞当前函数,所以比case_b 多等 1s,下面这句最后打印
    print('end', get_time(), 'case_a')


async def case_b():
    print('start', get_time(), 'case_b')
    await asyncio.sleep(1)
    print('end', get_time(), 'case_b')


async def main():
    await asyncio.gather(
        case_a(),
        case_b()
    )


if __name__ == '__main__':
    start = time.time()
    # asyncio.run(main())  # 运行方式1

    # 运行方式2
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    print(time.time() - start)

通过上述代码示例可以发现case_a和case_b通过async并行运行了,但是case_a由于使用await等待2s比case_b的结果晚一秒出现.

打印异步函数的返回值示例

import asyncio
import time

from x_mock.m_mock import m_mock


def get_time():
    return m_mock.mock('@time("%H:%M:%S.%f")')


async def case_a():
    print('start', get_time(), 'case_a')
    await asyncio.sleep(2)  # 只阻塞当前函数,所以比case_b 多等 1s,下面这句最后打印
    print('end', get_time(), 'case_a')
    return 'case_a'


async def case_b():
    print('start', get_time(), 'case_b')
    await asyncio.sleep(1)
    print('end', get_time(), 'case_b')
    return 'case_b'


async def main():
    return await asyncio.gather(
        case_a(),
        case_b()
    )


if __name__ == '__main__':
    start = time.time()
    # asyncio.run(main())  # 运行方式1,不建议,会有一些报错

    # 运行方式2
    loop = asyncio.get_event_loop()
    print(loop.run_until_complete(main()))
    print(time.time() - start)

  • 8
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Python 中,异步接收的回调函数可以使用 `asyncio` 模块中的 `Protocol` 类来实现。`Protocol` 是一个抽象基类,用于定义异步网络协议。具体的实现中,需要定义一个继承自 `Protocol` 的类,并实现其中的方法。 下面是一个简单的例子,演示如何使用 `Protocol` 类实现异步接收的回调函数: ```python import asyncio class MyProtocol(asyncio.Protocol): def __init__(self, on_data_received): self.on_data_received = on_data_received def connection_made(self, transport): print('Connection made') self.transport = transport def data_received(self, data): print('Data received:', data) self.on_data_received(data) def connection_lost(self, exc): print('Connection lost') asyncio.get_event_loop().stop() async def main(): def on_data_received(data): print('Data received in callback:', data) loop = asyncio.get_event_loop() _, protocol = await loop.create_connection(lambda: MyProtocol(on_data_received), 'localhost', 1234) await asyncio.sleep(1) protocol.transport.write(b'Hello, world!') await asyncio.sleep(1) if __name__ == '__main__': asyncio.run(main()) ``` 在上面的例子中,`MyProtocol` 类继承自 `asyncio.Protocol`,并实现了 `connection_made`、`data_received` 和 `connection_lost` 三个方法。其中,`connection_made` 在连接建立时被调用,`data_received` 在接收到数据时被调用,`connection_lost` 在连接断开时被调用。 在 `main` 函数中,我们使用 `create_connection` 方法创建了一个与服务器的连接,并将 `MyProtocol` 类的实例作为回调函数传入。在回调函数中,我们定义了一个 `on_data_received` 函数,用于处理接收到的数据。当数据接收完成后,调用 `on_data_received` 函数进行处理。 最后,在 `main` 函数中,我们使用 `asyncio.sleep` 方法暂停了一段时间,然后向服务器发送了一条消息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Franciz小测测

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值