创建新文件时运行python脚本

时间:2014-05-05 18:45:38

标签: python file

我有一个存储一堆jpg图像的文件夹。当一个新图像添加到该文件夹​​时,我需要在其上运行一个python脚本。

这可能吗?如果是这样,怎么样?我看到的一个可能的解决方案是pyinotify,但没有看到任何有力的例子。

3 个答案:

答案 0 :(得分:8)

我认为watchdog library在这里使用更好的东西,就像提到的那样。我按如下方式使用它来监视新文件的文件夹:

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()

答案 1 :(得分:1)

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()   

答案 2 :(得分:0)

import threading
import glob
import os


f1 = glob.glob('*.txt')
def Status():


  threading.Timer(1.0, Status).start()
  f2 = glob.glob('*.txt')
  f3 =  set(f2) - set(f1)
  if len(f3) == 0:
    print " No new file"
  else:
    print "new file arrived do something"
    print list(f3)[0]

Status()

运行此脚本,并在运行此python脚本的同一目录中逐个复制文本文件。它将告诉您最近复制的文件的名称。您可以添加更复杂的条件检查(仅通过简单的示例代码即可),并且可以对新到达的文本文件执行所需的操作。

输出将是这样的:

 No new file
 No new file
 No new file
 No new file
 No new file
new file arrived do something
File_request.txt
new file arrived do something
File_request.txt
new file arrived do something
File_request (another copy).txt
new file arrived do something
File_request (another copy).txt
new file arrived do something
File_request (3rd copy).txt
new file arrived do something
File_request (3rd copy).txt
new file arrived do something
File_request (4th copy).txt
new file arrived do something
File_request (4th copy).txt
new file arrived do something
File_request (4th copy).txt
new file arrived do something
File_request (5th copy).txt
new file arrived do something
File_request (5th copy).txt

警告::该代码是为了演示与查询相关的基本概念,我没有检查此代码的健壮性。