Here is a trimmed down version of the example from the inotify page on PyPI
(https://pypi.python.org/pypi/inotify) to get you started:
import inotify.adapters
import os
notifier = inotify.adapters.Inotify()
notifier.add_watch('/home/student')
for event in notifier.event_gen():
if event is not None:
# print event # uncomment to see all events generated
if 'IN_CREATE' in event[1]:
print "file '{0}' created in '{1}'".format(event[3], event[2])
os.system("your_python_script_here.py")
It creates a Inotify object then adds a directory to watch using the add_watch() method. Next it creates a event generator from the Inotify object using the event_gen() method. Finally it iterate overs that generator
Now file operations that affect the watched directory will generate one or more events. Each event takes the form of a tuple with four values:
- An _INOTIFY_EVENT tuple (omitted in the output below for clarity)
- A list of strings describing the events
- The name of the directory affected
- The name of the file affected
Running the above example with the first print statement uncommented and then creating the file 'new' in the watched directory gives this output:
( (...), ['IN_CREATE'], '/home/student', 'new')
file 'new' created in '/home/student'
( (...), ['IN_ISDIR', 'IN_OPEN'], '/home/student', '')
( (...), ['IN_ISDIR', 'IN_CLOSE_NOWRITE'/home/student', '')
( (...), ['IN_OPEN'], '/home/student', 'new')
( (...), ['IN_ATTRIB'], '/home/student', 'new')
( (...), ['IN_CLOSE_WRITE'], '/home/student', 'new')
Since the 'IN_CREATE' event occurs when a new file is created, this is where you would add whatever code you wanted to run.