Wx.Python非阻塞GUI启动和停止脚本/模块
问题描述:
我希望能够运行并停止来自我的GUI的脚本/模块而不会阻塞它。我学习了一些关于在GUI代码中线程化并执行“简单”长任务的基本知识。然而,所有的例子都是关于简单的while
或for
循环,可以中止。在大多数情况下,这是一种计数。Wx.Python非阻塞GUI启动和停止脚本/模块
所以问题是:如何使用基于wx.python的GUI来运行/停止外部脚本/模块?脚本没什么特别,它可以是任何类型的长期任务。
这里是基本的wx.Python示例代码!
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()
答
您正在调用的脚本需要一些干净的退出机制,否则您只需要处理这个混乱。我会使用Python的子进程模块来启动外部脚本,然后使用类似psutil(https://github.com/giampaolo/psutil)的东西来杀死它,如果我需要的话。这将需要你用子进程获取进程ID(pid)并跟踪它,以便稍后可以杀死它。
我写了在wxPython中使用psutil这里的一个例子:http://www.blog.pythonlibrary.org/2012/07/13/wxpython-creating-your-own-cross-platform-process-monitor-with-psutil/
我没有与计数任何问题。我不会以简单的形式使用长时间运行的任务。我将使用一些外部脚本,所以我只需要一种方法来启动或停止使用按钮的脚本。 – Domagoj 2013-03-01 13:44:12