如何启动和终止正在运行的线程?
如何启动和终止正在运行的线程?
我目前正在编写自己的小型网络爬虫程序,尝试实现在将URL添加或从列表中删除时启动和终止线程的功能。目前我已经创建了以下代码:
import concurrent.futures import time import random import requests class WebScraper: def __init__(self): self.session = requests.Session() def run(self, url: str): while True: response = self.do_request(url) if response.status_code != 200: continue data = self.scrape_data(response) ... time.sleep(500) def do_request(self, url): response = self.session.get(url) return response def scrape_data(self, response): # TODO: 在这里实现你的网络爬虫逻辑 return {} if __name__ == '__main__': URLS_TO_TEST = [ "http://books.toscrape.com/catalogue/category/books/travel_2/index.html", "http://books.toscrape.com/catalogue/category/books/mystery_3/index.html", "http://books.toscrape.com/catalogue/category/books/historical-fiction_4/index.html", "http://books.toscrape.com/catalogue/category/books/sequential-art_5/index.html", "http://books.toscrape.com/catalogue/category/books/classics_6/index.html", ] with concurrent.futures.ThreadPoolExecutor() as executor: for url in URLS_TO_TEST: session = WebScraper() future = executor.submit(session.run, url) time.sleep(random.randint(10, 20)) URLS_TO_TEST.pop(random.randint(0, len(URLS_TO_TEST) - 1)) # 删除的URL也应该终止线程 time.sleep(random.randint(10, 20)) URLS_TO_TEST.append('http://books.toscrape.com/catalogue/category/books/health_47/index.html') # 添加的URL也应该启动新线程
我的问题是,我不确定是否可以在从主列表中删除URL时终止正在运行的线程,反之亦然。是否可以使用线程来实现这个功能?
以后的想法是通过数据库来设置URL_TO_TEST,而不是使用静态列表,并且将会动态更新,但这将在以后进行。
如何启动和终止正在运行的线程?
在Python中,可以使用观察者模式来实现。观察者模式是一种软件设计模式,用于在对象之间定义一种一对多的依赖关系,以便当一个对象的状态发生变化时,所有依赖于它的对象都会得到通知并自动更新。这可以通过在线程中使用观察者模式来启动和终止线程。
另一种方法是创建一个URL类,如上所示的代码。该类包含一个URL列表和一些用于控制线程的属性和方法。通过调用append_url方法,可以将新的URL添加到URL列表中,并在新的线程中运行WebScraper的run方法。调用delete_url方法可以终止指定URL的线程,并从URL列表中删除该URL。
此外,还提供了一个append_list方法,该方法接受一个URL列表,并使用线程池执行器在多个线程中并行地调用append_url方法。
通过使用这些方法和类,可以在Python中启动和终止正在运行的线程。这些方法和类可以根据具体的需求进行修改和扩展。