在KDE Python应用中处理KeyboardInterrupt?
我正在开发一个使用PyKDE4/PyQt4的应用程序,叫做Autokey。我发现,当我按下CTRL+C的时候,程序并没有立即响应这个中断,直到我和应用程序进行互动,比如点击一个菜单项或者更改一个复选框。
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
这尽管在/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)
为什么键盘中断没有被及时捕捉到:
- 当我发出中断时,而不是等到我下次在图形界面上进行操作时
- 在最初的try/except语句中?
我正在使用Ubuntu 9.04和Python 2.6。
1 个回答
11
试试这样做:
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
在调用 a.main()
之前。
更新:记住,在图形界面应用中,Ctrl-C可以用来复制。更好的做法是在Qt中使用Ctrl+\,这样可以结束事件循环并关闭应用程序。