执行完某个tas后停止线程

2024-09-27 21:25:21 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我写了一些代码,当按下“停止”按钮时停止线程。它是有效的,但有一些注意事项。它往往会在一两秒钟内冻结资源,一旦有压力就会停止一切。我想停止按钮停止线程一旦它完成它正在做什么。在

以下是我为停止事件创建的函数:

def Stop(self, event):
    if myClass.worker != None:
        if myClass.browser!=None:
            while(myClass.browser.quit()!=None):
                myClass.browser.quit()
        myClass.worker.stop()
        myClass.worker = None
        while True:
            try:
                myfile = open(self.fpath, "r+")
                myfile.close()
                break
            except IOError:
                myClass.closeIt(self)
        os.unlink(self.fpath)
        os.rename(self.temp, self.fpath)

基本上,如果没有生成线程(因此不是没有),它会退出浏览器窗口,然后停止从浏览器上的网页中获取信息的线程。然后,它保存正在写入的文件。在

实际停止的线程是我创建的openExcel类的一个实例:

^{pr2}$

此类的实例调用一个名为findDomains的函数:

def findDomains(self,searchrow, numrows, sheet, wbook):
    for i in range(searchrow, numrows):
        domain = sheet.cell_value(i, 2)

        if domain == "":
            company = sheet.cell_value(i, 1)
            self.browser.get('https://www.google.com/')
            wait = WebDriverWait(self.browser, 300)
            inputGoogle=wait.until(EC.presence_of_element_located((By.NAME, "q")))
            inputGoogle.clear()
            inputGoogle.send_keys(company)
            inputGoogle.submit()

            self.browser.refresh()
            tries = 0
            while tries<1000:
                try:
                    domain=wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "cite._Rm")))
                    domain = domain.text
                    break
                except StaleElementReferenceException:
                    tries+=1
                    self.browser.refresh()

            domainlength=len(domain)
            period=0
            for charac in range(domainlength):
                if domain[charac]==".":
                    period+=1
            if period==1:
                if "//" in domain:
                    domain = domain.split("//",1)[1]
                index = domain.find("/")
                domain = domain[:index]
            elif period > 1:
                domain = domain.split(".",1)[1]
                index = domain.find("/")
                domain = domain[:index]

            checkdom=domain.split(".",1)[0]

            if (checkdom+".") not in domain:
                domain="error"

            worksheet.write(i,2,domain)
            wbook.save(file)

与其停止它在这个函数中所做的一切,我希望stop特性等到“domain”被保存到excel表中。一、 在试图关闭浏览器并退出之前,它必须先完成它正在做的事情。在


Tags: 函数inselfbrowsernoneindexifdomain

热门问题