Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I want to be able to run this script in the background on a linux machine. Not really doing a program.py & but if you notice to kill the notify process I have a try & except statement that kills the process on keyboard interupt. I want the program to continue to loop until I kill it or the system kills it manually. I apologize in advanced for my code. New to this.

Thanks

#!/usr/bin/python

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 = "%s" % output
    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
share|improve this question

1 Answer

I figured it out. It is not the best code but after reading some information and using the daemon.py example from pyinotify I was able to have the script do what I need it to do. I still think this code needs some cleaning up. Either way I'm new to python so any input would be great. Thanks

I added:

import functools
import sys
import pyinotify
import os, time, smtplib, string
from pyinotify import WatchManager, Notifier, ThreadedNotifier, EventsCodes, ProcessEvent


class Counter(object):
    """
    Simple counter.
    """
    def __init__(self):
        self.count = 0
    def plusone(self):
        self.count += 1

def on_loop(notifier, counter):
    """
    Dummy function called after each event loop, this method only
    ensures the child process eventually exits (after 5 iterations).
    """
    if counter.count > 4:
        # Loops 5 times then exits.
        sys.stdout.write("Exit\n")
        notifier.stop()
        sys.exit(0)
    else:
        sys.stdout.write("Loop %d\n" % counter.count)
        counter.plusone()

    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 = "%s" % output
        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()


    wm = pyinotify.WatchManager()
    notifier = pyinotify.Notifier(wm, PTmp())
    wm.add_watch('/var/test', pyinotify.ALL_EVENTS)
    on_loop_func = functools.partial(on_loop, counter=Counter())

    try:
        notifier.loop(daemonize=True, callback=on_loop_func,
              pid_file='/tmp/pyinotify.pid', stdout='/tmp/stdout.txt')
        notifier.process_events()
        if notifier.check_events():
            notifier.read_events()
    except pyinotify.NotifierError, err:
        print >> sys.stderr, err
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.