Terminating python script easily

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Oct 23 03:47:52 CEST 2009

En Thu, 22 Oct 2009 10:03:51 -0300, Bahadir Balban
<bilgehan.balban at gmail.com> escribió:
> On Thu, Oct 22, 2009 at 4:01 PM, Jean-Michel Pichavant
> <jeanmichel at sequans.com> wrote:
>> Balban wrote:
>>> Often, if I want to terminate the script prematurely, I press ctrl-c,
>>> but I have to do this many times before I can kill the script for
>>> good. I was wondering is there a way that I define a signal handler
>>> and kill the whole thing at once with a single ctrl-c?

>> you may want to use subprocess instead of os.system.
>> On catching CTRL+C, you kill all the pid started with subprocess and  
>> exit
>> the script smoothly.
> Hmm. OK, this is what I suspected I needed. So no explicit signal
> catching is required I guess.

Note that KeyboardInterrupt (the exception generated by pressing ^C) may
be catched (sometimes inadvertedly) if the code uses a bare 'except'
clause, and then the program continues normally, effectively ignoring ^C.
The most generic 'except' clause should be, normally:
try: ...
except Exception: ...

Gabriel Genellina

More information about the Python-list mailing list