This post originated from an RSS feed registered with Python Buzz
by Ben Last.
Original Post: There Can Be Only One
Feed Title: The Law Of Unintended Consequences
Feed URL: http://benlast.livejournal.com/data/rss
Feed Description: The Law Of Unintended Consequences
Those who run lots of little Python scripts on their various servers know how it is; inevitably, your script will die at some obscure time (only whilst in development, naturally) due to some unforeseen exception. You want to be able to restart it from something like cron, but you also want to be sure only one version is running at any one time. In other, simpler terms; you want your script to check whether another instance is running and to shut down if so.
There are, of course, many ways to do this. Here's a Linux way I do it, which has proven to be more reliable in my environment than others. It's also very simple. Your mileage may vary. Void where prohibited by law. No deposit or return. All goods sold as seen. Etc.
import sys
#Get the process id of this process
pid = os.getpid()
#Get the name of this script, as passed to the Python interpreter
myname = sys.argv[0]
#Run a ps command that includes the command lines of processes
ps = os.popen('ps --no-headers -elf|fgrep %s' % myname)
#Search for any processes that are running python and this script. We check for
#python so that we don't bomb when, for example, someone's editing this script
#in vi.
for p in ps:
if p.find('python')>-1 and p.find(myname)>-1:
#If the pid of the process we've found is not the same as our pid,
#then another instance is running.
otherpid = int(p.split()[3])
if otherpid <> pid: sys.exit()
ps.close()
Feel free to contribute your own way to achieve the same thing; I'm sure there are a hundred different better ways to do this.