How to only allow one instance of a program made in Python?

Posted on

Question :

Assuming I created a program in Python and it works perfectly, how do I only allow one instance of the program at a time? I searched Google and found a person saying they solved the question using PIDs, but it was not in Python and there were no more details, nor did I find information about the solution mentioned.


Answer :

Form 1

Save a file somewhere, and you can check if the process is running if the pid already exists in the file. Note that it will be necessary to delete the file after finishing execution.

Save the # process ID to a temporary file. And check to see if this file exists at the beginning of the program, besides deleting the file when the process is terminated.

import os
import sys

pid = str(os.getpid())
pidfile = "/tmp/"

if os.path.isfile(pidfile):
    print ("Processo já existe e não será executado novamente")
    #seu programa aqui

Form 2

When using

from tendo import singleton
me = singleton.SingleInstance() # roda sys.exit(-1) se existe outra instância.

How to install the Tendo library:

easy_install tendo
pip install tendo
manualmente pelo site:


Leave a Reply

Your email address will not be published. Required fields are marked *