我在使用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')
2条答案
按热度按时间mdfafbf11#
你使用submit将所有数据一次性传递给函数,你需要使用map一次传递一个数据项,如下所示:
或者如果您需要继续使用submit,则必须自己拆分数据:
bqf10yzr2#
避免该错误的最简单编辑是更改
到
然而,这样它几乎等同于同步调用(我说“几乎”是因为一些代码仍然可以在
submit
和as_completed
之间执行,但是由于GIL,它本身应该是异步的或者调用一些IO)。如果希望函数
get_french_addresses
异步返回数据(在处理数据时),则必须重写它以支持这一点。