Running a python script when a new file is created

11,263

Solution 1

I think the watchdog library is a better thing to use here as creimers mentioned. I have used it as follows to monitor a folder for new files:

import time 
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class ExampleHandler(FileSystemEventHandler):
    def on_created(self, event): # when file is created
        # do something, eg. call your function to process the image
        print "Got event for file %s" % event.src_path 

observer = Observer()
event_handler = ExampleHandler() # create event handler
# set observer to use created handler in directory
observer.schedule(event_handler, path='/folder/to/watch')
observer.start()

# sleep until keyboard interrupt, then stop + rejoin the observer
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    observer.stop()

observer.join()

Solution 2

import os                                                                       
import pyinotify                                                                

WATCH_FOLDER = os.path.expanduser('~')                                          

class EventHandler(pyinotify.ProcessEvent):                                     
    def process_IN_CLOSE_WRITE(self, event):                                    
        """"                                                                    
        Writtable file was closed.                                              
        """                                                                     
        if event.pathname.endswith('.jpg'):                                     
            print event.pathname                                                

    def process_IN_MOVED_TO(self, event):                                       
        """                                                                     
        File/dir was moved to Y in a watched dir (see IN_MOVE_FROM).            
        """                                                                     
        if event.pathname.endswith('.jpg'):                                     
            print event.pathname                                                

    def process_IN_CREATE(self, event):                                         
        """                                                                     
        File/dir was created in watched directory.                              
        """                                                                     
        if event.pathname.endswith('.jpg'):                                     
            print event.pathname                                                


def main():                                                                     
    # watch manager                                                             
    mask = pyinotify.IN_CREATE | pyinotify.IN_MOVED_TO | pyinotify.IN_CLOSE_WRITE
    watcher = pyinotify.WatchManager()                                          
    watcher.add_watch(WATCH_FOLDER,                                             
                      mask,                                                     
                      rec=True)                                                 
    handler = EventHandler()                                                    
    # notifier                                                                  
    notifier = pyinotify.Notifier(watcher, handler)                             
    notifier.loop()                                                             

if __name__ == '__main__':                                                      
    main()   
Share:
11,263

Related videos on Youtube

Anconia
Author by

Anconia

Updated on October 27, 2022

Comments

  • Anconia
    Anconia over 1 year

    I have a folder that stores a bunch of jpg images. When a new image is added to this folder I need to run a python script on it.

    Is this possible? If so, how? One potential solution I saw was pyinotify but have not seen any robust examples of it.

    • creimers
      creimers almost 10 years
      Take a look at watchdog