[Python] How to prevent error on shutdown with Logging Handler / QObject?

Discussão em 'Python' iniciado por Stack, Abril 23, 2025.

  1. Stack

    Stack Membro Participativo

    In order to show logging messages in a PyQt GUI, I'm using a custom logging handler that sends the logRecord as a pyqtSignal.
    This handler inherits from both QObject and logging.Handler.

    This works as it should but on shutdown there's this error:


    File "C:\Program Files\Python313\Lib\logging\__init__.py", line 2242, in shutdown
    if getattr(h, 'flushOnClose', True):
    RuntimeError: wrapped C/C++ object of type Log2Qt has been deleted​

    My interpretation is that logging tries to close the handler but because the handler is also a QObject, Qt has already deleted it.
    But when you connect the aboutToQuit signal to a function that removes the handler from the logger, the error still occurs.

    Here's a MRE:

    import logging
    from PyQt6.QtWidgets import QApplication, QWidget
    from PyQt6.QtCore import QObject, pyqtSignal


    class Log2Qt(QObject, logging.Handler):
    log_forward = pyqtSignal(logging.LogRecord)

    def emit(self, record):
    self.log_forward.emit(record)


    logger = logging.getLogger(__name__)
    handler = Log2Qt()
    logger.addHandler(handler)


    def closing():
    # handler.close()
    logger.removeHandler(handler)
    print(logger.handlers)


    app = QApplication([])
    app.aboutToQuit.connect(closing)
    win = QWidget()
    win.show()
    app.exec()


    The print from closing() shows that logger has no more handlers, so why does logging still try to close the handler when it's already removed?
    And how could you prevent the error from occuring?

    Continue reading...

Compartilhe esta Página