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

1 view
Skip to first unread message

Naresh Surampudi

unread,
Aug 4, 2017, 2:16:11 AM8/4/17
to learnadmin+g...@googlegroups.com
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

------------------------
test.py
------------------------
import os, time
import datetime as dt

def is_locked(filepath):
    """Checks if a file is locked by opening it in append mode.
    If no exception thrown, then the file is not locked.
    """
    locked = None
    file_object = None
    if os.path.exists(filepath):
        try:
            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." % \
                  message
            locked = True
        finally:
            if file_object:
                file_object.close()
                print "%s closed." % filepath
    else:
        print "%s not found." % filepath
    return locked

def wait_for_files(filepaths):
    """Checks if the files are ready.

    For a file to be ready it must exist and can be opened in append
    mode.
    """
   now=dt.datetime.now()
   ago=now-dt.timedelta(minutes=4)

    for filepath in filepaths:
        # If the file exists but locked, wait wait_time seconds and check
        # again until it's no longer locked by another process.
       if is_locked(filepath):
            print "%s is currently in use." % \
                  (filepath)
            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)
-------------------------

python test.py


--
Posted By Naresh Surampudi to LearnAdmin at 8/04/2017 11:46:00 AM
Reply all
Reply to author
Forward
0 new messages