我有一个脚本正在观看要接收的文件的文件夹。如果在X时间内未收到文件我想要收到警报,如果收到,我想退出脚本。我计划使用Windows计划任务来启动/停止脚本(因为我不知道如何在Python中回收它)。我目前只是试图退出Watchdog / Python WHEN文件被收到(因为我只想要警报,如果不是)。
在Handler类中,如果检测到event.event_type,我在quitter函数上添加了一个调用。但是,它不会退出并持续到达超时值。
这是我到目前为止所拥有的:
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import smtplib
import sys
file_rec = False
class Watcher:
DIRECTORY_TO_WATCH = r"C:\Temp"
def __init__(self):
self.observer = Observer()
def run(self):
t_end = time.time() + 5 * 3 # Configure timeout value
global file_rec
event_handler = Handler()
self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=False)
self.observer.start()
try:
while not file_rec:
if time.time() > t_end: # If timeout reached file not created -- send email
email()
else:
time.sleep(5)
except:
self.observer.stop()
print("Error")
self.observer.join()
class Handler(FileSystemEventHandler):
@staticmethod
def on_any_event(event):
if event.is_directory:
return None
elif event.event_type == 'created':
# File has been received, can now quit watching
global file_rec
file_rec = True
quitter()
if __name__ == '__main__':
def email():
createMsg = "File XXX on Server XXX has not been received, manual intervention required."
sender = 'NoReply@mydomain.com'
receiver = 'test.user@mydomain.com'
message = """From: No Reply <NoReply@mydomain.com>
TO: Test User <test.user@mydomain.com>
Subject: File Not Received
Attention Required: """ + str(createMsg)
mail = smtplib.SMTP('email.mydomain.com', 25)
mail.ehlo()
#mail.starttls()
mail.sendmail(sender, receiver, message)
mail.close()
quitter()
def quitter():
sys.exit()
w = Watcher()
w.run()
答案 0 :(得分:0)
我遇到了同样的问题。我解决了将观察者传递给处理程序扩展构造函数
的问题from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
def __init__(self, observer):
object.__init__(self)
self.observer = observer
def process(self, event):
"""
event.event_type
'modified' | 'created' | 'moved' | 'deleted'
event.is_directory
True | False
event.src_path
path/to/observed/file
"""
# the file will be processed there
print event.src_path, event.event_type # print now only for debug
self.observer.stop()
print "stopped"
def on_modified(self, event):
self.process(event)
def on_created(self, event):
self.process(event)