Skip to content

Instantly share code, notes, and snippets.

@mjallday
Created March 8, 2012 17:36
Show Gist options
  • Save mjallday/2002264 to your computer and use it in GitHub Desktop.
Save mjallday/2002264 to your computer and use it in GitHub Desktop.
File watcher in Python
#!/bin/python
"""
A simple directory watching script that will compute the checksum for all files
within a path and execute a change when the sum changes.
This will not work well with large files as it reads the entire file into
memory.
"""
import argparse
import hashlib
import os
import subprocess
import time
def checksum(dir):
sums = []
for dir, dirs, files in os.walk(dir):
for subdir in dirs:
sums += checksum(os.path.join(dir, subdir))
for file in files:
sums.append(filesum(os.path.join(dir, file)))
return sums
def filesum(path_to_file):
return hashlib.md5(file(path_to_file, 'r').read()).hexdigest()
def main(dir, action):
sums = checksum(dir)
sum = hashlib.md5(''.join(sums)).hexdigest()
while True:
sums = checksum(dir)
new_sum = hashlib.md5(''.join(sums)).hexdigest()
if new_sum != sum:
subprocess.call(action, shell=True)
sum = new_sum
time.sleep(1)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--dir', nargs='?', help='Directory to watch')
parser.add_argument('--action', nargs='?',
help='Action to perform on change')
args = parser.parse_args()
main(args.dir, args.action)
@mjallday
Copy link
Author

mjallday commented Mar 9, 2012 via email

@mjallday
Copy link
Author

Downloading/unpacking pyinotify
  Running setup.py egg_info for package pyinotify
    inotify is not available on macosx-10.7-intel
    Complete output from command python setup.py egg_info:
    inotify is not available on macosx-10.7-intel

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment