Ctrl-C 不适用于 PyQt [英] Ctrl-C doesn't work with PyQt

查看:69
本文介绍了Ctrl-C 不适用于 PyQt的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 Ctrl+C 不能破坏使用 PyQt 的 Python 程序?我想调试它并获得堆栈跟踪,出于某种原因,这比使用 C++ 更难做到!

Why doesn't Ctrl+C work to break a Python program that uses PyQt? I want to debug it and get a stack trace and for some reason, this is harder to do than with C++!

推荐答案

CTRL+C 使信号发送到过程.Python 抓住了信号,并设置一个全局变量,类似于 CTRL_C_PRESSED = True.然后,每当 Python 解释器得到执行一个新的操作码,它看到变量集并引发一个键盘中断.

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.

这意味着 CTRL+C 只有在Python 解释器正在旋转.如果解释器正在执行一个用 C 编写的扩展模块执行长时间运行的操作,CTRL+C 不会中断它,除非它明确地与 Python合作".例如: time.sleep() 理论上是一个阻塞操作,但该功能的实现与 Python 合作"使 CTRL+C 工作的解释器.

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.

这都是设计的:CTRL+C 的意思做一个干净的中止";这就是为什么它被变成异常Python(以便清理在堆栈展开期间执行),及其扩展模块的支持排序的选择加入".如果你想完全中止进程,而不给它一个有机会清理,你可以用CTRL+.

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+.

当 Python 调用 QApplication::exec()(C++ 函数),Qt 不知道如何与Python合作"CTRL+C,这就是为什么它不工作.我不认为有什么好办法让它发挥作用";你可能想看如果你可以通过全局来处理它事件过滤器.— 乔瓦尼·巴霍

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

将此添加到主程序解决了问题.

Adding this to the main program solved the problem.

import signal

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

我不确定这与解释有什么关系.

I'm not sure what this has to do with the explanation.

这篇关于Ctrl-C 不适用于 PyQt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆