Allow only one instance of python script? [duplicate]

Allow only one instance of python script? [duplicate]

This question already has an answer here:

Check to see if python script is running

19 answers

I have a python script that I want to only allow to be running once on a machine. I want it to print something like “Error, already running” if it is already running, whether its running in the background or in a different ssh session. How would I do this? Here is my script.
import urllib, urllib2, sys
num = sys.argv[1]
print ‘Calling’
phones = [
data = urllib.urlencode({“NUMBER”:num, “DIAL”:”Dial”, “active_line”:1})
while 1:
for phone in phones:
urllib2.urlopen(phone,data) # make call
urllib2.urlopen(phone+”?dialeddel=0″) # clear logs
except: pass

P.S I am using CentOS 5 if that matters.


Solution 1:

  1. You can implement a lock on the file.
  2. Create a temp file at the start of the execution and check if that file is present before running the script.

Refer to this post for answer- Check to see if python script is running

Solution 2:

You can install the single package with pip install single that will use an advisory lock to ensure that only a single instance of a command will run without leaving stale lock files behind.

You can invoke it on your script like this: -c long-running-script arg1 arg2

Solution 3:

You could lock an existing file using e.g. flock at start of your script. Then, if the same script is run twice, the latest started would block. See also this question.

Related:  Install lxml on Centos 7 - error: command 'gcc' failed with exit status 4