I want to handle the signal.SIGINT
from a CTRL-C keyboard event to safely exit my processes before exiting the main thread. I know how to do this using a signal handler, but if any of my threads or processes imports the module, nltk.corpus.stopwords
that somehow prevents the signal handler from running. What I assume is going on, is that the module is so large that it is still being loaded when the signal is produced, but I'm not one-hundred percent sure.
Here is a minimal complete and verifiable example
The following code works as expected.
import signal
import time
import sys
def signal_handler(signum, frame):
print "Safely exiting processes"
for p in proc:
print p
sys.exit(0)
proc = [1, 2, 3, 4]
signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C to interrupt download')
while(True):
time.sleep(1)
print 'wait'
It produces the expected output:
> Press Ctrl+C to interrupt download
> wait
> wait
> Safely exiting processes
> 1
> 2
> 3
> 4
Adding the import statement
from nltk.corpus import stopwords
Changes the output to this error message:
> Press Ctrl+C to interrupt download
> wait
> wait
> forrtl: error (200): program aborting due to control-C event
> Image PC Routine Line Source
>
> kernel32.dll 0000000077544AE3 Unknown Unknown Unknown
> kernel32.dll 00000000775059ED Unknown Unknown Unknown
> ntdll.dll 000000007763C541 Unknown Unknown Unknown
Ctrl-C crashes Python after importing scipy.stats is a very similar question but the described behavior is slightly different and the accepted answer does not work for me.
- The accepted answer also reports getting the same error message using the
time
module. I have no issue with thetime
module. - The accepted answer's solution simply moves the import statements after the handler initialization. This doesn't remove the error for me, maybe because they are using
win32api.SetConsoleCtrlHandler
instead ofsignal.signal