【问题标题】:Redirect qDebug output to file with PyQt5使用 PyQt5 将 qDebug 输出重定向到文件
【发布时间】:2016-06-23 23:31:20
【问题描述】:

我使用 python2.7、Qt5.5 和 PyQt5 实现了一个应用程序。我使用logging-Module 让 Python 记录器工作:日志消息都发送到标准错误和日志文件。

但是,Qt 日志消息只出现在 stderr 中,我找不到将它们重定向到文件的方法。

为了缩小问题的范围,我尝试了这个:

>>> 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

注意: 纯 Qt 方式似乎在操作 QDebug 对象,但我无法在 PyQt5 中找到该类。

问题: 如何让qDebug 写入文件stderr.txt

【问题讨论】:

    标签: python qt pyqt5


    【解决方案1】:

    你可以安装一个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()
    

    但请注意:

    • python 代码的上下文属性将始终存在,但对于 来自 Qt 的消息,您将需要一个调试版本(或 QT_MESSAGELOGCONTEXT 在发布版本中定义)
    • 由于某种原因,qInfo() 目前没有被 PyQt 包装

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-24
      • 2020-07-23
      • 2016-08-09
      • 2013-10-11
      相关资源
      最近更新 更多