Kurt Peek Kurt Peek - 13 days ago 4
Bash Question

How to catch Cntrl + C in a shell script which runs a Python script

I'm trying to write a simple program which runs a Python program and inspects the resulting output file:


rm archived_sensor_data.json
python rethinkdb_monitor_batch.py
trap "gedit archived_sensor_data.json" 2

The Python script
runs indefinitely and writes (in append-only mode) to the file
. 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.

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

jez jez

You could do this by capturing the signal inside rethinkdb_monitor_batch.py as follows:

#!/usr/env/bin python

    # 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" )

...and the wrapper script would then simply be:


python rethinkdb_monitor_batch.py
gedit archived_sensor_data.json

But really, why bother with the wrapper, when you could replace the final print() call with

os.execv("gedit", ["archived_sensor_data.json"])

...and then just call the Python script directly from the command-line.