Prasad Roy
Prasad Roy

Reputation: 127

python program to monitor a file using file control

I am writing a python program to monitor a file for any modification to the file by an external program. I used the below sample program for monitoring the TEST.txt file but the sample program only work for directory and not for the file. Any help appreciated to make it working for file.

import time
import fcntl
import os
import signal

FNAME = "/HOME/PRASAD/TEST.txt"

def handler(signum, frame):
    print "File %s modified" % (FNAME,)

signal.signal(signal.SIGIO, handler)
fd = os.open(FNAME,  os.O_RDONLY)
fcntl.fcntl(fd, fcntl.F_SETSIG, 0)
fcntl.fcntl(fd, fcntl.F_NOTIFY,
            fcntl.DN_MODIFY | fcntl.DN_CREATE | fcntl.DN_MULTISHOT)

while True:
    time.sleep(10000)

Upvotes: 1

Views: 619

Answers (1)

furas
furas

Reputation: 143187

I would use fcntl to control folder in which is TEST.txt and when something changed in this folder then I would use other methods to check file TEST.txt - ie os.stat(filename).st_mtime or even full os.stat(filename).

I don't know if I need all values DN_ but without DN_ATTRIB it doesn't recognize touch TEST.txt

import time
import fcntl
import os
import signal

DNAME = "/HOME/PRASAD/"
FNAME = "/HOME/PRASAD/TEST.txt"

previous = os.stat(FNAME).st_mtime
#previous = os.stat(FNAME)

def handler(signum, frame):
    global previous
    
    print("DIR: {}".format(DNAME))
    
    current = os.stat(FNAME).st_mtime # <--- file
    #current = os.stat(FNAME)         # <--- file

    if current != previous:
        print("FILE: {} {}".format(FNAME, current))
        previous = current

signal.signal(signal.SIGIO, handler)
fd = os.open(DNAME, os.O_RDONLY)      # <--- directory
fcntl.fcntl(fd, fcntl.F_SETSIG, 0)
fcntl.fcntl(fd, fcntl.F_NOTIFY,
            fcntl.DN_ACCESS |
            fcntl.DN_MODIFY |
            fcntl.DN_CREATE |
            fcntl.DN_DELETE |
            fcntl.DN_RENAME |
            fcntl.DN_ATTRIB |
            fcntl.DN_MULTISHOT)

while True:
    time.sleep(10000)

Upvotes: 1

Related Questions