#!/usr/bin/python # Filename: module-lockfile.py # 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)