Capturing SIGINT using KeyboardInterrupt exception works in terminal, not in script
<p>I'm trying to catch <code>SIGINT</code> (or keyboard interrupt) in Python 2.7 program. This is how my Python test script <code>test</code> looks:</p>

<pre><code>#!/usr/bin/python

import time

try:
    time.sleep(100)
except KeyboardInterrupt:
    pass
except:
    print "error"
</code></pre>

<p>Next I have a shell script <code>test.sh</code>:</p>

<pre><code>./test &amp; pid=$!
sleep 1
kill -s 2 $pid
</code></pre>

<p>When I run the script with bash, or sh, or something <code>bash test.sh</code>, the Python process <code>test</code> stays running and is not killable with <code>SIGINT</code>. Whereas when I copy <code>test.sh</code> command and paste it into (bash) terminal, the Python process <code>test</code> shuts down.</p>

<p>I cannot get what's going on, which I'd like to understand. So, where is difference, and why?</p>

<p>This is not about <em>how to catch <code>SIGINT</code> in Python!</em> According to <a href="https://docs.python.org/2/library/signal.html" rel="noreferrer">docs</a> – this is the way, which should work:</p>

<blockquote>
  <p>Python installs a small number of signal handlers by default: SIGPIPE ... and SIGINT is translated into a KeyboardInterrupt exception</p>
</blockquote>

<p>It is indeed catching <code>KeyboardInterrupt</code> when <code>SIGINT</code> is sent by <code>kill</code> if the program is started directly from shell, but when the program is started from bash script run on background, it seems that <code>KeyboardInterrupt</code> is never raised.</p>