lockfile in python

lockfile is one of my must haves, as it is a very useful semaphore lock file creator.
# lockfile --help
Usage: lockfile -v | -nnn | -r nnn | -l nnn | -s nnn | -! | -ml | -mu | file ...
# rpm -qf `which lockfile`
procmail-3.22-25.1.el6.x86_64
As can be seen above, /usr/bin/lockfile is part of procmail, which comes with its own dependencies (usually sendmail or postfix etc.). I did not like having to install those MTA type dependencies to setup procmail for locking purposes. This is the reason why I wrote lockfile.py.

lockfile.py

#!/usr/bin/python

# Author Evuraan Gmail dot com

import optparse,sys,os,time

def usage():
	print """
Usage   : lockfile.py 
Usage   : lockfile.py -l  
Example : lockfile.py -l 1300 /tmp/my.lockfile.txt
Example : lockfile.py /tmp/my.lockfile.txt

"""


def remove_lockfile(lock_file):
	os.remove(lock_file)


def set_lockfile(lock_file):
	write_file = open(lock_file,"w",)
	write_file.write(str(time.time()))
	write_file.close()
	if os.path.isfile(lock_file):
		# file exists, good enough for us.
		return 0
	else:
		return 1



#if the lockfile exists, check for locktimeout
def checklock(lock_file):
	if os.path.isfile(lock_file):
		# lock file exists. check how old etc.
		mtime = float(os.path.getmtime(lock_file))
		delta = time.time() - mtime
		if float(delta) >= float(locktimeout):
			# file is stale, over write it
			if set_lockfile(lock_file) != 0:
				sys.exit(1)
		else:
			#file is not stale. new. spanking new.
			sys.exit(1)
	else:
		# no lock file.
		if set_lockfile(lock_file) != 0:
			sys.exit(1)



if __name__ == "__main__":

	parser = optparse.OptionParser()
	parser.add_option('-l', '--locktimeout',
		dest="locktimeout",
		type="int",
		default="3489999999",
		help="""If you specify a locktimeout then a lockfile will be
removed by force after locktimeout seconds have passed since the lockfile was last
modified/created (most likely by some other program that unexpectedly
died a long time ago, and hence could not clean up any leftover lockfiles)."""
		)

	options,remainder = parser.parse_args()

	#print "locktimeout       :", options.locktimeout
	#print "remainder         :", remainder

	global locktimeout
	locktimeout = options.locktimeout

	try:
		if len(remainder) == 0:
			print "Invalid usage"
			usage()
			sys.exit(2)
		else:
			global lock_file
			lock_file = remainder[0]
	except:
		sys.exit(2)


	#print "Ahem", lock_file
	checklock(lock_file)


Download

lockfile.py can be downloaded as:
$ wget https://evuraan.info/evuraan/stuff/lockfile.py.txt --no-check-certificate -O lock.py

Usage:

$ ./lockfile.py
Invalid usage

Usage   : lockfile.py 
Usage   : lockfile.py -l  
Example : lockfile.py -l 1300 /tmp/my.lockfile.txt
Example : lockfile.py /tmp/my.lockfile.txt


$ ./lockfile.py --help
Usage: lockfile.py [options]

Options:
  -h, --help            show this help message and exit
  -l LOCKTIMEOUT, --locktimeout=LOCKTIMEOUT
                        If you specify a locktimeout then a lockfile will be
                        removed by force after locktimeout seconds have passed
                        since the lockfile was last modified/created (most
                        likely by some other program that unexpectedly  died a
                        long time ago, and hence could not clean up any
                        leftover lockfiles).


$ ./lockfile.py  /tmp/mylockfile ; echo $?
0

$ ./lockfile.py  /tmp/mylockfile ; echo $?
1

Feedback

Your feedback, suggestions etc are welcome. Please leave your comments/feedback at this link.

License

Software License:

Copyright (c) 2013, evuraan All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.