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语句来确保文件在操作完成后被正确关闭。