您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何捕获Python解释器的输出并在Text小部件中显示?

如何捕获Python解释器的输出并在Text小部件中显示?

我假设“来自解释器的输出”是指写入控制台或终端窗口的输出,例如使用产生的输出print()

Python产生的所有控制台输出都被写入程序的输出sys.stdout(正常输出)和sys.stderr错误输出,例如异常回溯)。这些是类似文件的对象。

您可以将这些流替换为您自己的类似文件的对象。您的所有自定义实现都必须提供一个write(text)函数。通过提供自己的实现,您可以将所有输出转发到您的小部件:

class MyStream(object):
    def write(self, text):
        # Add text to a QTextEdit...

sys.stdout = MyStream()
sys.stderr = MyStream()

如果您需要重置这些流,它们仍然可以通过sys.__stdout__和使用sys.__stderr__

sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__

这是PyQt4的一些工作代码。首先定义一个流,该流报告使用Qt信号写入其中的数据:

from PyQt4 import QtCore

class EmittingStream(QtCore.QObject):

    textWritten = QtCore.pyqtSignal(str)

    def write(self, text):
        self.textWritten.emit(str(text))

现在,在您的GUI中,将此流的一个实例安装到sys.stdout并将textWritten信号连接到将文本写入到的插槽中QTextEdit

# Within your main window class...

def __init__(self, parent=None, **kwargs):
    # ...

    # Install the custom output stream
    sys.stdout = EmittingStream(textWritten=self.normalOutputWritten)

def __del__(self):
    # Restore sys.stdout
    sys.stdout = sys.__stdout__

def normalOutputWritten(self, text):
    """Append text to the QTextEdit."""
    # Maybe QTextEdit.append() works as well, but this is how I do it:
    cursor = self.textEdit.textCursor()
    cursor.movePosition(QtGui.QTextCursor.End)
    cursor.insertText(text)
    self.textEdit.setTextCursor(cursor)
    self.textEdit.ensureCursorVisible()
python 2022/1/1 18:45:22 有320人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶