【问题标题】:Disable sys.stdout, err, .. to print in terminal?禁用 sys.stdout, err, .. 在终端打印?
【发布时间】:2021-02-04 15:15:29
【问题描述】:

我有一个以 ./mygui.py 开头的 pyqt5 GUI。在 myguy.py 中,我添加了一个类来通过弹出窗口处理异常(复制自 http://timlehr.com/python-exception-hooks-with-qt-message-box/)。然而,虽然异常现在出现在弹出窗口中,但它们仍然被写入终端。我怎样才能删除这个?这是上面链接中的类,可能需要在其中更改/添加一些内容:

import sys
import traceback
import logging
# basic logger functionality
log = logging.getLogger(__name__)
handler = logging.StreamHandler(stream=sys.stdout)
log.addHandler(handler)

def show_exception_box(log_msg):
    """Checks if a QApplication instance is available and shows a messagebox with the exception message. 
    If unavailable (non-console application), log an additional notice.
    """
    if QtWidgets.QApplication.instance() is not None:
            errorbox = QtWidgets.QMessageBox()
            errorbox.setText("Oops. An unexpected error occured:\n{0}".format(log_msg))
            errorbox.exec_()
    else:
        log.debug("No QApplication instance available.")
 
class UncaughtHook(QtCore.QObject):
    _exception_caught = QtCore.Signal(object)
 
    def __init__(self, *args, **kwargs):
        super(UncaughtHook, self).__init__(*args, **kwargs)

        # this registers the exception_hook() function as hook with the Python interpreter
        sys.excepthook = self.exception_hook

        # connect signal to execute the message box function always on main thread
        self._exception_caught.connect(show_exception_box)
 
    def exception_hook(self, exc_type, exc_value, exc_traceback):
        """Function handling uncaught exceptions.
        It is triggered each time an uncaught exception occurs. 
        """
        if issubclass(exc_type, KeyboardInterrupt):
            # ignore keyboard interrupt to support console applications
            sys.__excepthook__(exc_type, exc_value, exc_traceback)
        else:
            exc_info = (exc_type, exc_value, exc_traceback)
            log_msg = '\n'.join([''.join(traceback.format_tb(exc_traceback)),
                                 '{0}: {1}'.format(exc_type.__name__, exc_value)])
            log.critical("Uncaught exception:\n {0}".format(log_msg), exc_info=exc_info)

            # trigger message box show
            self._exception_caught.emit(log_msg)

【问题讨论】:

    标签: python terminal pyqt5 stdout


    【解决方案1】:

    根据您的逻辑,您将 StreamHandler 用作将日志发送到 sys.stdout(本例中为终端)的处理程序,如果您不希望发送日志,请使用 NullHandler:

    log = logging.getLogger(__name__)
    handler = logging.NullHandler() # StreamHandler(stream=sys.stdout)
    log.addHandler(handler)
    

    【讨论】:

      猜你喜欢
      • 2017-07-11
      • 2013-06-27
      • 2013-09-14
      • 2011-12-01
      • 1970-01-01
      • 2023-02-13
      • 1970-01-01
      • 2022-11-02
      • 1970-01-01
      相关资源
      最近更新 更多