python中协程的使用

python中协程的使用

在Python中,协程(Coroutines)是一种用户态的轻量级线程,它的切换开销极小。Python的asyncio库提供了对协程的原生支持,使得我们可以方便地使用协程来编写异步IO代码。

简单例子

import asyncio  
  
async def my_coroutine(number):  
    print(f"Starting coroutine {number}")  
    await asyncio.sleep(number)  # 模拟耗时操作  主动放弃cpu执行,调度其他协程
    print(f"Ending coroutine {number}")  
    return f"Result {number}"  

async def test():  
    # 创建一组协程  
    coroutines = [my_coroutine(3), my_coroutine(1)]  
      
    # 使用 asyncio.gather 并发执行协程  
    results = await asyncio.gather(*coroutines)  # 需要 *
      
    # 打印结果  
    for result in results:  
        print(result)  


def main():
    # Python 3.7+ 可以直接使用 asyncio.run() 来运行协程  
    asyncio.run(test())

main()

# 结果

'''
Starting coroutine 3
Starting coroutine 1
Ending coroutine 1
Ending coroutine 3
Result 3
Result 1

'''

文件aio

在Python中,可以使用asyncio库来编写执行文件I/O操作的协程。asyncio库提供了open_connection、read、write等底层函数来执行网络I/O操作,但是对于文件I/O,通常我们使用aiofiles库,它是一个基于asyncio的第三方库,用于异步文件操作。


import asyncio  
import aiofiles  
  
async def read_file(file_path):  
    async with aiofiles.open(file_path, mode='r') as f:  
        content = await f.read()  
        return content  
  
async def write_file(file_path, content):  
    async with aiofiles.open(file_path, mode='w') as f:  
        await f.write(content)  
  
async def main():  
    # 异步读取文件内容  
    file_content = await read_file('input.txt')  
    print(f"File content: {file_content}")  
      
    # 修改文件内容并异步写入  
    new_content = "New content to be written to the file.\n"  
    await write_file('output.txt', new_content)  
    print("File written successfully.")  
  
# 运行事件循环  
asyncio.run(main())

在这个例子中,定义了两个协程函数read_file和write_file,分别用于异步读取和写入文件。我们使用aiofiles.open来异步打开文件,并使用async with语句来确保文件在操作完成后被正确关闭。

  • 8
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值