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.
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/mydaemon.pid" if os.path.isfile(pidfile): print ("Processo já existe e não será executado novamente") sys.exit(-1) else: #seu programa aqui facaAlgo() os.unlink(pidfile)
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: http://pypi.python.org/pypi/tendo