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 - , . , , .