Making sure script only runs once instance at a time.
hpsekhon at googlemail.com
Mon Oct 2 12:18:30 CEST 2006
number_procs=commands.getstatusoutput('ps -ef|grep %s|grep -v grep|wc
-l' % scriptpath)
was supposed to be
number_procs=int(commands.getstatusoutput('ps -ef|grep %s|grep -v
grep|wc -l' % scriptpath))
Hari Sekhon wrote:
> Fredrik Lundh wrote:
>> Hari Sekhon wrote:
>>> I'm not sure if that is a very old way of doing it, which is why I was
>>> reluctant to do it. My way actually uses the process list of the os
>>> (linux) and counts the number of instances. If it is more than 0 then
>>> another process is running and the script exits gracefully.
>> the code that reliably identifies instances of a given program would be
>> interesting to see.
>>> Also, apart from the fact the using lockfiles feels a bit 1970s, I have
>> > found that in real usage of other programs within the company that use
>> > lockfiles, it sometimes causes a bit of troubleshooting time when
>> > it stops working due to a stale lockfile.
>> to minimize that risk, store the pid in the lockfile (and preferrably
>> also the host name), and make sure that the program checks that the pid
>> is still active before it "stops working".
> 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....
> 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
> print "Please do not run more than one instance of this program"
> print "Quitting for safety..."
> This works nicely for me.
> You might also want to add a bit of discrimination to the script
> (something along the lines of "get a decent os"...since this won't
> work on windows)
> import platform
> if platform.system() != 'Linux':
> print "Sorry but this program can only be run on Linux"
> #todo: should do a bit extra for our bsd cousins here....
> Let me know if you think you have a better way. Please provide a code
> snippet if so.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-list