我有以下问题。我正在尝试重构我的代码以便使用多线程处理 API 调用。我的核心数据是以下格式的简单元组列表:
lst = [('/Users/sth/photo1.jpg',
'/Users/sth/photo2'),
('/Users/sth/photo1.jpg',
'/Users/sth/photo3'), (...)]
我使用的函数获取 lst 列表并通过需要一对照片的 API 对其进行处理。毕竟每对返回一个数字。到目前为止,我正在使用一个循环将一个元组放入我的函数中并生成提到的数字。我想以一种方式并行化整个计算,即一个进程占用我的列表的一部分并调用批处理中元组的函数。为此,我尝试对多处理模块使用池函数:
from multiprocessing.dummy import Pool as ThreadPool
pool = ThreadPool(2)
results = pool.map(score_function, lst)
但是,出现以下错误:
IOError: [Errno 2] No such file or directory: 'U'
这里发生了一些奇怪的事情。它试图将我的元组中的单个字符视为参数。任何想法如何正确地做到这一点?
谢谢
@编辑
缺少 score_function 定义是我的错。让我更新问题:
def score_function(pairs):
score_list = list()
for pair in pairs:
score = findElement(target = pair[0], source = pair[1])
score_list.append([pair[0], pair[1], score])
return score_list
其中 findElement 定义为:
def findElement(target, source):
with open(source, 'rb') as source_:
source_bytes = source_.read()
with open(target, 'rb') as target_:
target_bytes = target_.read()
score = API_request(target_bytes = target_bytes,
source_bytes = source_bytes)
return score
请您参考如下方法:
您可以使用 starmap函数而不是像这样的映射:
from multiprocessing import Pool
pool = Pool(processes=4)
results = pool.starmap(score_function, lst)
pool.close()
pool.join()
