创建新文件时运行python脚本 [英] Running a python script when a new file is created
本文介绍了创建新文件时运行python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个存储一堆jpg图像的文件夹.将新图像添加到此文件夹后,我需要在其上运行python脚本.
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.
这可能吗?如果是这样,怎么办?我看到的一个可能的解决方案是 pyinotify ,但没有看到任何可靠的示例.
Is this possible? If so, how? One potential solution I saw was pyinotify but have not seen any robust examples of it.
推荐答案
我认为看门狗库是如此处所说的火化器,这是一个更好的选择.我使用它来监视文件夹中的新文件:
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()
这篇关于创建新文件时运行python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文