0

新编码器在这里

我希望能够稍微清理一下这段代码。我希望能够将 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
4

1 回答 1

0

如果你想让你的代码更好,可以做的第一件事就是将所有常量放在单独的文件中,比如 myapp.conf:

 SUBJECT = {'dc':'Directory changed', 'sf':'Server fault' and etc}
 TO = 'user@localhost'
 FROM = 'user@localhost'
 and etc ...

为了形成邮件正文,您可以使用像 Mako 这样的模板引擎,并使用它您可以将邮件模板放置到另一个单独的文件中。你可以将你的类实现与主代码分开。之后,您的代码将保持更灵活,并且更易于维护。

于 2012-06-09T07:51:43.183 回答