I am trying to learn to use watchdog utility on windows.
I have gone through basic examples available on google. I am trying to write a script which will monitor a given directory and then will send mail if any sub-directory is created which has a file named version.
import time
from watchdog.observers import Observer
from watchdog.events import DirCreatedEvent
import re
import smtplib
class MyHandler(DirCreatedEvent):
def process(self,event):
fileTocheck = "Version"
with open(event.src_path+"\\"+fileTocheck) as version:
chngstring = version.read()
changeNumber = re.findall(r"\D(\d{5})\D",chngstring)
if not changeNumber:
return
server = smtplib.SMTP('smtp.gmail.com',587)
server.login("xyz@gmail.com","abc@123")
message = "New Build has been create with Chnage Number %d" %int(changeNumber[0])
server.sendmail("xyz@gmail.com","abc@gmail.com",message)
def on_created(self,event):
self.process(event)
if __name__ == '__main__':
observer = Observer()
path = "D:\\"
observer.schedule(MyHandler(),path,recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
The problem is that whenever I am running the script I am getting this error:
>>> ================================ RESTART ================================
>>>
Traceback (most recent call last):
File "C:/Users/Prince/Desktop/KeepLearing/Watchdog.py", line 37, in <module>
observer.schedule(MyHandler(),path,path,recursive=True)
TypeError: __init__() missing 1 required positional argument: 'src_path'
I am providing proper path while envoking observer.schedule, I don't understand why I am getting this.
Please help me find out what I am missing.
The error is here:
class MyHandler(DirCreatedEvent):
You've made your handler a subclass of DirCreatedEvent
. The error is arising because DirCreatedEvent
's __init__
method, which you are not overriding in your MyHandler
class, has one parameter, named src_path
, and when you create a handler using MyHandler()
, you're not passing in any value for this parameter.
It would be more correct to say your handler handles events than to say your handler is an event. So instead of subclassing DirCreatedEvent
, you need to subclass an event handler, and FileSystemEventHandler
seems to be the one you want.
So, change the above line to
class MyHandler(FileSystemEventHandler):
Also, import the FileSystemEventHandler
class from watchdog.events
.
Note that your MyHandler
class will receive events for file creation as well as for directory creation. The easiest way to ignore them is to modify your on_created
method to:
def on_created(self,event):
if isinstance(event, DirCreatedEvent):
self.process(event)