Making sure script only runs once instance at a time.
fredrik at pythonware.com
Mon Oct 2 18:57:27 CEST 2006
Hari Sekhon wrote:
> How exactly do you check that the pid is still active in python? Is
> there a library or something that will allow me to manipulate system
> processes and listings etc the way everybody does in unix shells....
by passing zero to the os.kill primitive:
if this raises an OSError, there's no active process with the given pid.
> I'm a huge fan of shell so I've done my own thing which leans on shell
> as follows:
> import sys,commands,os
> scriptpath = sys.argv
> scriptname = os.path.basename(scriptpath)
> number_procs=commands.getstatusoutput('ps -ef|grep %s|grep -v grep|wc
> -l' % scriptpath)
> if number_procs > 1:
> print "There appears to be another %s process running." % scriptname
what if you have commands with overlapping names (e.g. "bar.py" and
"foobar.py"), or some other user on the machine happens to run a
command that, on purpose or by accident, contains your script's name
(e.g. "emacs mybar.py") ?
More information about the Python-list