Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect qDebug output to file with PyQt5

Tags:

python

qt

pyqt5

I implemented an application using python2.7, Qt5.5 and PyQt5. I got the Python-logger working using logging-Module: Log-Messages are both sent to stderr and to a log-file.

However, the Qt log messages only appear in stderr and I could not find a way to redirect them to a file.

In order to narrow down the problem, I tried this:

>>> from PyQt5.QtCore import qDebug
>>> import sys
>>> sys.stderr = open("stderr.txt", 'w')
>>> qDebug('test message')
test message
>>> sys.stderr.close()
>>> # stderr.txt is empty

Note: The pure-Qt-way seems to be manipulating a QDebug object, but I was not able to find the class within PyQt5.

Question: How can I have qDebug write to a file stderr.txt?

like image 290
koffein Avatar asked Mar 09 '16 14:03

koffein


1 Answers

You can install a message handler:

import sys
from PyQt5 import QtCore, QtWidgets

def qt_message_handler(mode, context, message):
    if mode == QtCore.QtInfoMsg:
        mode = 'INFO'
    elif mode == QtCore.QtWarningMsg:
        mode = 'WARNING'
    elif mode == QtCore.QtCriticalMsg:
        mode = 'CRITICAL'
    elif mode == QtCore.QtFatalMsg:
        mode = 'FATAL'
    else:
        mode = 'DEBUG'
    print('qt_message_handler: line: %d, func: %s(), file: %s' % (
          context.line, context.function, context.file))
    print('  %s: %s\n' % (mode, message))

QtCore.qInstallMessageHandler(qt_message_handler)

app = QtWidgets.QApplication(sys.argv)

def main():
    QtCore.qDebug('something informative')
    win = QtWidgets.QMainWindow()
    # trigger a Qt debug message
    win.setLayout(QtWidgets.QVBoxLayout())

main()

But note:

  • context properties will always be there for python code, but for messages coming from Qt, you will need a debug build (or have QT_MESSAGELOGCONTEXT defined in a release build)
  • for some reason, qInfo() is not currently wrapped by PyQt
like image 193
ekhumoro Avatar answered Nov 16 '22 09:11

ekhumoro