簡體   English   中英

在 Python 上使用看門狗時出現回溯錯誤

[英]Traceback error when using Watchdog on Python

我正在嘗試制作一個腳本,一旦檢測到我在指定文件夾中復制了一個文件,我就會使用我在互聯網研究中找到的一些代碼部分來發送電子郵件,現在我遇到了這個錯誤。

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 = 'MyUser@domain.com'

                    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('MyUser@domain.com', '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('MyUser@hotmail.com',
                        '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()

我已經安裝了看門狗 api,當我運行腳本時,我在終端收到錯誤:

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.

我該如何解決這個問題?

規格:

操作系統:Windows 10 Python 版本:Python 3.8.3 編輯:Visual Studio

這一行:

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

意思就是它所說的:在執行 python 腳本期間的某個地方,找不到您在代碼中指定的路徑之一。

這通常是由路徑定義中的拼寫錯誤引起的。 在您的情況下,這可能是由於在路徑中錯誤地使用正斜杠( / )而不是反斜杠( \ )引起的。 雖然在 Linux / UNIX 系統中使用正斜杠,但 Windows 使用反斜杠。

嘗試更改此行:

DIRECTORY_TO_WATCH = "/Documents/ReportesSemanales"

對此:

DIRECTORY_TO_WATCH = "\Documents\ReportesSemanales"

並對send_email() function 調用執行相同操作,在其中指定.xlsx文件的路徑。 如果仍然有錯誤,請檢查路徑中是否有任何拼寫錯誤,以及您指定的文件夾和文件是否確實存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM