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
?
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:
QT_MESSAGELOGCONTEXT
defined in a release build)qInfo()
is not currently wrapped by PyQtIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With