Python concurrent.futures: 线程没有启动

Python concurrent.futures: threads don't start

我制作了一个程序,它使用 concurrent.futures 启动 4 个线程并向列表中的每个网站发送请求。

问题:就是不启动

import requests
import threading
import concurrent.futures

list=['amazon.com', 'google.com', 'youtube.com', 'microsoft.com']

def start(url):
    requests.get('https://'+url)
    print(line+' finished')

with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
    for url in list:
        executor.submit(start, url)

另一方面,这有效:

import concurrent.futures

def start():
    print('lol')

with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
    for i in range(10):
        executor.submit(start)

您刚刚安排了任务,但没有等待结果,您的代码中有一个错误(使用未定义的变量),但是错误消息被上下文管理器“吞没”了。

executor.submit method returns a Future object where you can get the return value by calling result方法:

import requests
import threading
import concurrent.futures

URLS = ['amazon.com', 'google.com', 'youtube.com', 'microsoft.com']


def start(url):
    requests.get('https://' + url)
    print(f'{url}: finished')


def main():
    futures = []

    with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
        for url in URLS:
            futures.append(executor.submit(start, url))

        for future in futures:
            future.result()


if __name__ == "__main__":
    main()