【问题标题】:Safely interrupt a program with threaded downloading通过线程下载安全地中断程序
【发布时间】:2011-06-11 03:20:43
【问题描述】:

我有一个(命令行/终端)程序,它使用从队列中下载的工作线程和一个下载索引文件(每页 50 个条目)的主线程来抓取网站。如何让程序检查中断(CTRL+C 或我自己定义的),当它捕获到这样的中断时,它会首先清理(下载剩余的队列)然后终止。

【问题讨论】:

    标签: python multithreading web-scraping


    【解决方案1】:

    在主循环中,您想要捕获 KeyboardInterrupt 异常(当用户按下 CTRL-C 时引发)。对于清理,你可以使用 atexit 模块运行一些全局清理函数或使用 threading.Event/threading.Condition 通知工作线程清理自己并退出。

    import atexit
    atexit.register(cleanup_function)
    

    【讨论】:

      【解决方案2】:

      使用这样的异常处理程序包装等待线程完成的主函数:

      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
      • 它是(现在仍然是)伪代码,无需添加额外的复杂性。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-15
      • 2012-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多