python - threading ignores KeyboardInterrupt exception -
i'm running simple code:
import threading, time class reqthread ( threading.thread ): def __init__ (self): threading.thread.__init__(self) def run ( self ): in range(0,10): time.sleep(1) print '.' try: thread=reqthread() thread.start() except (keyboardinterrupt, systemexit): print '\n! received keyboard interrupt, quitting threads.\n'
but when run it, prints
$ python prova.py ` . . ^c. . . . . . . . exception keyboardinterrupt in <module 'threading' '/usr/lib/python2.6/threading.pyc'> ignored `
in fact python thread ignore ctrl+c keyboard interrupt , doesn't print received keyboard interrupt
. why? wrong code?
try
try: thread=reqthread() thread.daemon=true thread.start() while true: time.sleep(100) except (keyboardinterrupt, systemexit): print '\n! received keyboard interrupt, quitting threads.\n'
without call time.sleep
, main process jumping out of try...except
block early, keyboardinterrupt
not caught. first thought use thread.join
, seems block main process (ignoring keyboardinterrupt) until thread
finished.
thread.daemon=true
causes thread terminate when main process ends.
Comments
Post a Comment