繁体   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