avoid script running twice
Robin Becker
robin at reportlab.com
Tue Jun 19 05:20:14 EDT 2007
Nick Craig-Wood wrote:
> Tim Williams <tim at tdw.net> wrote:
>> On 18/06/07, Nick Craig-Wood <nick at craig-wood.com> wrote:
>> On Windows the open-a-file-for-writing method works well, but as *nix
>> doesn't work the same way then maybe the socket solution is the best
>> cross-platform option.
>
> Actually you could combine your solution and Jeff McNeil's solution to
> make something which should work on both windows and unix and is 100%
> guaranteed to release the lock on process exit.
>
> import sys
>
> try:
> # use fcntl lock if we can
> from fcntl import lockf, LOCK_EX, LOCK_NB
> from errno import EAGAIN
> locking = True
> except ImportError:
> # otherwise platform mustn't open a file twice for write
> if sys.platform != "win32":
> raise AssertionError("Unsupported platform for locking")
> locking = False
>
> try:
> fhandle = file("ourlockfile.txt", "w")
> if locking:
> lockf(fhandle.fileno(), LOCK_EX|LOCK_NB)
> except IOError, e:
> if locking and e.errno != EAGAIN:
> raise
> print >>sys.stderr, "exiting, another copy currently running"
>
> import time
> time.sleep(2)
>
> (I tested it on linux only!)
>
many interesting suggestions, unfortunately I'm not exactly sure about the
filesystem to be used. I think it might be some kind of NFS which might impact
some of these solutions.
--
Robin Becker
More information about the Python-list
mailing list