我的PyQt应用程序不再将错误(stderr?)打印到控制台。
我使用QtDesigner并像这样导入UI:
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
from PyQt5.uic import loadUiType
Ui_MainWindow, QMainWindow = loadUiType("test.ui")
class Main(QMainWindow, Ui_MainWindow):
"""Main window"""
def __init__(self,parent=None):
super(Main, self).__init__(parent)
self.setupUi(self)
self.pushButton.clicked.connect(self.testfunc)
def testfunc(self):
print(9/0)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
main = Main()
main.show()
sys.exit(app.exec_())
test.ui包含一个QPushButton和一个标签。当我在非Qt应用程序中调用testfunc(显然会给出错误)时,会收到错误消息,回溯等信息。执行此代码时,它会退出。
我以前没有QtDesigner编写了一个PyQt应用程序,并且按预期将错误打印到控制台。 QtDesigner和继承有什么区别?
最佳答案
这可能是由于PyQt-5.5处理异常的方式发生了变化。引用PyQt5 Docs:
In PyQt v5.5 an unhandled Python exception will result in a call to Qt’s qFatal() function. By default this will call abort() and the application will terminate. Note that an application installed exception hook will still take precedence.
当我在普通控制台中运行您的示例时,这是我看到的:
$ python test.py
Traceback (most recent call last):
File "test.py", line 213, in testfunc
print(9/0)
ZeroDivisionError: division by zero
Aborted (core dumped)
因此主要区别在于,应用程序现在会在遇到未处理的异常时立即终止(即就像普通的python脚本一样)。当然,您仍然可以通过使用
try/except
块或通过覆盖sys.excepthook来全局控制此行为。如果没有看到任何回溯,则可能是由于您用于运行应用程序的Python IDE出现问题。
PS:
作为最低要求,可以像下面那样恢复仅将跟踪记录打印到stdout/stderr的旧PyQt4行为:
def except_hook(cls, exception, traceback):
sys.__excepthook__(cls, exception, traceback)
if __name__ == "__main__":
import sys
sys.excepthook = except_hook
关于python - PyQt : No error msg (traceback) on exit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56406750/