无法使用Ctrl-c终止线程

时间:2013-11-17 03:23:45

标签: python python-3.x

我在python中创建了一个类似setInterval的函数,但cntrl-c无法终止它继承代码

import threading
def setInterval(sec,func,*args,**kw):
    def wrapper():
        setInterval(sec,func,*args,**kw) 
        func(*args,**kw) 
    t = threading.Timer(sec, wrapper)
    t.start()
    return t

这就是我要做的事情

>>> setInterval(3,print,"hello")
<Timer(Thread-1, started 6576)>
>>> hello
KeyboardInterrupt
>>> hello

在我按下ctrl-c后它继续运行。如果我使用键盘中断,我如何添加一些东西让它停止?

1 个答案:

答案 0 :(得分:0)

您可以使用Event以编程方式停止该线程:

import time
import threading

def setInterval(sec,func,*args,**kw):
    e = threading.Event()
    def wrapper():
        print('Started')
        while not e.wait(sec):
            func(*args,**kw)
        print('Stopped')
    t = threading.Thread(target=wrapper)
    t.start()
    return t,e

if __name__ == '__main__':
    try:
        t,e = setInterval(1,print,'hello')
        time.sleep(5)
    except KeyboardInterrupt:
        pass
    e.set()
    t.join()
    print('Exiting')

输出:

Started
hello
hello
hello
hello
Stopped
Exiting

按Ctrl-C:

Started
hello
hello
Stopped
Exiting