CTRL+C causes a signal to be sent to
the process. Python catches the
signal, and sets a global variable,
something like CTRL_C_PRESSED = True.
Then, whenever the Python interpreter
gets to execute a new opcode, it sees
the variable set and raises a
KeybordInterrupt.
This means that CTRL+C works only if
the Python interpreter is spinning. If
the interpreter is executing an
extension module written in C that
executes a long-running operation,
CTRL+C won't interrupt it, unless it
explicitly "cooperates" with Python.
Eg: time.sleep() is theoretically a
blocking operation, but the
implementation of that function
"cooperates" with the Python
interpreter to make CTRL+C work.
This is all by design: CTRL+C is meant
to do a "clean abort"; this is why it
gets turned into an exception by
Python (so that the cleanups are
executed during stack unwind), and its
support by extension modules is sort
of "opt-in". If you want to totally
abort the process, without giving it a
chance to cleanup, you can use CTRL+.
When Python calls QApplication::exec()
(the C++ function), Qt doesn't know
how to "cooperate" with Python for
CTRL+C, and this is why it does not
work. I don't think there's a good way
to "make it work"; you may want to see
if you can handle it through a global
event filter.
— Giovanni Bajo
把这个加到主程序中解决了这个问题。
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
我同意尼尔G的观点,并补充如下:
如果不调用QApplication.exec()来启动事件循环,而是在一个交互式python shell(使用python-i)中执行程序,那么pyqt将在交互式提示等待时自动处理事件,Ctrl-C应再次按预期操作。这是因为Qt事件循环将与python解释器共享时间,而不是独占运行,从而使解释器有机会捕获这些中断。
把这个加到主程序中解决了这个问题。
我不知道这和解释有什么关系。
相关问题 更多 >
编程相关推荐