简体   繁体   中英

Can't terminate thread with Ctrl-c

I've created a setInterval like function in python but cntrl-c can't terminate it Heres the code

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

And here's what I do to run it

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

It continues to run after I've hit ctrl-c. How would I add something to have it stop if I use the keyboard interupt?

You can use an Event to stop the thread programmatically:

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')

Output:

Started
hello
hello
hello
hello
Stopped
Exiting

Hitting Ctrl-C:

Started
hello
hello
Stopped
Exiting

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM