Robins Gupta
Robins Gupta

Reputation: 3153

Python:How to prohibit opening of an application if it is already running

I am designing a windows utility software for Windows 7 coded in Python with Wxpython for GUI works.I dont want to open my software if it is already opened. I want a function like this if user opens that software a message box is to be displayed on windows screen showing that "Your application is already running".

Plz help. Thanks in advance...

Upvotes: 6

Views: 656

Answers (1)

Rostyslav Dzinko
Rostyslav Dzinko

Reputation: 40795

There's already existing wxPython facility that implements wanted logic, called wx.SingleInstanceChecker. Here's and example of code (shamelessly borrowed from wxPython wiki):

import wx

class SingleAppFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(300, 300))
        self.Centre()


class SingleApp(wx.App):
    def OnInit(self):
        self.name = "SingleApp-%s" % wx.GetUserId()
        self.instance = wx.SingleInstanceChecker(self.name)
        if self.instance.IsAnotherRunning():
            wx.MessageBox("Another instance is running", "ERROR")
                return False
       frame = SingleAppFrame(None, "SingleApp")
       frame.Show()
       return True


app = SingleApp(redirect=False)
app.MainLoop()

This cannonical example (for a matter of luck) makes exatly what you've asked.

Upvotes: 9

Related Questions