当新文件创建时运行Python脚本

3 投票
3 回答
16455 浏览
提问于 2025-04-18 05:27

我有一个文件夹,里面存放着很多jpg格式的图片。当这个文件夹里添加了一张新图片时,我需要对它运行一个python脚本。

这可能吗?如果可以的话,怎么做呢?我看到一个可能的解决方案是pyinotify,但我没有找到什么很好的例子。

3 个回答

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

警告:这段代码只是用来演示与问题相关的基本概念,我没有检查这段代码的健壮性。

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

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得更简单易懂。

15

我觉得watchdog库在这里是个更好的选择,就像creimers提到的那样。我用它来监控一个文件夹,看看有没有新文件,具体用法如下:

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

撰写回答