带有现有进程的wxPython GUI

2 投票
1 回答
567 浏览
提问于 2025-04-20 04:51

我最开始想用Python创建一个文件监控系统,使用了watchdog和Process。在我的程序里,有一个叫FileSystemEventHandler的子类(DirectoryMonitorHandler),用来监控文件夹的变化。我声明了一个全局队列,这样DirectoryMonitorHandler就可以把监测到的项目放进这个队列里。然后,这个队列可以被一个Process子类用来处理DirectoryMonitorHandler放进去的对象。下面是我程序中的一段代码:

if __name__ == "__main__":
    # The global queue that is shared by the DirectoryMonitorHandler and BacklogManager is created
    q = Queue()

    # Check if source directory exists
    if os.path.exists(source):
        # DirectoryMonitorHandler is initialized with the global queue as the input
        monitor_handler = DirectoryMonitorHandler(q)
        monitor = polling.PollingObserver()
        monitor.schedule(monitor_handler, source, recursive = True)
        monitor.start()

        # BacklogManager is initialized with the global queue as the input
        mamanger = BacklogManager(q)
        mamanger.start()

        mamanger.join()
        monitor.join()
    else:
        handleError('config.ini', Error.SourceError)

这个程序运行得很好,但现在我决定给它加一个图形用户界面(GUI)。目前我做到了这些:

class MonitorWindow(wx.Frame):
    def __init__(self, parent):
        super(MonitorWindow, self).__init__(parent, title='Monitor', size=(size_width, size_height))
        staticBox = wx.StaticBox(self, label='Monitor Status:', pos=(5, 105), size=(size_width - 28, size_height/3))
        self.statusLabel = wx.StaticText(staticBox, label='None', pos=(10, 35), size=(size_width, 20), style=wx.ALIGN_LEFT)
        self.InitUI()

    def InitUI(self):
        panel = wx.Panel(self)
        self.SetBackgroundColour(background_color)
        self.Centre()
        self.Show()

    def updateStatus(self, status):
        self.statusLabel.SetLabel('Update: ' + status)

if __name__ == '__main__':
    app = wx.App()
    window = MonitorWindow(None)
    app.MainLoop()

这个窗口运行得不错,但我不太确定该如何把这两个部分结合在一起。wxPython的GUI应该作为一个单独的进程运行吗?我在想我可以创建一个MonitorWindow的实例,然后在DirectoryMonitorHandlerBacklogManager启动之前把它传进去。

我还看过这个http://wiki.wxpython.org/LongRunningTasks,里面解释了wxPython窗口如何与线程一起工作,但我需要的是它能与Process一起工作。另一个可能的解决方案是我需要在Window类内部创建并启动DirectoryMonitorHandlerBacklogManager的实例。你们觉得怎么样?

1 个回答

1

wxPython本身应该是主要的程序,它会启动一个长时间运行的进程来监控你的文件系统。如果你在使用多进程模块,那么你可能需要看看以下几个链接:

你提到的关于长时间运行任务的维基文章非常适合学习如何使用wxPython和线程。我自己也多次使用过那篇文章里的技巧,没遇到过问题。

撰写回答