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
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.
self.name = "SingleApp-%s" % wx.GetUserId()
After that, you need to create an object out of this class.
self.instance = wx.SingleInstanceChecker(self.name)
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.
1 #!/usr/bin/env python 2 3 import wx 4 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() 9 10 11 class SingleApp(wx.App): 12 def OnInit(self): 13 self.name = "SingleApp-%s" % wx.GetUserId() 14 self.instance = wx.SingleInstanceChecker(self.name) 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 21 22 23 app = SingleApp(redirect=False) 24 app.MainLoop()