Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow only one instance of python script? [duplicate]

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 = [
'http://phone1/index.htm',
'http://phone2/index.htm',
'https://phone3/index.htm',
'https://phone4/index.htm',
'https://phone5/index.htm'
]
data = urllib.urlencode({"NUMBER":num, "DIAL":"Dial", "active_line":1})
while 1: 
    for phone in phones:
        try:
            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.

like image 226
CJ Sculti Avatar asked Sep 01 '12 21:09

CJ Sculti


2 Answers

  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

like image 84
fatrock92 Avatar answered Sep 19 '22 20:09

fatrock92


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:

single.py -c long-running-script arg1 arg2
like image 30
aculich Avatar answered Sep 21 '22 20:09

aculich