Created
August 20, 2014 07:53
-
-
Save maliubiao/cb58cd45bc0c0b788bef to your computer and use it in GitHub Desktop.
backup your file automatically.
This file contains hidden or 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
| #! /usr/bin/env python | |
| """ | |
| backup your file automatically. | |
| """ | |
| import os | |
| import time | |
| import shutil | |
| import sys | |
| import errno | |
| import os.path | |
| try: | |
| import _inotify | |
| except: | |
| print "install _inotify please, url: https://github.com/maliubiao/python_inotify" | |
| exit(0) | |
| backup_dst = "/dropbox/path/backup" | |
| backup_list = [ | |
| "/home/user/.vimrc", | |
| "/home/user/.bashrc" | |
| ] | |
| #ident -> file | |
| wds = {} | |
| #inotify fd | |
| fd = 0 | |
| #log | |
| log_path = "/tmp/backup.log" | |
| #touch down wd | |
| twd = 0 | |
| #touch down path | |
| tpath = "/tmp/backup.down" | |
| def recv(event): | |
| mask = event["mask"] | |
| wd = event["wd"] | |
| f = wds[wd] | |
| if (mask & _inotify.MODIFY) or (mask & _inotify.CLOSE_WRITE) or (mask & _inotify.ATTRIB): | |
| if wd == twd: | |
| print "yes, exit....." | |
| exit(0) | |
| print "backup:", time.ctime(), f | |
| try: | |
| shutil.copyfile(f, backup_dst + os.path.basename(f)) | |
| except OSError as e: | |
| print e | |
| if mask & _inotify.DELETE_SELF: | |
| print f, " was itself deleted, add it again" | |
| try: | |
| wd2 = _inotify.add(fd, f, _inotify.ALL_EVENTS) | |
| wds[wd2] = f | |
| except OSError as e: | |
| print e | |
| if mask & _inotify.IGNORED: | |
| del wds[wd] | |
| def touch_down(): | |
| global twd | |
| f = open(tpath, "w+") | |
| f.close() | |
| try: | |
| twd = _inotify.add(fd, tpath, _inotify.ALL_EVENTS) | |
| wds[twd] = tpath | |
| except OSError: | |
| print i, e | |
| def backup(*args): | |
| global fd | |
| fd = _inotify.create() | |
| for i in backup_list: | |
| try: | |
| wd = _inotify.add(fd, i, _inotify.ALL_EVENTS) | |
| wds[wd] = i | |
| except OSError as e: | |
| print i, e | |
| touch_down() | |
| while True: | |
| time.sleep(0.5) | |
| try: | |
| _inotify.read_event(fd, recv) | |
| except OSError as e: | |
| if e.errno == errno.EAGAIN: | |
| pass | |
| def background_backup(*args): | |
| if os.fork() == 0: | |
| os.setsid() | |
| sys.stdin = open('/dev/null', "r") | |
| output = open(log_path, "w+", buffering=0) | |
| sys.stdout = output | |
| sys.stderr = output | |
| if os.fork() == 0: | |
| backup(*args) | |
| else: | |
| exit(0) | |
| else: | |
| exit(0) | |
| if __name__ == "__main__": | |
| backup() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment