How can I avoid running a python script multiple times?

Padraig at Linux.ie Padraig at Linux.ie
Tue Jan 28 13:30:29 CET 2003


Grzegorz Adam Hankiewicz wrote:
> Hi.
> 
> Using the concurrency jargon, I'm trying to mark python scripts as
> 'critical processes' which are not allowed to be run more than one
> at the same time (I'm constrained to unix environments, BTW). To
> do so, and following the logic of a bash script I had, I've created
> a function which is passed the real entry point of the script.

[snip]

> def run_if_possible(entry_point):
>    """Given a function, it is called if there's no previous process running"""
>    permission = 0
>    lock_path = "%s.lock" % os.path.realpath(sys.argv[0])
>    if os.path.isfile(lock_path):
>       file = open(lock_path, "rt")

what does t do in "rt" ?
Hmm this didn't give an error for me: file = open(lock_path, "wqst")
So unrecognised options must be ignored. I tried x also, but this
seemed to set the exclusive bit? Where are these documented?
Ah, OK on Linux (glibc):
     info libc "Opening Streams"
This shows that the x is glibc specific and sets O_EXCL
on the subsequent open() call (which is what you want).

You could just do os.system("sematree ...") as I've worked
this out already: http://www.pixelbeat.org/sematree/

Note a simple atomic locking mechanism could be to
try and create a directory, which should work over
NFS etc. Might be simpler that messing with exclusive
bits on files?

Note also sockets would be troublesome as you'll
have issues with SO_REUSEADDR for one thing.

Pádraig.





More information about the Python-list mailing list