Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: module for creating PID-based lockfile?

I'm writing a Python script that may or may not (depending on a bunch of things) run for a long time, and I'd like to make sure that multiple instances (started via cron) don't step on each others toes. The logical way to do this seems to be a PID-based lockfile… But I don't want to re-invent the wheel if there is already code to do this.

So, is there a Python module out there which will manage the details of a PID-based lockfile?

like image 909
David Wolever Avatar asked Sep 18 '09 14:09

David Wolever


People also ask

What is lockfile for Python?

This package is pre-release software. Between versions 0.8 and 0.9 it was changed from a module to a package. It is quite possible that the API and implementation will change again in important ways as people test it and provide feedback and bug fixes.

How do you lock a text file in Python?

This package contains a single module, which implements a platform independent file lock in Python, which provides a simple way of inter-process communication: from filelock import Timeout, FileLock lock = FileLock("high_ground. txt.

What is a PID lock?

The PID file usually contains the process ID number of the already launched and running program if one exists. Also, when it starts up, it creates the lock file. As long as the lock file exists, it won't start another one without user intervention.


2 Answers

This might be of help to you: lockfile

like image 187
ennuikiller Avatar answered Oct 04 '22 01:10

ennuikiller


If you can use GPLv2, Mercurial has a module for that:

http://bitbucket.org/mirror/mercurial/src/tip/mercurial/lock.py

Example usage:

from mercurial import error, lock  try:     l = lock.lock("/path/to/lock", timeout=600) # wait at most 10 minutes     # do something except error.LockHeld:      # couldn't take the lock else:     l.release() 
like image 28
tonfa Avatar answered Oct 03 '22 23:10

tonfa