[Python-ideas] IDEA: do not alter default SIGINT handling

Bernie Innocenti bernie at codewiz.org
Sun Sep 13 23:25:23 CEST 2009

On startup, the Python interpreter changes the default behavior
of SIGINT, which results in  many Python programs to ignore the
keyboard interrupt exactly in the situations when users are
most likely to use it (i.e.: when the program becomes unresponsive).

Minimal testcase:
 $ echo "void foo() { for(;;) {} }" >foo.c
 $ gcc -shared -o foo.so foo.c
 $ python -c 'import ctypes;ctypes.CDLL("./foo.so").foo()'

This scenario mimics a Python program calling some blocking library
function.  It can also happen with IO-bound functions if they loop
on read() and don't abort on short reads.

One might be tempted to say "this behavior of the Python intepreter
is by design" and suggest users to use CTRL-\ instead of CTRL-C.
However, this non-standard behavior is very annoying for users who
expect ^C to work on UNIX systems.  In fact, no other compiled or
interpreted language I know of behaves this way, and Python should
not be the only exception.

While I see the usefulness of KeyboardInterrupt from the programmer
point of view, only a minority of programs actually need to trap
SIGINT and do something with it.  Other language runtimes require
the programmer to manually trap SIGINT when needed.  The Python
interpreter could maintain backwards compatibility by enabling
automatic SIGINT trapping when entering a  "try" block that would
intercept KeyboardInterrupt.

For 2 years, I've been using this workaround in my

import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)

CTRL-C has been working perfectly ever since.  So far, I have
not yet found a single Python program where restoring the
default behavior of SIGINT causes real issues, but there may
certainly be a few.

Granted, this is just a kludge, not a perfect fix, but from a
user perspective, it already improves upon the current behavior
(i.e. more pros than cons).  At least, this is my personal
experience.  If you're skeptical, please try the above workaround
yourself for a few months and let me know what breaks for you.

If we could break the syntax of "print" statements, I'm sure we
can also find a satisfactory compromise for CTRL-C handling that
won't affect more than 0.1% of existing Python programs.

   // Bernie Innocenti - http://codewiz.org/
 \X/  Sugar Labs       - http://sugarlabs.org/

More information about the Python-ideas mailing list