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 #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()) 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.