这里有新的编码器
我希望能够清理一下这段代码。我希望能够将smtplib内容移出类,但我仍然需要它来发送包含pinotify数据的电子邮件,如果你看了我的代码,你就会明白。这是非常多余的。
如果通知数据>发送包含文件创建数据的电子邮件
如果通知数据>发送包含已删除文件数据的电子邮件
我如何才能巩固这一点。
import os, pyinotify, time, smtplib, string
from pyinotify import WatchManager, Notifier, ThreadedNotifier, EventsCodes, ProcessEvent
wm = WatchManager()
mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE # Watched Events
class PTmp(ProcessEvent):
def process_IN_CREATE(self,event):
output = "Created: %s " % os.path.join(event.path, event.name)
localtime = time.asctime( time.localtime(time.time()) )
final = output + localtime
SUBJECT = "Directory Changed"
TO = "user@localhost"
FROM = "user@domain.net"
text = final
BODY = string.join((
"From: %s" % FROM,
"To: %s" % TO,
"Subject: %s" % SUBJECT ,
"",
text
), "\r\n")
s=smtplib.SMTP('localhost')
s.sendmail(FROM, TO, BODY)
s.quit()
def process_IN_DELETE(self,event):
output = "Removed: %s" % os.path.join(event.path, event.name)
localtime = time.asctime( time.localtime(time.time()) )
final = output + localtime
SUBJECT = "Directory Changed"
TO = "user@localhost"
FROM = "user@domain.net"
text = final
BODY = string.join((
"From: %s" % FROM,
"To: %s" % TO,
"Subject: %s" % SUBJECT ,
"",
text
), "\r\n")
s=smtplib.SMTP('localhost')
s.sendmail(FROM, TO, BODY)
s.quit()
notifier=Notifier(wm, PTmp())
wdd=wm.add_watch('/var/test',mask,rec=True)
while True: # Loop Forever
try:
# process the queue of events as explained above
notifier.process_events()
if notifier.check_events():
# read notified events and enqeue them
notifier.read_events()
except KeyboardInterupt:
# Destroy the inotify's instance on this interupt(stop monitoring)
notiifier.stop()
break发布于 2012-06-09 15:51:43
如果你想让你的代码更好,你可以做的第一件事就是把你所有的常量放在单独的文件中,比如myapp.conf:
SUBJECT = {'dc':'Directory changed', 'sf':'Server fault' and etc}
TO = 'user@localhost'
FROM = 'user@localhost'
and etc ...为了形成邮件正文,您可以使用像Mako这样的模板引擎,并使用它将邮件模板放到另一个单独的文件中。而且你可以把你的类实现和主代码分开。在此之后,您的代码将保持更灵活,并且将更容易维护。
https://stackoverflow.com/questions/10957842
复制相似问题