Sometimes you want to ensure, that only one instance of your application is running. There is class for achieving this. It is called wx.SingleInstanceChecker.

What Objects are Involved

* wx.SingleInstanceChecker

Process Overview

First, you define a name. It must be carefully chosen. Normally you need to prevent running more instances of o program for one user, but you want to allow another user to run it concurrently. = "SingleApp-%s" % wx.GetUserId() 

After that, you need to create an object out of this class.

 self.instance = wx.SingleInstanceChecker( 

If desired you can give a second parameter containing the path to use for the lock file. By default, it will be created in user's home directory.

You check whether an instance of an application is running with the  IsAnotherRunnig()  method. If yes, you should close the application because another is already running.

We create a destructor in order to delete that lock file, when the application ends. If we don't do this, each time you start your application a message dialog informs you that an old lock file has been deleted. Such behavior is really annoying and practically unusable in real world applications.

Code Sample

   1 #!/usr/bin/env python
   3 import wx
   5 class SingleAppFrame(wx.Frame):
   6     def __init__(self, parent, title):
   7         wx.Frame.__init__(self, parent, title=title, size=(300, 300))
   8         self.Centre()
  11 class SingleApp(wx.App):
  12     def OnInit(self):
  13 = "SingleApp-%s" % wx.GetUserId()
  14         self.instance = wx.SingleInstanceChecker(
  15         if self.instance.IsAnotherRunning():
  16             wx.MessageBox("Another instance is running", "ERROR")
  17             return False
  18         frame = SingleAppFrame(None, "SingleApp")
  19         frame.Show()
  20         return True
  23 app = SingleApp(redirect=False)
  24 app.MainLoop()

-jan bodnar


OneInstanceRunning (last edited 2010-01-17 16:15:25 by 79-65-133-135)