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

 


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()

Tags: ,

One Response to “Python: Allow only one instance of your application”

  1. PyGTK: Allow only one instance of your application | le-Web.org Says:

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

Leave a Reply