如何将 asyncio 用于基本文件 IO
How to use asyncio for basic file IO
基本上我目前正在做以下事情:
for bigLogFile in bigLogFileFolder:
with open(bigLogFile) as bigLog:
processBigLogfile(bigLog)
由于我是从网络驱动器加载此日志文件,因此执行时间的大部分是等待文件加载。但是,processBigLogFile 的执行时间也很重要。
所以我的基本想法是使进程异步,允许程序在处理当前日志的同时加载下一个日志文件。
看起来很简单,但我对异步编程没有任何经验,asyncio 似乎提供了很多不同的方法来实现我想做的事情(使用 Task 或 Future 似乎是可能的候选者)。
谁能告诉我实现此目标的最简单方法? Asyncio 不是绝对必要的,但我更喜欢使用内置库
需要注意的是,日志文件必须顺序处理,所以我不能简单地并行加载和处理文件
当可以使用简单的 ThreadPoolExecutor 实现时,无需复杂的异步编码:
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=1) as tp:
for bigLogFile in bigLogFileFolder:
with open(bigLogFile) as bigLog:
data = bigLog.read()
tp.submit(process_data, data)
由于 ThreadPoolExecutor 在后台使用队列,因此只要 max_workers=1
.
就会保留处理顺序
此外,如果您有足够的内存来容纳 all/most 个文件,它也可以正常工作。如果您受内存限制,那么您必须等待 ThreadPoolExecutor 完成一些任务。
听起来您希望文件打开是并行的,但处理是顺序的。我不确定这是否会节省您的时间。
from concurrent.futures import ThreadPoolExecutor, as_completed
bigLogFileFolder = [...]
num = len(bigLogFileFolder)
pool = ThreadPoolExecutor(num)
futures = [pool.submit(open, bigLogFile) for bigLogFile in bigLogFileFolder]
for x in as_completed(futures):
processBigLogFile(x.result())
基本上我目前正在做以下事情:
for bigLogFile in bigLogFileFolder:
with open(bigLogFile) as bigLog:
processBigLogfile(bigLog)
由于我是从网络驱动器加载此日志文件,因此执行时间的大部分是等待文件加载。但是,processBigLogFile 的执行时间也很重要。
所以我的基本想法是使进程异步,允许程序在处理当前日志的同时加载下一个日志文件。 看起来很简单,但我对异步编程没有任何经验,asyncio 似乎提供了很多不同的方法来实现我想做的事情(使用 Task 或 Future 似乎是可能的候选者)。
谁能告诉我实现此目标的最简单方法? Asyncio 不是绝对必要的,但我更喜欢使用内置库
需要注意的是,日志文件必须顺序处理,所以我不能简单地并行加载和处理文件
当可以使用简单的 ThreadPoolExecutor 实现时,无需复杂的异步编码:
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=1) as tp:
for bigLogFile in bigLogFileFolder:
with open(bigLogFile) as bigLog:
data = bigLog.read()
tp.submit(process_data, data)
由于 ThreadPoolExecutor 在后台使用队列,因此只要 max_workers=1
.
此外,如果您有足够的内存来容纳 all/most 个文件,它也可以正常工作。如果您受内存限制,那么您必须等待 ThreadPoolExecutor 完成一些任务。
听起来您希望文件打开是并行的,但处理是顺序的。我不确定这是否会节省您的时间。
from concurrent.futures import ThreadPoolExecutor, as_completed
bigLogFileFolder = [...]
num = len(bigLogFileFolder)
pool = ThreadPoolExecutor(num)
futures = [pool.submit(open, bigLogFile) for bigLogFile in bigLogFileFolder]
for x in as_completed(futures):
processBigLogFile(x.result())