How to show os.system() in textEdit in pyqt4

987 views Asked by At

I use QtDesigner and pyqt4 for design my application. I want to show os.system() function results in textEdit! here is my code:

def aiaa(self):
    import os
    ss = os.system("systemctl status tor.service")
    self.textEdit.setText(str(ss))
def setupUi(self, MainWindow):
    self.textEdit = QtGui.QTextEdit(self.centralwidget)
    self.textEdit.setGeometry(QtCore.QRect(40, 10, 351, 201))
    self.textEdit.setObjectName(_fromUtf8("textEdit"))
    self.pushButton = QtGui.QPushButton(self.centralwidget)
    self.pushButton.setGeometry(QtCore.QRect(170, 250, 94, 32))
    self.pushButton.setObjectName(_fromUtf8("pushButton"))
    self.pushButton.clicked.connect(self.aiaa)

but its show result in terminal not in textEdit. Thanks...

1

There are 1 answers

2
ekhumoro On

The reason your example won't work is because os.system returns the exit code of the command, rather than its output (which is just printed on stdout). There are other questions which give some standard python solutions for this, but since you are using PyQt. I thought I'd show the Qt way of doing things instead.

Below is a demo script that uses a QProcess to run commands. Signals from the process are connected to some slots which can then display the output from stdout and stderr whenever they become available:

import sys
from PyQt4 import QtCore, QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.display = QtGui.QTextEdit(self)
        self.display.setReadOnly(True)
        self.command = QtGui.QLineEdit(self)
        self.button = QtGui.QPushButton('Run Command', self)
        self.button.clicked.connect(self.handleButton)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.display)
        layout.addWidget(self.command)
        layout.addWidget(self.button)
        self.process = QtCore.QProcess(self)
        self.process.readyReadStandardOutput.connect(self.handleStdOut)
        self.process.readyReadStandardError.connect(self.handleStdErr)

    def handleButton(self):
        self.process.start(self.command.text())

    def handleStdOut(self):
        data = self.process.readAllStandardOutput().data()
        self.display.append(data.decode('utf-8'))

    def handleStdErr(self):
        data = self.process.readAllStandardError().data()
        self.display.append(data.decode('utf-8'))

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(600, 100, 500, 400)
    window.command.setText('systemctl status tor.service')
    window.show()
    sys.exit(app.exec_())