Python - Cancel timer

I am trying to create a method that runs on a timer against the background of my main script:

def hello_world(self):
        print 'Hello!'
        threading.Timer(2,hello_world).start()

if __name__ == "__main__":
    try:
        hello_world()
    except KeyboardInterrupt:
        print '\nGoodbye!'

I get this message when I try to interrupt my script on the keyboard:

Exception KeyboardInterrupt in <module 'threading' from '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py'> ignored

How to close the stream so that I can completely close the application?

+3
source share
3 answers

To talk a bit about Aphex's answer, the main thread cannot catch the KeyboardInterrupt signal unless you have very fast fingers. The main stream comes out almost immediately! Try the following:

import threading

def hello_world():
        print 'Hello!'
        threading.Timer(2,hello_world).start()

if __name__ == "__main__":
    try:
        hello_world()
    except KeyboardInterrupt:
        print '\nGoodbye!'
    print "main thread exited"

More generally, I would not suggest using a self-timer, like this, only because it creates many threads. Just create one thread and call time.sleepinside it.

, , , , KeyboardInterrupt . daemon, , .

import threading
import time

def hello_world():
    while(True):
        print 'Hello!'
        time.sleep(2)

if __name__ == "__main__":
    hw_thread = threading.Thread(target = hello_world)
    hw_thread.daemon = True
    hw_thread.start()
    try:
        time.sleep(1000)
    except KeyboardInterrupt:
        print '\nGoodbye!'

1000 - , . , , .

+11

Timer daemon

def hello_world(self):
    print 'Hello!'
    t = threading.Timer(2,hello_world)
    t.daemon = True
    t.start()

, , . - KeyboardInterrupt.

daemon , - daemon .

+6

KeyboardInterrupt: http://effbot.org/zone/stupid-exceptions-keyboardinterrupt.htm

; , caveat:

Threads interact strangely with interrupts: a KeyboardInterrupt exception will be thrown by an arbitrary thread. (When a signal module is available, interrupts always go to the main thread.)

In short, you cannot be sure what KeyboardInterruptfits your main thread. To get around this, you might want to study the module signal.

Edit: A more elegant way to cancel a thread is to have a shared variable that the thread is looking at and exits if it becomes false. Then, if you want to kill the thread from the main thread, you set the variable to false.

+2
source

All Articles