The Artima Developer Community
Sponsored Link

Python Buzz Forum
There Can Be Only One

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Ben Last

Posts: 247
Nickname: benlast
Registered: May, 2004

Ben Last is no longer using Python.
There Can Be Only One Posted: Dec 2, 2004 2:09 PM
Reply to this message Reply

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
Latest Python Buzz Posts
Latest Python Buzz Posts by Ben Last
Latest Posts From The Law Of Unintended Consequences

Advertisement
Cheap Linux/Python Trick #101

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.

Read: There Can Be Only One

Topic: 16 Nov 2004 Previous Topic   Next Topic Topic: 12 Nov 2004

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use