将 python 个线程结果合并到一个列表中

Combine python thread results into one list

我正在尝试修改此处显示的解决方案: 除了检查 header 状态我正在发出 API 请求 returns 字典和我希望所有这些 API 请求的最终结果是所有词典的列表。

这是我的代码——假设 api_calls 是一个列表,每个 url 都可以为 json 请求打开...

from threading import Thread
from Queue import Queue

concurrent = 200 

def doWork():
    while True:
        url = q.get()
        result = makeRequest(url[0])
        doSomethingWithResult(result, url)
        q.task_done()

def makeRequest(ourl):
    try:
        api_call = urlopen(ourl).read()
        result = json.loads(api_call)
        return result, ourl
    except:
        return "error", ourl

def doSomethingWithResult(result, url):
  print(url,result)

q = Queue(concurrent * 2)
for i in range(concurrent):
    t = Thread(target=doWork)
    t.daemon = True
    t.start()
try:
    for url in api_calls:
        q.put(url)
    q.join()
except KeyboardInterrupt:
    sys.exit(1)

就像链接的例子一样,这目前将成功地在每一行打印 url,结果。相反,我想做的是将 (url, result) 添加到每个线程的列表中,然后在最后将它们加入一个主列表。我不知道如何获得这个主列表并在最后加入结果。有人可以帮助我在 doSomethingWithResult 中修改什么吗?如果我正在做一个大循环,我将只有一个空列表,并且我会在每个 API 请求后将结果附加到列表中,但我不知道如何模仿它,因为我现在正在使用线程。

我希望常见的回应是使用 https://en.wikipedia.org/wiki/Asynchronous_I/O,如果这是建议,那么我将不胜感激有人实际提供了一个与我上面链接的代码一样多的示例。

改用ThreadPool。它为您完成繁重的工作。这是一个获取一些 url 的工作示例。

import multiprocessing.pool
concurrent = 200 

def makeRequest(ourl):
    try:
        api_call = urlopen(ourl).read()
        result = json.loads(api_call)
        return "success", ourl
    except:
        return "error", ourl

def main():
    api_calls = [
        'http:http://jsonplaceholder.typicode.com/posts/{}'.format(i)
        for i in range(1,5)]

    # a thread pool that implements the process pool API.
    pool = multiprocessing.pool.ThreadPool(processes=concurrent)
    return_list = pool.map(makeRequest, api_calls, chunksize=1)
    pool.close()
    for status, data in return_list:
        print(data)

main()