Python script to check if file is locked also display last modified time

To lock file for testing use this command 

The below command will lock /home/ubuntu/fileloc

flock -x -w 5 /home/ubuntu/fileloc echo "4" >  /home/ubuntu/fileloc && sleep 5

import os, time
import datetime as dt

def is_locked(filepath):
    locked = None
    file_object = None
    if os.path.exists(filepath):
            print "Trying to open %s." % filepath
            buffer_size = 8
            # Opening file in append mode and read the first 8 characters.
            file_object = open(filepath, 'a', buffer_size)
            if file_object:
                print "%s is not locked." % filepath
                locked = False
        except IOError, message:
            print "File is locked (unable to open in append mode). %s." % \
            locked = True
            if file_object:
                print "%s closed." % filepath
        print "%s not found." % filepath
    return locked

def wait_for_files(filepaths):

    for filepath in filepaths:
       if is_locked(filepath):
            print "%s is currently in use." % \
            st = os.stat(filepath)    
            mtime = dt.datetime.fromtimestamp(st.st_mtime)
            print('%s modified %s'%(filepath, mtime))


# Test
if __name__ == '__main__':
    files = [r"/home/ubuntu/filelock"]
    print wait_for_files(files)



soumya Teja said...

This is an excellent blog, Thanks for sharing most valuable information with us. keep share more on Devops Online Training Bangalore

Ajith said...

Great Article, thanks for sharing the valuable information!