【发布时间】:2017-01-26 05:35:19
【问题描述】:
我只有几周的时间来学习 python,之前没有编程背景,所以我为我的无知道歉..
我正在尝试使用模块组合来监视文件夹中的新文件(看门狗),对任何事件发出警报(日志模块),然后将警报发送到我的电子邮件(smtplib)。
我在这里找到了一个很好的例子:How to run an function when anything changes in a dir with Python Watchdog?
但是,我一直在尝试将日志记录信息保存为变量,以便在我的电子邮件消息中使用。我想知道是否需要将日志信息输出到文件中,然后在行中读取以用作变量。
无论如何,这就是我所拥有的。任何帮助表示赞赏。与此同时,我将继续使用 Google。
import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler
import smtplib
class Event(LoggingEventHandler):
def on_any_event(self, event):
logMsg = logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
sender = 'NoReply@myDomain.com'
receiver = 'test.user@myDomain.com'
message = """From: No Reply <NoReply@myDomain.com>
TO: Test User <test.user@myDomain.com>
Subject: Folder Modify Detected
The following change was detected: """ + str(logMsg)
mail = smtplib.SMTP('mailServer.myDomain.com', 25)
mail.ehlo()
mail.starttls()
mail.sendmail(sender, receiver, message)
mail.close()
if __name__ == "__main__":
path = sys.argv[1] if len(sys.argv) > 1 else '.'
event_handler = Event()
observer = Observer()
observer.schedule(event_handler, path, recursive=False)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
【问题讨论】:
-
我的意思是如果你能记录它,你就知道你在记录什么。只需将该变量取出并通过邮件发送即可?
标签: python email outlook smtplib watchdog