3

I'm working on a PyKDE4/PyQt4 application, Autokey, and I noticed that when I send the program a CTRL+C, the keyboard interrupt is not processed until I interact with the application, by ie. clicking on a menu item or changing a checkbox.

lfaraone@stone:~$ /usr/bin/autokey
^C^C^C
Traceback (most recent call last):
  File "/usr/lib/python2.6/dist-packages/autokey/ui/popupmenu.py", line 113, in on_triggered
    def on_triggered(self):
KeyboardInterrupt
^C^C^C
Traceback (most recent call last):
  File "/usr/lib/python2.6/dist-packages/autokey/ui/configwindow.py", line 423, in mousePressEvent
    def mousePressEvent(self, event):
KeyboardInterrupt

This is despite having the following in /usr/bin/autokey:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
from autokey.autokey import Application

a = Application()
try:
    a.main()
except KeyboardInterrupt:
    a.shutdown()
sys.exit(0)

Why isn't the KeyboardInterrupt caught:

  • when I issue it, rather than when I next take an action in the GUI
  • by the initial try/except clause?

Running Ubuntu 9.04 with Python 2.6.

Clare Macrae
  • 3,473
  • 2
  • 26
  • 42
lfaraone
  • 44,680
  • 16
  • 48
  • 70
  • If the sig is caught asap, then it shows the reason KeyboardInterrupt is not being raised is that you're in a C-based event loop inside Qt, and the Python interpreter doesn't get a chance to register the ^C until the next time around the event loop. – Vinay Sajip Aug 31 '09 at 15:36

1 Answers1

7

Try doing this:

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

before invoking a.main().

Update: Remember, Ctrl-C can be used for Copy in GUI applications. It's better to use Ctrl+\ in Qt, which will cause the event loop to terminate and the application to close.

Vinay Sajip
  • 84,585
  • 13
  • 155
  • 165
  • yes, the sig is then caught. want me to paste the contents of a.main()? – lfaraone Aug 31 '09 at 13:57
  • Okay. Is there a way I can change it so that CTRL+C works as it does in almost every other UNIX application? – lfaraone Sep 03 '09 at 14:44
  • Just as a note: E.g. on a german keyboard you cannot press Ctrl+\ because \ os already a key sequence (Alt Gr+ß). – panzi Nov 12 '11 at 02:55
  • 2
    Note SIG_DFL is the default signal handler of the OS, which kills the application. The code will not raise a KeyboardInterrupt on ^C, the application will be killed before. – Alicia Oct 06 '13 at 16:32