为什么使用pyqt时,PyCharm中的python控制台不显示任何错误消息? [英] Why python console in PyCharm doesn't show any error message when pyqt is used?

查看:984
本文介绍了为什么使用pyqt时,PyCharm中的python控制台不显示任何错误消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一些使用pyqt5的代码遇到了一些问题. 当我的Qt类出现问题时,控制台不会记录有关崩溃原因的任何信息. 例如使用以下代码:

I'm facing some issue with some of my code which use pyqt5. When something go wrong in my Qt classes, the console doesn't log any information about why the crashes happened. for instance with this code:

rom PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys


class SurfViewer(QMainWindow):
    def __init__(self, parent=None):
        super(SurfViewer, self).__init__()
        self.parent = parent
        self.centralWidget = QWidget()
        self.color = self.centralWidget.palette().color(QPalette.Background)
        self.setCentralWidget(self.centralWidget)
        self.plotview = QGroupBox(" ")
        self.layout_plotview = QVBoxLayout()
        self.Button_Crash= QPushButton('Crash!')
        self.layout_plotview.addWidget(self.Button_Crash)
        self.centralWidget.setLayout(self.layout_plotview)
        self.Button_Crash.clicked.connect(self.TestForCrash)


    def TestForCrash(self,): 
        a=b 
        return  

def main():
    app = QApplication(sys.argv)
    ex = SurfViewer(app)
    ex.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

由于bTestForCrash函数中未知,因此Qt窗口只是退出,但控制台中没有任何内容.我想知道他们是否是一种方法,可以迫使控制台自动显示正在发生的事情的一些线索.

As b is not known in TestForCrash function, the Qt window just quits but I've got nothing in the console. I'm wondering if their is a way to force the console to automatically print some clue of what is going on.

目前,我正在使用try except来解决问题,但是我不太喜欢这个主意:

For now I'm using a try except to go around the issue but I don't like this idea much:

from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys


class SurfViewer(QMainWindow):
    def __init__(self, parent=None):
        super(SurfViewer, self).__init__()
        self.parent = parent
        self.centralWidget = QWidget()
        self.color = self.centralWidget.palette().color(QPalette.Background)
        self.setCentralWidget(self.centralWidget)
        self.plotview = QGroupBox(" ")
        self.layout_plotview = QVBoxLayout()
        self.Button_Crash= QPushButton('Crash!')
        self.layout_plotview.addWidget(self.Button_Crash)
        self.centralWidget.setLayout(self.layout_plotview)
        self.Button_Crash.clicked.connect(self.TestForCrash)


    def TestForCrash(self,):
        try:
            a=b
        except BaseException as e:
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Critical)
            msg.setText(str(e))
            msg.setStandardButtons(QMessageBox.Ok)
            msg.exec_()
        return




def main():
    app = QApplication(sys.argv)
    ex = SurfViewer(app)
    ex.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

他们是在不使用try except的情况下在控制台中记录一些信息的另一种方法吗?

Is their another way to log some info in the console without using a try except?

正如@three_pineapples提到的那样,当我在真实的" Windows终端(使用c:\​​ anaconda3 \ python.exe)而不是在PyCharm控制台(运行脚本)中执行脚本时,出现了错误.那么他们是直接在Pycharm中强制错误日志的方法吗?也许这是我还没有找到的选择?

As mention by @three_pineapples, I've got errors when I execute the script in 'real' windows terminal (with c:\anaconda3\python.exe) but not in the PyCharm console (when I run the script). So is their a way to force error logs in Pycharm directly? maybe it is an option I didn't find yet?

推荐答案

您可以做的是重新定义异常挂钩 sys.excepthook .引用文档中的内容:

What you can do is redefine the exception hook sys.excepthook. To quote from the documentation:

引发并捕获异常时,解释器将使用三个参数(异常类,异常实例和回溯对象)调用sys.excepthook.在交互式会话中,这恰好在控制权返回到提示之前发生.在Python程序中,这恰好在程序退出之前发生. 可以通过为sys.excepthook分配另一个三参数函数来定制此类顶级异常的处理.

When an exception is raised and uncaught, the interpreter calls sys.excepthook with three arguments, the exception class, exception instance, and a traceback object. In an interactive session this happens just before control is returned to the prompt; in a Python program this happens just before the program exits. The handling of such top-level exceptions can be customized by assigning another three-argument function to sys.excepthook.

您的自定义功能可以显示例如QMessagebox.在下面的示例中,这是通过功能catch_exceptions()完成的.该函数还调用旧的异常钩子(存储在old_hook中),以便除消息框外还遵循处理异常的常规路径.

Your custom function could display, for example, a QMessagebox. This is done in the function catch_exceptions() in the following example. That function also calls the old exception hook (stored in old_hook) so that the normal path of handling exceptions is followed in addition to the message box.

import sys

from PyQt5 import QtWidgets

def catch_exceptions(t, val, tb):
    QtWidgets.QMessageBox.critical(None,
                                   "An exception was raised",
                                   "Exception type: {}".format(t))
    old_hook(t, val, tb)

old_hook = sys.excepthook
sys.excepthook = catch_exceptions

def main():
    app = QtWidgets.QApplication(sys.argv)
    raise RuntimeError

if __name__ == "__main__":
    main()

这篇关于为什么使用pyqt时,PyCharm中的python控制台不显示任何错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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