from concurrent.futures import ThreadPoolExecutor
urls = []
with ThreadPoolExecutor(max_workers=5) as executor:
for url in urls:
executor.submit(self.fetch_page, url).add_done_callback(self.check_and_parse)
time.sleep(1)
在一个线程池执行submit,爬取目标urls中的地址,并在完成后执行check_and_parse进行爬取内容解析。
这是预期的效果。
但是在实际运行后,发现如果不写time.sleep(1),或者间隔较小时,可能会只执行其中1,2个url。
看源文档并不需要额外的间隔才对。也没捕获到任何错误。
请问哪位大腿能给我点线索
做了一个关于submit的测试代码如下
from concurrent.futures import ThreadPoolExecutor
import time
def report_result(fu):
print(fu.result())
def do_some_thing(dly):
time.sleep(dly)
return dly
with ThreadPoolExecutor(max_workers=1) as executor:
for i in range(5):
executor.submit(do_some_thing, i).add_done_callback(report_result)
print("for end")
print("with end")
数据结果为:
for end
1
2
3
4
with end
应该可以证明with会在内部包含的future全部执行完成。包含其callback也执行完成后才会退出。
那我的这个问题。线索又断了吗。
原因是没有等待线程执行结束,程序就退出了。
submit函数会返回Future对象,你可用调用Future的result()函数等待线程结束。