【问题标题】:Wx.Python non-Blocking GUI starting and stopping script/moduleWx.Python 非阻塞 GUI 启动和停止脚本/模块
【发布时间】:2013-03-01 11:23:54
【问题描述】:

我希望能够从我的 GUI 运行和停止脚本/模块,而不会阻止它。我学习了一些关于线程和在 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()

【问题讨论】:

  • 我对计数没有任何问题。而且我不会以简单的形式使用长时间运行的任务。我将使用一些外部脚本,所以我只需要一种方法来使用按钮启动或停止我的脚本。

标签: python multithreading user-interface module wxpython


【解决方案1】:

您正在调用的脚本将需要某种机制来彻底退出,否则您将不得不处理混乱。我会使用 Python 的 subprocess 模块来启动外部脚本,然后在需要时使用 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/

【讨论】:

    猜你喜欢
    • 2012-09-05
    • 1970-01-01
    • 2016-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-07
    • 2020-06-22
    相关资源
    最近更新 更多