Wx.Python非阻塞GUI启动和停止脚本/模块

时间:2013-03-01 11:23:54

标签: python multithreading user-interface module wxpython

我希望能够在不阻止脚本/模块的情况下运行和停止脚本/模块。我学习了一些关于线程和在GUI代码中运行“简单”长任务的基本知识。但是,所有示例都是关于可以双中止的简单whilefor循环。在大多数情况下,这是一种计数。

所以问题是:如何使用基于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()

1 个答案:

答案 0 :(得分:1)

您正在调用的脚本需要一些干净利落的机制,否则您只需要处理这些混乱。我会使用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/