为什么即使使用QThreadPool,GUI也会冻结?

2024-04-24 22:02:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图构建一个使用简单QTextEdit的定制Python控制台小部件。行编辑框接收输入并通过线程中的python解释器运行它。在

给你解释器.py在

import sys
from io import StringIO, IncrementalNewlineDecoder
from code import InteractiveConsole
from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot
from stream import NewLineIO

class PythonInterpreter(QObject, InteractiveConsole):
    output = pyqtSignal(str)

    def __init__(self):
        QObject.__init__(self)
        self.l = {}
        InteractiveConsole.__init__(self, self.l)
        self.out = NewLineIO()
        self.out.output.signal_str.connect(self.console)

    def write(self, string):
        self.output.emit(string)

    def runcode(self, codez):
        """
        Reimplementation to capture stdout and stderr
        """
        sys.stdout = self.out
        sys.stderr = self.out
        sys.excepthook = sys.__excepthook__
        result = InteractiveConsole.runcode(self, codez) # Where the magic happens
        sys.stdout = sys.__stdout__
        sys.stderr = sys.__stderr__
        #self.output.emit(self.out.getvalue()) # Send the output
        return result

    @pyqtSlot(str)
    def console(self, string):
        #print(string, file=sys.__stdout__)
        self.output.emit(string)

class JavaScriptInterpreter(QObject):
    pass

这是主.py在

^{pr2}$

每次从PythonInterpreter实例发出信号时,它调用self.send_console_log,后者接收解释器上运行的命令的输出。在

但是,如果我运行一个像for i in range(10000):print(i)这样的大循环作为通过self.send_console_input发送给解释器的命令,它将执行self.send_console_log中的print语句,而不是{}。它将冻结,直到循环完成,整个过程将被附加到QTextEdit。在

如何解决这个问题?在


Tags: fromimportselfoutputstringdefstderrstdout