Interrupting a continuous script
Christopher Armstrong
radix at twistedmatrix.com
Mon Jun 3 08:47:21 EDT 2002
>>>>> "Julian" == Julian Gollop <julian.gollop at ntlworld.com> writes:
Julian> I have a few programs continually processing text files on a Linux
Julian> machine. Occasionally I need to stop them, but I don't want to use
Julian> a keyboard interrupt because it may cause the script to stop in the
Julian> middle of doing something. Does anyone know a simple way to allow
Julian> me to stop the process by pressing a key on the keyboard - without
Julian> stopping inside something crucial?
Julian> Julian.
>>> import signal
>>> def handleBreak(sig, frame):
... print "I caught a break!"
...
>>> signal.signal(signal.SIGINT, handleBreak)
<built-in function default_int_handler>
>>> while 1: pass
...
I caught a break!
I caught a break!
I caught a break!
(I pressed C-c 3 times)
Your handleBreak method should set a flag somewhere so your processing
code knows it should stop and clean up whenever it gets the chance.
In case you're considering just catching KeyboardInterrupt exception: don't.
It's not the same as using a signal handler, bacause it will still interrupt
execution and jump to your 'except' block. (with signals, after running thi
handler, it goes back to the code it was running last)
--
Chris Armstrong
<< radix at twistedmatrix.com >>
http://twistedmatrix.com/users/carmstro.twistd/
More information about the Python-list
mailing list