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>The other answers involve modifying the Python code itself, which is less than ideal since I don't want it to contain code related only to the testing. Instead, I found that the following bash script useful:</p>

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

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

<p>This will run the <code>gedit archived_sensor_data.json</code> command after <code>python rethinkdb_monitor_batch.py</code> is finished, regardless of whether it exited successfully.</p>

python shell