0

I have created a program using qt designer and then modified it using pyqt5 with functions and more. I use it to start another script using threading when I click a button and that's working good, but I also want to redirect stdout and stderr to a QTextEdit widget using this piece of code to insert into the textedit:

class PrintLogger(object):

    def __init__(self, textbox):
        self.textbox = textbox
        self.textbox.setReadOnly(True)

    def write(self, text):
        self.textbox.moveCursor(QTextCursor.End)
        self.textbox.insertText(text)
        self.textbox.moveCursor(QTextCursor.End)

    def flush(self):
        pass

And then I use this to redirect the output (Where textEdit_2 is my QTextEdit):

sys.stdout = PrintLogger(self.textEdit_2)
sys.stderr = PrintLogger(self.textEdit_2)

And I use this to start my other script:

        def startscript():
            process = subprocess.Popen(["python", "MyOtherScript.py"], stdout=subprocess.PIPE)
            while process.poll() is None:
                line = process.stdout.readline()
                line = line.decode('utf-8').rstrip()
                print(line)

        threading.Thread(target=startscript, daemon=True).start()

"MyOtherScript" is a web scraper that prints out some results. The problem is when I redirect the output, It works for a while before it randomly crashes after about 30 - 60 minutes. The whole program crashes (I'm on windows) and then it either says that Python is not responding or it just exits and gives me one of these two exit codes: 0xC0000005 or 0xC0000374. Just to clarify, if I don't redirect the output this way, it all works as it should without crashing. I have the textedit set with a maximum of 500 lines, but that shouldn't be the problem since after those 30 - 60 minutes, the web scraper have already printed "much" more than that. I have also tried not redirecting the output this way and instead of printing the output in the while process.Poll() is None: I insert it into the textedit instantly. So instead of print(line) I do

self.textEdit_2.moveCursor(QTextCursor.End)
self.textEdit_2.insertPlainText(line)
self.textEdit_2.moveCursor(QTextCursor.End)

This does not help at all. It still crashes as it did before. The only way to fix this is again, to not redirect the output at all and instead just print it in the python console.
I believe this is because of inserting into the QTextEdit and not anything with the sys.stdout... sys.stderr... since it happens when using both my ways.
How should I fix this? Am I inserting the text into the textEdit the wrong way?
Thank you

Coder
  • 49
  • 1
  • 8

0 Answers0