inotify

Sometimes it would be nice to do something when a file was written to disk.

For example a file is saved in the editor and after the file is written on disk we want to run a script or code.

Two ways to solve this:

inotify-tools

Install inotify-tools via your package manager.

Example usage:

# watch all files in this folder
while inotifywait -e close_write *; do
  bash process.sh
done

inotify in Python

There are some Python packages for inotify. One is aionotify and is Python 3 only.

Source of aionotify: https://github.com/rbarrois/aionotify

Because inotify is kernel based this can be used to trigger events when files are uploaded to a system. When the file is closed a function is called to process the file.

Example usage:

import asyncio
import aionotify
from pathlib import Path

PATH = Path("/tmp/uploads")

# Setup the watcher
watcher = aionotify.Watcher()
watcher.watch(alias="uploads", path=str(PATH), flags=aionotify.Flags.CLOSE_WRITE)

# Prepare the loop
loop = asyncio.get_event_loop()

def process(filename):
    # print first line; could do more useful stuff
    with open(PATH / filename) as fp:
        print(fp.readline())

async def work():
    await watcher.setup(loop)
    while True:
        event = await watcher.get_event()
        print(event)
        process(event.name)
    watcher.close()

loop.run_until_complete(work())
loop.stop()
loop.close()

This example monitors the folder /tmp/uploads for files written and closed. A closed file will be opened and the first line is printed.

An example call of the script above:

echo "foo\nbar" > /tmp/uploads/xxx

results in

Event(flags=8, cookie=0, name='xxx', alias='uploads')
foo

Allowed flags are listed here: https://github.com/rbarrois/aionotify/blob/master/aionotify/enums.py