首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >pyinotify代码清理smtplib

pyinotify代码清理smtplib
EN

Stack Overflow用户
提问于 2012-06-09 10:09:15
回答 1查看 202关注 0票数 0

这里有新的编码器

我希望能够清理一下这段代码。我希望能够将smtplib内容移出类,但我仍然需要它来发送包含pinotify数据的电子邮件,如果你看了我的代码,你就会明白。这是非常多余的。

如果通知数据>发送包含文件创建数据的电子邮件

如果通知数据>发送包含已删除文件数据的电子邮件

我如何才能巩固这一点。

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-06-09 15:51:43

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

代码语言:javascript
复制
 SUBJECT = {'dc':'Directory changed', 'sf':'Server fault' and etc}
 TO = 'user@localhost'
 FROM = 'user@localhost'
 and etc ...

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10957842

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档