Search code examples
pythonbatch-filepyqt4popenqthread

Update bat file output from Qthread to Gui


I am a system administrator and this is the first time I am trying to achieve something using Python. I am working on a small python tool that will run a bat file in a Qthread. On the GUI I have a textedit box where I want to update output/error from the bat file.

Here is the code I have so far,

QThread -

class runbat(QtCore.QThread):
    line_printed = QtCore.pyqtSignal(str)
    def __init__(self, ):
        super(runbat, self).__init__()
    def run(self):
        popen = subprocess.Popen("install.bat", stdout=subprocess.PIPE, shell=True)
        lines_iterator = iter(popen.stdout.readline, b"")
        for line in lines_iterator:
        self.line_printed.emit(line)

From main -

self.batfile.line_printed.connect(self.batout)

def batout(self, line):
    cursor = self.ui.textEdit.textCursor()
    cursor.movePosition(cursor.End)
    cursor.insertText(line)
    self.ui.textEdit.ensureCursorVisible()

but I am getting - TypeError: runbat.line_printed[str].emit(): argument 1 has unexpected type 'bytes'. Another question is does stdout catches errors or just output, What do I need to catch the errors as well?


Solution

  • ok, I was able to get it to work by changing the code to following.

    in Qthread

    line_printed = QtCore.pyqtSignal(bytes)
    

    in main

    def batout(self, line):
        output = str(line, encoding='utf-8')
        cursor = self.ui.textEdit.textCursor()
        cursor.movePosition(cursor.End)
        cursor.insertText(output)
        self.ui.textEdit.ensureCursorVisible()
    

    Basically the out put was in bytes and I had to convert it to string. Its working as expected with this changes however if anyone have a better solution I would love to try it. Thank you all.