Interrupting a continuous script
Eric Brunel
eric.brunel at pragmadev.com
Mon Jun 3 10:56:57 EDT 2002
Julian Gollop wrote:
> I have a few programs continually processing text files on a Linux
> machine. Occasionally I need to stop them, but I don't want to use a
> keyboard interrupt because it may cause the script to stop in the middle
> of doing something.
> Does anyone know a simple way to allow me to stop the process by pressing
> a key on the keyboard - without stopping inside something crucial?
I'd use an interrupt handler on the signal SIGINT, which is sent to your
process when you press Ctrl-C. It may sound complicated, but is in fact
quite straightforward (as often with Python :-):
---------------------------
import sys, os, signal, time
interrupted = 0
def ctrlCHandler(*whatever):
global interrupted
interrupted = 1
print "Interrupt caught. Please wait..."
signal.signal(signal.SIGINT, ctrlCHandler)
print "Something really important start"
for i in range(50): time.sleep(0.1)
print "Something really important end"
if interrupted: sys.exit()
print "Something really important start"
for i in range(50): time.sleep(0.1)
print "Something really important end"
---------------------------
Try to run this script and press Ctrl-C while it runs. You'll see it stops
only when the "important" things are over. You'll just have to put a few
lines like:
if interrupted: sys.exit()
at strategic places in your code, i.e. between important things.
HTH
--
- Eric Brunel <eric.brunel at pragmadev.com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com
More information about the Python-list
mailing list