示例代码:
import logging
import aiofiles
import asyncio
logging.basicConfig(filename='file.txt', level=logging.DEBUG)
async def write_to_file():
async with aiofiles.open('file.txt', 'a') as f:
await f.write('Hello, world!')
async def main():
tasks = [asyncio.create_task(write_to_file()) for i in range(10)]
await asyncio.gather(*tasks)
if __name__ == '__main__':
asyncio.run(main())
这将运行10个并发任务,并将它们的输出同时写入“file.txt”文件。其中,logging模块用于记录异步操作的状态和输出。