Live Chat!

How can I avoid running a python script multiple times? Implement file locking.

3 votos Vota!!

March 13th, 2009 mysurface Posted in Developer, python | Hits: 133689 |

Sometimes we just need a single instance of the python script to run at a time. Meaning, the python script itself should detects whether any instances of himself are still running and act accordingly.

Well, how to do it?

The idea is simple, the first instance of the python script will open a file, and lock it. Therefore when the consequent instances try to lock the file, it will fails.

The code is simple too.


import fcntl
def lockFile(lockfile):
    fp = open(lockfile, 'w')
    try:
        fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except IOError:
        return False

    return True

The function will try to lock the file specified by me, if it success, return True, else return False.

From any point of my codes, I’ll do


if not lockFile(".lock.pod"):
        sys.exit(0)

Interesting?

4 Responses to “How can I avoid running a python script multiple times? Implement file locking.”

  1. Nice. Thanks.

  2. It is interesting, but partly because I can’t see much difference between writing an ordinary file checking for its existence. I can’t seem to find any differences on the command line between the two files using stat nor ls, although they must exist.

    Also, it might be worth mentioning LOCK_UN as a param to fcntl.lockf for the purpose of unlocking. :)

  3. The nice thing is that the lock will be dropped when the program terminates.

  4. Hmm, strange. I tried this, but it didn’t seem to work. I even tried copy-pasting your example, but it didn’t work either. It’s such a simple little snippet that I don’t see what could possibly be wrong with it.

    Guess I’m off to find another way to do this.

Leave a Reply

Security Code: