【发布时间】:2011-06-11 03:20:43
【问题描述】:
我有一个(命令行/终端)程序,它使用从队列中下载的工作线程和一个下载索引文件(每页 50 个条目)的主线程来抓取网站。如何让程序检查中断(CTRL+C 或我自己定义的),当它捕获到这样的中断时,它会首先清理(下载剩余的队列)然后终止。
【问题讨论】:
标签: python multithreading web-scraping
我有一个(命令行/终端)程序,它使用从队列中下载的工作线程和一个下载索引文件(每页 50 个条目)的主线程来抓取网站。如何让程序检查中断(CTRL+C 或我自己定义的),当它捕获到这样的中断时,它会首先清理(下载剩余的队列)然后终止。
【问题讨论】:
标签: python multithreading web-scraping
在主循环中,您想要捕获 KeyboardInterrupt 异常(当用户按下 CTRL-C 时引发)。对于清理,你可以使用 atexit 模块运行一些全局清理函数或使用 threading.Event/threading.Condition 通知工作线程清理自己并退出。
import atexit
atexit.register(cleanup_function)
【讨论】:
使用这样的异常处理程序包装等待线程完成的主函数:
try:
main()
except KeyboardInterrupt:
stop()
def stop():
for t in threads:
t.my_stop_function()
# wait for threads to stop here...
class MyThread(threading.Thread):
def __init__(self, *args, **kwargs):
threading.Thread.__init__(self, *args, **kwargs)
self.stop = False
def my_stop_function(self):
self.stop = True
def run(self):
while not self.stop:
scrape()
【讨论】:
MyThread 应该源自threading.Thread。