Search code examples
pythonwindowswatchdogpython-watchdog

Traceback error when using Watchdog on Python


I'm trying to make a script that sends an e-mail once it is detected that I copy a file in a specified folder, using some parts of code that I found on internet researching and now I'm stuck with this error.

import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os.path

class Watcher:
    DIRECTORY_TO_WATCH = "/Documents/ReportesSemanales"

    def __init__(self):
        self.observer = Observer()

    def run(self):
        event_handler = Handler()
        self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=True)
        self.observer.start()
        try:
            while True:
                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':
            # Take any action here when a file is first created.
                def send_email(email_recipient,
               email_subject,
               email_message,
               attachment_location = ''):

                    email_sender = '[email protected]'

                    msg = MIMEMultipart()
                    msg['From'] = email_sender
                    msg['To'] = email_recipient
                    msg['Subject'] = email_subject

                    msg.attach(MIMEText(email_message, 'plain'))

                    if attachment_location != '':
                        filename = os.path.basename(attachment_location)
                        attachment = open(attachment_location, "rb")
                        part = MIMEBase('application', 'octet-stream')
                        part.set_payload(attachment.read())
                        encoders.encode_base64(part)
                        part.add_header('Content-Disposition',
                                        "attachment; filename= %s" % filename)
                        msg.attach(part)

                    try:
                        server = smtplib.SMTP('smtp.office365.com', 587)
                        server.ehlo()
                        server.starttls()
                        server.login('[email protected]', 'MyPassword')
                        text = msg.as_string()
                        server.sendmail(email_sender, email_recipient, text)
                        print('email sent')
                        server.quit()
                    except:
                        print("SMPT server connection error")
                    return True

                send_email('[email protected]',
                        'Happy New Year',
                        'We love Outlook', 
                        '/ReportesSemanales/Bitacora-Diaria.xlsx')
                print("Received created event - %s." % event.src_path)
        elif event.event_type == 'modified':
            # Taken any action here when a file is modified.
            print("Received modified event - %s." % event.src_path)


if __name__ == '__main__':
    w = Watcher()
    w.run()

I already installed watchdog api and when I run the script, I receive the error in terminal:

Traceback (most recent call last):
  File "SendEmail.py", line 90, in <module>
    w.run()
  File "SendEmail.py", line 22, in run
    self.observer.start()
  File "C:\Users\MyUser\AppData\Local\Programs\Python\Python38-32\lib\site-packages\watchdog\observers\api.py", line 260, in start
    emitter.start()
  File "C:\Users\MyUser\AppData\Local\Programs\Python\Python38-32\lib\site-packages\watchdog\utils\__init__.py", line 110, in start
    self.on_thread_start()
  File "C:\Users\MyUser\AppData\Local\Programs\Python\Python38-32\lib\site-packages\watchdog\observers\read_directory_changes.py", line 66, in on_thread_start
    self._handle = get_directory_handle(self.watch.path)
  File "C:\Users\MyUser\AppData\Local\Programs\Python\Python38-32\lib\site-packages\watchdog\observers\winapi.py", line 307, in get_directory_handle
    return CreateFileW(path, FILE_LIST_DIRECTORY, WATCHDOG_FILE_SHARE_FLAGS,
  File "C:\Users\MyUser\AppData\Local\Programs\Python\Python38-32\lib\site-packages\watchdog\observers\winapi.py", line 113, in _errcheck_handle
    raise ctypes.WinError()
FileNotFoundError: [WinError 3] The system cannot find the path specified.

How can I solve this?

Specifications:

OS: Windows 10 Python Version: Python 3.8.3 Editing: Visual Studio


Solution

  • This line:

    FileNotFoundError: [WinError 3] The system cannot find the path specified.
    

    Means just what it says: somewhere during the execution of the python script, one of the paths that you specified in your code was not found.

    This is commonly caused by typos in path definitions. In your case, it might be caused by mistakenly using forward slashes ( / ) in your paths instead of backslashes, ( \ ). While forward slashes are used in Linux / UNIX systems, Windows uses backslashes.

    Try changing this line:

    DIRECTORY_TO_WATCH = "/Documents/ReportesSemanales"
    

    to this:

    DIRECTORY_TO_WATCH = "\Documents\ReportesSemanales"
    

    And do the same for the send_email() function call, where you specify the path to the .xlsx file. If you still have errors, check if you have any typos in the path, and whether the folders and files that you specified actually exist.