How to catch Cntrl + C in a shell script which runs a Python script
<p>I'm trying to write a simple program which runs a Python program and inspects the resulting output file:</p>

<pre><code>#!/bin/bash

rm archived_sensor_data.json
python rethinkdb_monitor_batch.py
trap "gedit archived_sensor_data.json" 2
</code></pre>

<p>The Python script <code>rethinkdb_monitor_batch.py</code> runs indefinitely and writes (in append-only mode) to the file <code>archived_sensor_data.json</code>. In order to start on a 'clean slate' every time, I'd like to delete the file every time before running. Then after I interrupt the execution with Cntrl + C, I'd like to automatically trigger an opening of the file using Gedit.</p>

<p>The problem is that when I press Cntrl+C, it doesn't seem to open Gedit automatically. Is <code>2</code> not the right exit code to use here?</p>

<p>You could do this by capturing the signal inside <code>rethinkdb_monitor_batch.py</code> as follows:</p>

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

try:
    # your existing code here---let's assume it does the following:

    import time
    outfile = open( "archived_sensor_data.json", "wt" )  # NB: this already does the job of erasing previous content
    while True:
        outfile.write( "There's a horse in aisle five.\n" )
        time.sleep( 1 )
        outfile.write( "My house is full of traps.\n" )
        time.sleep( 1 )

except KeyboardInterrupt:
    print( "You pressed Ctrl-C" )
</code></pre>

<p>...and the wrapper script would then simply be:</p>

<pre><code>#!/bin/bash

python rethinkdb_monitor_batch.py
gedit archived_sensor_data.json
</code></pre>

<p>But really, why bother with the wrapper, when you could do it all in the Python, replacing the final <code>print()</code> call as follows:</p>

<pre><code>except KeyboardInterrupt:
    os.execlp("gedit", "archived_sensor_data.json")
</code></pre>

<p>...and then just call the Python script directly from the command-line.</p>

python shell