import sys, os, datetime import time from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler import shutil import configparser class MyHandler(PatternMatchingEventHandler): ignore_patterns = ["*.tmp", "*~$*", "*.pst", "*.ost", "*.ini"] # ignore some file types def process(self, event): """ event.event_type 'modified' | 'created' | 'moved' | 'deleted' event.is_directory True | False event.src_path path/to/observed/file """ global config dest = config['folderMonitor']['destinationTempFolder'] tempAge = int(config['folderMonitor']['allowedTempFileAge']) # the file will be processed there print(event.src_path, event.event_type) # print now only for debugging try: # remove all the files in the temp folder that have been there more than x minutes self.remove_files(dest, tempAge) except: print("Couldn't remove existing files!") try: # this sleep is necessary because Python is too fast and generates # a FileNotFound Error if we don't wait a second before trying to copy time.sleep(3) shutil.copy2(event.src_path, dest) except: print("Couldn't copy the file! fileName: " + event.src_path) def on_modified(self, event): self.process(event) ### # the on_modified event gets called when a file is created, so no need to call # on_created too...just redundancy ### #def on_created(self, event): # self.process(event) ### # Decided not to deal with complexity of handling move/rename in the monitored folders. # This will reduce functionality a little bit for edge cases, but not a big deal ### #def on_moved(self, event): # print('Source: ' + event.src_path + '\r\nDest: ' + event.dest_path) # #shutil.move(event.src_path, self.dest) # deletes all files older than tempAge from the Temp Destination (self.dest) folder def remove_files(self, dest, tempAge): removed=0 # Check current working directory. #print("Current working directory %s" % self.dest) for dirpath, dirnames, filenames in os.walk(dest): for file in filenames: curpath = os.path.join(dirpath, file) file_modified = datetime.datetime.fromtimestamp(os.path.getmtime(curpath)) if datetime.datetime.now() - file_modified > datetime.timedelta(minutes=tempAge): os.remove(curpath) removed+=1 print('Removed: ' + str(removed)) if __name__ == '__main__': args = sys.argv[1:] paths = [] config = configparser.ConfigParser() config.read('settings.ini') paths = config['folderMonitor']['pathsToMonitor'].split(',') observer = Observer() print("Starting up monitoring of folders:") for i in paths: targetPath = str(i) print(targetPath) observer.schedule(MyHandler(), targetPath, recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()