我正在替换使用 ThreadPoolExecutor
的服务器查询工具实现,改用所有异步调用使用 asyncio
和 aiohttp
。由于网络调用是非阻塞 IO,大部分转换都很直接,问题在于保存响应。
我使用的所有示例,甚至是两个库的文档,都使用 asyncio.gather()
收集所有可等待结果。在我的情况下,这些结果可能是几 GB 的文件,而我不想将它们存储在内存中。
有什么适当的方法来解决这个问题吗? 是使用 asyncio.as_completed()
然后:
for f in as_completed(aws):
earliest_result = await f
# Assumes `loop` defined under `if __name__` block outside coroutine
loop = get_event_loop()
# Run the blocking IO in an exectuor and write to file
_ = await loop.run_in_executor(None, save_result, earliest_result)
这是否引入了一个线程(假设默认情况下使用
ThreadPoolExecutor
),从而使这成为异步、多线程程序,而不是异步、单线程程序?此外,这是否确保每次只写入 1 个
earliest_result
到文件中?我不希望调用 await loop.run_in_executor(...)
,然后另一个结果出现,我尝试运行到同一个文件;我可以用一个信号量来限制。