Jul-01-2019, 11:06 PM
Did look more this so i did write an improved version,battle tested in Windows and Linux.
Now do a recursive scan in folder with pathlib, os.walk in combination with glob.
So now can choice to watch all files or only a file extension eg deb, txt, jpg, ect...
The setup has been made easy.
Watchdog handles many filesystem events and can also execute shell command.
Now do a recursive scan in folder with pathlib, os.walk in combination with glob.
So now can choice to watch all files or only a file extension eg deb, txt, jpg, ect...
The setup has been made easy.
# watch_folder.py import os, sys import platform import logzero from logzero import logger from pathlib import Path, PurePath def newest_file(folder_to_watch, file_extension): if file_extension == '*': fn = [] for root, dirs, files in os.walk(folder_to_watch): for file in files: fn.append(os.path.join(root, file)) try: return max(fn, key=os.path.getctime) except ValueError: print('No file in folder') sys.exit() else: paths = [] for filename in Path(folder_to_watch).glob(f'**/*.{file_extension}'): paths.append(filename) try: return max(paths, key=os.path.getctime) except ValueError: print(f'No file with extension <{file_extension}>') sys.exit() def stamp(newest_file): file_stamp = os.path.getmtime(newest_file) return file_stamp, newest_file def file_compare(file_stamp, file_name, log_folder): # 3 rotations, each with a maximum filesize of 1MB logzero.logfile(f"{log_folder}logfile.log", maxBytes=1e6, backupCount=3, disableStderrLogger=True) try: with open(f'{log_folder}stamp.txt') as f: old_stamp = float(f.read()) if old_stamp == file_stamp: print(f'No change: {file_name} --> {file_stamp}') else: print(f'New file: {repr(file_name)} --> {file_stamp}') logger.info(f'{file_name} --> {file_stamp}') with open(f'{log_folder}stamp.txt', 'w') as f: f.write(str(file_stamp)) except OSError: with open(f'{log_folder}stamp.txt', 'w') as f: f.write(str(file_stamp)) if __name__ == '__main__': #--- Setup ---# folder_to_watch = '/home/tom/Documents/test_folder/' # Watch a spesific file extensions,eg txt, jpg, zip, ect... # All files default * file_extension = '*' # Folder to save filestamp and log file log_folder = '/home/tom/Documents/stamp/' #---# newest_file = newest_file(folder_to_watch, file_extension) file_stamp = stamp(newest_file)[0] file_name = os.path.basename(stamp(newest_file)[1]) #--- Start ---# file_compare(file_stamp, file_name, log_folder)For and all Python schedule solution can use schedule.
import subprocess import schedule import time def watch_folder(): subprocess.run(['python', 'watch_folder.py']) if __name__ == '__main__': schedule.every(.1).minutes.do(watch_folder) while True: schedule.run_pending() time.sleep(1)So can call it a very lite version of watchdog.
Watchdog handles many filesystem events and can also execute shell command.