try / except loop with bash terminal command as interrupt
<p>I'm using a simple python.py script in Linux. I need to run a while/counter loop and would like to stop the loop immediately by using a/any terminal command. I need to run the script using Screen. Simply stopping the Screen session doesn't work - it only stops the current process in the loop and then continues with the next process. The terminal command must preferably be specific for the loop in question.</p>

<p>I was looking at a Try / Except loop:</p>

<pre><code>x = 1
y = 100
try:
    while x &lt; y:
        process x
        time.sleep(10)
        x = x + 1
except ?
</code></pre>

<p>I don't know where to start. I need help with the implementation or maybe a better way to do this.</p>

<p>If this is linux then you can use Operating System Signals.
Just create a signal handler that throws an exception and catch that exception.
Register the signal handler with</p>

<pre><code>signal.signal(signal.SIGINT, handler)
</code></pre>

<p>This will register the handler function to be called when ever the SIGINT is sent to the process ID.</p>

<pre><code>import signal, time
class InterruptException(Exception):
    pass

def handler(signum, frame):
    raise InterruptException("Recieved SIGINT")


# Set the signal handler
signal.signal(signal.SIGINT, handler)

x = 1
y = 100
try:
    while x &lt; y:
        print x
        time.sleep(10)
        x = x + 1
except InterruptException:
    print "Iterrupted"
</code></pre>

<p>From bash you can use </p>

<pre><code>kill -2 PID
</code></pre>

<p>where PID is the process ID for the running script</p>

<p>You could always launch and kill from bash like</p>

<pre><code>python my.app &amp;
MY_PID=$!
kill -2 $MY_ID
</code></pre>

python gnu-screen