2012-06-09 88 views
0

新編碼器在這裏pyinotify代碼清理smtplib

我希望能夠清理這個代碼了一下。我希望能夠將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 = "[email protected]" 
    FROM = "[email protected]" 
    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 = "[email protected]" 
    FROM = "[email protected]" 
    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 
+0

你能說出你在想什麼,你試過了嗎? –

+0

請求諮詢工作在這裏是焦點話題。如果代碼有效,你可以嘗試http://codereview.stackexchange.com –

回答

0

如果你想使你的代碼更好的什麼可以做的第一件事是發生在單獨的文件中所有的常量,像myapp.conf:

SUBJECT = {'dc':'Directory changed', 'sf':'Server fault' and etc} 
TO = '[email protected]' 
FROM = '[email protected]' 
and etc ... 

形成郵件正文,你可以使用模板像Mako這樣的引擎,並且可以將郵件模板放置到另一個單獨的文件中。你可以將你的類實現從主代碼中分離出來。之後,您的代碼將保持更靈活,維護更容易。