Skip to content

Instantly share code, notes, and snippets.

@theodoregoetz
Created July 20, 2017 20:41
Show Gist options
  • Save theodoregoetz/9925da54d33a1b29821f6f89dab74c56 to your computer and use it in GitHub Desktop.
Save theodoregoetz/9925da54d33a1b29821f6f89dab74c56 to your computer and use it in GitHub Desktop.
python script to use linux kernel's inotify to monitor a single file, notifying the user through gnome shell's notification using notify2 python module.
#!/usr/bin/env python3
# coding: utf-8
import contextlib
import os
import sys
from inotify.adapters import Inotify
from inotify.constants import IN_DELETE, IN_MODIFY, IN_MOVED_TO
import notify2 as notify
MODIFIED = (IN_DELETE | IN_MODIFY | IN_MOVED_TO)
@contextlib.contextmanager
def watch_directory(dirpath, mask=MODIFIED):
assert os.path.isdir(dirpath)
dirpath = os.path.abspath(dirpath).encode('utf-8')
i = Inotify(block_duration_s=24*60*60)
try:
i.add_watch(dirpath, mask)
yield i
finally:
i.remove_watch(dirpath)
def watch_file(filepath):
filepath = os.path.abspath(filepath)
dirpath, filename = os.path.split(filepath)
filename = filename.encode('utf-8')
with watch_directory(dirpath) as watcher:
for event in watcher.event_gen():
if event is not None and event[3] == filename:
yield event[1]
if __name__ == '__main__':
f = sys.argv[1]
notify.init(f)
n = notify.Notification('File Modified', f, 'text-x-generic-symbolic')
for event_types in watch_file(f):
n.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment