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

Asked

Viewed 256 times

4

Assuming I created a program in Python and it is working perfectly, how do I allow just one instance of the program at a time? I Googled and found a person saying to have solved the issue using PID’s, but it was not in Python and there were no more details, also I did not find information on the solution cited.

1 answer

3


Form 1

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

Save the Process ID in a temporary file. And put to check if this file exists at the beginning of the program besides erasing 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)

Form 2

By using having

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
  • how to run an application using this form of Singleton??

  • @britodfbr means through the library or using the PID?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.