QProcess与极为相似
subprocess,但是在(Py)Qt代码中使用起来更加方便。因为它利用信号/插槽。另外,它异步运行该过程,因此您无需使用
QThread。
我已经为
QProcess以下代码修改(并清除了)您的代码:
import sysfrom PyQt4 import QtGui,QtCoreclass gui(QtGui.QMainWindow): def __init__(self): super(gui, self).__init__() self.initUI() def dataReady(self): cursor = self.output.textCursor() cursor.movePosition(cursor.End) cursor.insertText(str(self.process.readAll())) self.output.ensureCursorVisible() def callProgram(self): # run the process # `start` takes the exec and a list of arguments self.process.start('ping',['127.0.0.1']) def initUI(self): # Layout are better for placing widgets layout = QtGui.QHBoxLayout() self.runButton = QtGui.QPushButton('Run') self.runButton.clicked.connect(self.callProgram) self.output = QtGui.QTextEdit() layout.addWidget(self.output) layout.addWidget(self.runButton) centralWidget = QtGui.QWidget() centralWidget.setLayout(layout) self.setCentralWidget(centralWidget) # QProcess object for external app self.process = QtCore.QProcess(self) # QProcess emits `readyRead` when there is data to be read self.process.readyRead.connect(self.dataReady) # Just to prevent accidentally running multiple times # Disable the button when process starts, and enable it when it finishes self.process.started.connect(lambda: self.runButton.setEnabled(False)) self.process.finished.connect(lambda: self.runButton.setEnabled(True))#Function Main Startdef main(): app = QtGui.QApplication(sys.argv) ui=gui() ui.show() sys.exit(app.exec_())#Function Main ENDif __name__ == '__main__': main()


