Created
March 8, 2012 17:36
-
-
Save mjallday/2002264 to your computer and use it in GitHub Desktop.
File watcher in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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) |
Author
mjallday
commented
Mar 9, 2012
via email
If it had turned up when I googled for something I would have.
…On 9/03/2012, at 1:01, Mahmoud ***@***.*** wrote:
why do you use this instead of just using pyinotify ;) ?
---
Reply to this email directly or view it on GitHub:
https://gist.github.com/2002264
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