Ctrl + C terminates the main thread, but since your threads are not in daemon mode, they continue to work, and this keeps working. We can make them demons:
f = FirstThread() f.daemon = True f.start() s = SecondThread() s.daemon = True s.start()
But then another problem arises - as soon as the main thread has started your threads, it has nothing more to do. Thus, he exits, and the streams are instantly destroyed. So let keep the live stream:
import time while True: time.sleep(1)
Now it will print “first” and “second” until you press Ctrl + C.
Edit: as commenters noted, daemon threads may not be able to clean things like temporary files. If you need it, then catch KeyboardInterrupt in the main thread and copy its cleanup and shutdown. But in many cases, allowing sudden streams of demons is perhaps quite good.
Thomas K Aug 05 '12 at 11:30 2012-08-05 11:30
source share