Test if Script Already Running

Jon Ribbens jon+usenet at unequivocal.eu
Tue Apr 18 20:48:05 EDT 2017


On 2017-04-19, Matt <matt.mailinglists at gmail.com> wrote:
> I have a number of simple scripts I run with cron hourly on Centos
> linux.  I want the script to check first thing if its already running
> and if so exit.
>
> In perl I did it with this at the start of every script:
>
>     use Fcntl ':flock';
>     INIT {
>         open LH, $0 or die "Can't open $0 for locking!\nError: $!\n";
>         flock LH, LOCK_EX | LOCK_NB or die "$0 is already running somewhere!\n";
>     }
>
> How can I do something like this in Python?

I did exactly that very recently (well, I used a different file for
the lock rather than the script itself, but it could easily be
altered):

    import errno
    import fcntl
    import os
    import sys

    LOCKFILE = "...lock file name..."

    lockfd = os.open(LOCKFILE, os.O_WRONLY | os.O_CREAT)
    try:
      fcntl.flock(lockfd, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except IOError as exc:
      if exc[0] != errno.EAGAIN:
        raise
      sys.exit(0)



More information about the Python-list mailing list