【问题标题】:pyinotify code cleanup smtplib [closed]pyinotify 代码清理 smtplib [关闭]
【发布时间】:2012-06-09 02:09:14
【问题描述】:

这里是新编码器

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

【问题讨论】:

  • 您能否列出您的想法和尝试过的内容?
  • 咨询工作的请求在这里是题外话。如果代码有效,您可以尝试codereview.stackexchange.com

标签: python smtplib pyinotify


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-26
    • 2010-11-17
    • 2011-07-11
    • 2010-12-03
    相关资源
    最近更新 更多