[Twisted-Python] Exit all threads upon KeyboardInterrupt

johnnadre johnnadre at zoho.com
Sun Jan 12 14:01:46 MST 2014


Hi,

I want to exit my application immediately when CTRL+C is pressed, however reactor hangs when there are running threads.
Some of these threads have blocking I/O, so I can't simply set a variable or wait for them to terminate. An example application would be:

from twisted.internet import reactor, threads
from time import sleep
import signal

def do():
    try:
        sleep(10)
    except KeyboardInterrupt:
        print "interrupt!"

#def cleanup(signum, stackframe):
def cleanup():
    d.cancel()
    reactor.callFromThread(reactor._stopThreadPool)
    reactor.callFromThread(reactor.stop) 

if __name__ == '__main__':
    d = threads.deferToThread(do)
    #signal.signal(signal.SIGINT, cleanup)
    reactor.addSystemEventTrigger('before', 'shutdown', cleanup)
    reactor.run()


How can I achieve this?

- John




More information about the Twisted-Python mailing list