python - 在 Python 上使用 Watchdog 时出现回溯错误
问题描述
我正在尝试制作一个脚本,一旦检测到我在指定文件夹中复制了一个文件,我就会使用我在互联网研究中找到的一些代码部分来发送电子邮件,现在我遇到了这个错误。
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()
,在其中指定.xlsx
文件的路径。如果仍然有错误,请检查路径中是否有任何拼写错误,以及您指定的文件夹和文件是否确实存在。
推荐阅读
- python - Python:使用带有本地函数的for循环将数据帧拆分为多个数据帧
- flutter - 升级到最新 Flutter Stable 版本后 CachedNetworkImage 抛出错误
- python - 如何使用 .pkl 文件预测图像
- python - 使用 for 循环写入文件
- python-3.x - 在使用 Python3 解析 ElementTree 模块时尝试在 XML 文件中间插入元素时出现问题
- java - Java将变量传递给映射的DTO方法?
- mysql - 无法建立数据库错误。是什么原因造成的?
- c# - 是否可以使用 Google.Cloud.Vision 检测性别
- python - 在一个循环中获取和打印数据
- android - AWSMobileClient:访问令牌未自动刷新