Python多处理/多线程->'Future'对象不可迭代

holgip5t  于 2023-02-01  发布在  Python
关注(0)|答案(2)|浏览(310)

我在使用ProcessPoolExecutor的"提交"功能时收到此错误。
发生异常:TypeError 'Future'对象不可迭代文件"C:....\test3.py",第28行,在as_completed(res)中的f:

import time
import json
import os
import requests
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from concurrent.futures import as_completed

BAN_API_URL = 'https://api-adresse.data.gouv.fr/search/'

def get_french_addresses(request):
    print(f"Started task with pid: {os.getpid()} fetch addresses: {request['search_field']}")
    query_params = {'q': request['search_field'], 'type': 'housenumber', 'autocomplete': 1}
    response = requests.get(BAN_API_URL, params=query_params)
    print(f"Finished task with pid: {os.getpid()} to address: {request['search_field']}")
    return json.loads(response.text)

request_data = [
    {'search_field': '17 rue saint maur'},
    {'search_field': '35 boulevard voltaire'},
    {'search_field': '32 rue rivoli'},
    {'search_field': 'Route de la Croqueterie'},
]
if __name__ == '__main__':
    start_time = time.time()
    # Execute asynchronously with multi threads
    with ProcessPoolExecutor() as executor:
        res = executor.submit(get_french_addresses, request_data)
        print(res)
        for f in as_completed(res):
            print(f.result())

    end_time = time.time()
    print(f'Total time to run multithreads: {end_time - start_time:2f}s')
mdfafbf1

mdfafbf11#

你使用submit将所有数据一次性传递给函数,你需要使用map一次传递一个数据项,如下所示:

res = executor.map(get_french_addresses, request_data)

或者如果您需要继续使用submit,则必须自己拆分数据:

res = []
with ProcessPoolExecutor() as executor:
        for item in request_data:
            res.append(executor.submit(get_french_addresses, item ))
        print(res)
        for f in as_completed(res):
bqf10yzr

bqf10yzr2#

避免该错误的最简单编辑是更改

for f in as_completed(res):

for f in as_completed([res]):

然而,这样它几乎等同于同步调用(我说“几乎”是因为一些代码仍然可以在submitas_completed之间执行,但是由于GIL,它本身应该是异步的或者调用一些IO)。
如果希望函数get_french_addresses异步返回数据(在处理数据时),则必须重写它以支持这一点。

相关问题