Making sure script only runs once instance at a time.
Hari Sekhon
hpsekhon at googlemail.com
Mon Oct 2 06:11:45 EDT 2006
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".
>
> </F>
>
>
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[0]
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..."
sys.exit(200)
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"
sys.exit(201)
#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.
-h
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20061002/6fa6b8ba/attachment.html>
More information about the Python-list
mailing list