[Twisted-Python] Exit all threads upon KeyboardInterrupt

exarkun at twistedmatrix.com exarkun at twistedmatrix.com
Sun Jan 12 15:03:24 MST 2014


On 09:01 pm, johnnadre at zoho.com wrote:
>
>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:

Python threads (being plain old operating systems; for example, POSIX 
threads) aren't generally interruptable.  You could try exiting the 
entire process using `os._exit`.

This is the case whether you're using Twisted or not.

Jean-Paul
>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
>
>
>_______________________________________________
>Twisted-Python mailing list
>Twisted-Python at twistedmatrix.com
>http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python



More information about the Twisted-Python mailing list