I'm trying to catch SIGINT
(or keyboard interrupt) in Python 2.7 program. This is how my Python test script test
looks:
#!/usr/bin/python
import time
try:
time.sleep(100)
except KeyboardInterrupt:
pass
except:
print "error"
Next I have a shell script test.sh
:
./test & pid=$!
sleep 1
kill -s 2 $pid
When I run the script with bash, or sh, or something bash test.sh
, the Python process test
stays running and is not killable with SIGINT
. Whereas when I copy test.sh
command and paste it into (bash) terminal, the Python process test
shuts down.
I cannot get what's going on, which I'd like to understand. So, where is difference, and why?
This is not about how to catch SIGINT
in Python! According to docs – this is the way, which should work:
Python installs a small number of signal handlers by default: SIGPIPE ... and SIGINT is translated into a KeyboardInterrupt exception
It is indeed catching KeyboardInterrupt
when SIGINT
is sent by kill
if the program is started directly from shell, but when the program is started from bash script run on background, it seems that KeyboardInterrupt
is never raised.