Python: Allow only one instance of your application
Multitasking operating systems (all modern operating systems) allow us to execute an applications then once at the same time and this is a great feature. But, in some special cases, you may want to allow only one instance application.
I needed a way for my Back In Time project so I searched on the internet and found a very simple solution: when the application start it looks for a file that contains the “application instance” pid. If the file exists and the pid (from this file) is still valid then the application is already running so this second instance must exit. If not the application can start and save it’s pid in this file.
This is my Python implentation (applicationinstance.py).
import os import os.path import time #class used to handle one application instance mechanism class ApplicationInstance: #specify the file used to save the application instance pid def __init__( self, pid_file ): self.pid_file = pid_file self.check() self.startApplication() #check if the current application is already running def check( self ): #check if the pidfile exists if not os.path.isfile( self.pid_file ): return #read the pid from the file pid = 0 try: file = open( self.pid_file, 'rt' ) data = file.read() file.close() pid = int( data ) except: pass #check if the process with specified by pid exists if 0 == pid: return try: os.kill( pid, 0 ) #this will raise an exception if the pid is not valid except: return #exit the application print "The application is already running !" exit(0) #exit raise an exception so don't put it in a try/except block #called when the single instance starts to save it's pid def startApplication( self ): file = open( self.pid_file, 'wt' ) file.write( str( os.getpid() ) ) file.close() #called when the single instance exit ( remove pid file ) def exitApplication( self ): try: os.remove( self.pid_file ) except: pass if __name__ == '__main__': #create application instance appInstance = ApplicationInstance( '/tmp/myapp.pid' ) #do something here print "Start MyApp" time.sleep(5) #sleep 5 seconds print "End MyApp" #remove pid file appInstance.exitApplication()
If you want to use it in your application, all you have to do is:
from applicationinstance import * #create application instance appInstance = ApplicationInstance( '/tmp/myapplication.pid' ) # ... execute your application #remove pid file appInstance.exitApplication()

November 3rd, 2008 at 3:37 pm
[...] the post “Python: Allow only one instance of your application” I presented a method that works great for non GUI applications. It work’s fine for GUI [...]