退出sched.scheduler模块时遇到问题?

时间:2015-01-02 02:26:56

标签: python multithreading selenium multiprocessing scheduler

我在我的程序中使用Selenium Webdriver以尝试自动化某些东西。然后我解析结果页面,并检查页面中的特定元素。如果页面没有特定元素,那么我使用sched.scheduler重新自动化任务,方法是让用户单击一个按钮(在Tkinter GUI中)。该按钮运行一个函数,该函数为sched.scheduler计划任务,并将任务发送到我从多处理模块创建新进程的函数。

这基本上就是这样:

import time
import sched
from multiprocessing import Process

#the function needs to run for the first time, then waits for user input if an error shows up
#if it's the second time around, the worker function runs the scheduler
global first_time_happening
first_time_happening = True
terminate = False
scheduler = sched.scheduler(time.time, time.sleep)


def worker():
    #insert some working process here using selenium webdriver
    print("Worker happened!")
    global first_time_happening
    if first_time_happening:
        first_time_happening = False
    elif not first_time_happening:
        global relay_to_timer
        relay_to_timer = scheduler.enter(5, 2, timer)
        scheduler.run()


def process():
    p = Process(target=worker)
    #p.daemon = True
    p.start()


def timer():
    if not terminate:
        global relay_to_process
        relay_to_process = scheduler.enter(5, 2, process)
        scheduler.run()
    if terminate:
        scheduler.cancel(relay_to_process)
        scheduler.cancel(relay_to_timer)


def quit_button():
    global terminate
    terminate = True
    if scheduler.empty:
        print("The line is empty")
    elif not scheduler.empty:
        print("Something in the queue!")
    while not scheduler.empty:
        scheduler.cancel(relay_to_process)
        scheduler.cancel(relay_to_timer)

worker()

#simulating where the GUI asks a question, person presses a button, and the button redirects them
#to function worker()

worker()

#simulating a user press the quit button
quit_button()

即使我“点击”退出(或在这种情况下调用退出函数),它仍然继续运行。我一直把队列排空,但我不确定为什么它不起作用?感谢任何帮助,谢谢!!

1 个答案:

答案 0 :(得分:1)

即使有人(大概是另一个线程)再次输入内容,调度程序仍会继续运行,即使是空队列也是如此。我相信让它结束的方法是引发异常(无论是来自动作还是延迟函数) - .run将传播它并且你可以捕获它。

嗯......

class AllDoneException(Exception): pass

def worker():
    #insert some working process here using selenium webdriver
    print("Worker happened!")
    global first_time_happening
    if first_time_happening:
        first_time_happening = False
    elif not first_time_happening:
        global relay_to_timer
        relay_to_timer = scheduler.enter(5, 2, timer)
        try:
            scheduler.run()
        except AllDoneException:
            pass

并且在函数timer

    if terminate:
        raise AllDoneException