I want to be able to run and stop script/module from my GUI without blocking it. I learned some basic things about threading and running "simple" long tasks inside GUI code. However all the examples are about simple while
or for
loop that can bi aborted. In most cases it is some kind of counting.
So the question is: How to run/stop external script/module with wx.python based GUI? The script is nothing specific it can be any kind of long task.
Here is the basic wx.Python example code!
import wx
class MyApp (wx.App):
def OnInit(self):
self.frame = MyFrame(None, title = 'Example')
self.SetTopWindow(self.frame)
self.frame.Show()
return True
class MyFrame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, title=title ,style = (wx.MINIMIZE_BOX | wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.CLIP_CHILDREN))
button1 = wx.Button(self,-1,'Start')
button2 = wx.Button(self,-1, 'Stop')
self.gauge1 = wx.Button(self, -1)
box = wx.BoxSizer(wx.VERTICAL)
box.Add(button1,1, wx.ALL, 10)
box.Add(button2,1, wx.ALL, 10)
box.Add(self.gauge1,1,wx.EXPAND|wx.ALL,10)
self.SetSizer(box, wx.EXPAND)
self.Bind(wx.EVT_BUTTON, self.OnStart, button1)
self.Bind(wx.EVT_BUTTON, self.OnStop, button2)
def OnStart(self,e):
pass
def OnStop(self,e):
pass
if __name__=='__main__':
app = MyApp(False)
app.MainLoop()
The script that you are calling will need some mechanism for quitting cleanly or you will just have to deal with the mess. I would use Python's subprocess module to launch the external script and then use something like psutil (https://github.com/giampaolo/psutil) to kill it if I needed to. That would require you to grab the process id (pid) with subprocess and keep track of it so you could kill it later.
I wrote up an example of using psutil in wxPython here: http://www.blog.pythonlibrary.org/2012/07/13/wxpython-creating-your-own-cross-platform-process-monitor-with-psutil/