I have a program that call to an subprogram. While the subprogram is running with Popen, I need the run button to be disable and the stop button to enable. However, because Popen opens a new process, things that are suppose to print after the program has finish will print out right away. I tried adding self.p.communicate()
after Popen
, but the GUI will freeze until the subprogram finish running, hence the stop button will not work.
Here is my program:
def gui(QtGui.QWidget):
...
self.runButton = QtGui.QPushButton('Run')
self.stopButton = QtGui.QPushButton('Stop')
self.runButton.clicked.connect(self.run)
self.stopButton.clicked.connect(self.kill)
self.runButton.setEnabled(True)
self.stopButton.setEnabled(False)
def run(self):
self.runButton.setEnabled(False)
self.p = subprocess.Popen(sample.exe)
#self.p.communicate()
self.stopButton.setEnabled(True)
print "Finish running" #without communicate() it will print out before .exe finish running
def kill(self):
self.p.kill()
self.stopButton.setEnabled(False)
print 'You have stop the program'
self.runButton.setEnabled(True)
I'm using Window7, Python 2.7, pyqt4. I do not have to use subprocess, anything that open and able kill subprogram will be fine.
Thanks in advance.
Edit: Tried using QProcess
as dano suggested. I have added the following codes to my program:
def gui(QtCore.Widget):
self.process = QtCore.QProcess(self)
def run(self):
self.process.start(exe_path)
self.process.started.connect(self.onstart)
self.process.finished.connect(self.onfinish)
self.runButton.setEnabled(False)
#self.p = subprocess.Popen(sample.exe) #removed
#self.p.communicate() #removed
def onstart (self):
self.stopButton.setEnabled(True)
self.runButton.setEnabled(False)
print "Started\n"
def onfinish (self):
self.stopButton.setEnabled(False)
self.runButton.setEnabled(True)
print "Finish running\n"
def kill(self):
self.process.kill()
#self.p.kill() #removed
Here is the output:
Click "Run" (output when subprogram finish running)
Finish running
Click "Run" second time
Started
Click "Stop"
Finish running
Finish running
Click "Run" third time
Started
Started
Click "Stop"
Finish running
Finish running
Finish running
Something happened here.