Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 686
Robins Gupta Avatar asked Aug 20 '12 10:08

Robins Gupta


1 Answers

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.

like image 140
Rostyslav Dzinko Avatar answered Nov 03 '22 01:11

Rostyslav Dzinko