avoid script running twice

Nick Craig-Wood nick at craig-wood.com
Tue Jun 19 00:30:04 CEST 2007

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

    # 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

    fhandle = file("ourlockfile.txt", "w")
    if locking:
        lockf(fhandle.fileno(), LOCK_EX|LOCK_NB)
except IOError, e:
    if locking and e.errno != EAGAIN:
    print >>sys.stderr, "exiting, another copy currently running"

import time

(I tested it on linux only!)

Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick

More information about the Python-list mailing list