1   
  2   
  3   
  4  import fcntl, signal 
  5   
  8          self.watchers = {} 
  9          self.installed = 0 
  11          if self.installed: 
 12              return 
 13          signal.signal(signal.SIGIO, self.fire) 
 14          self.installed = 1 
  16          if not self.installed: 
 17              return 
 18          signal.signal(signal.SIGIO, signal.SIG_DFL) 
 19          self.installed = 0 
  20 -    def add(self, watcher): 
  28 -    def fire(self, signum, frame): 
  29           
 30           
 31          for watcher in self.watchers.values(): 
 32              watcher.callback() 
   33               
 35      DN_ACCESS = fcntl.DN_ACCESS   
 36      DN_MODIFY = fcntl.DN_MODIFY   
 37      DN_CREATE = fcntl.DN_CREATE   
 38      DN_DELETE = fcntl.DN_DELETE   
 39      DN_RENAME = fcntl.DN_RENAME   
 40      DN_ATTRIB = fcntl.DN_ATTRIB   
 41   
 42      handler = [None] 
 43       
 46   
 47          """This object watches a directory for changes. The .callback 
 48          attribute should be set to a function to be run every time something 
 49          happens to it. Be aware that it will be called more times than you 
 50          expect.""" 
 51   
 52          if callback: 
 53              self.callback = callback 
 54          else: 
 55              self.callback = self.fire 
 56          self.dirname = dirname 
 57          self.flags = reduce(lambda x, y: x | y, flags) | fcntl.DN_MULTISHOT 
 58          self.fd = open(dirname, "r") 
 59           
 60           
 61           
 62           
 63          if not self.handler[0]: 
 64              self.handler[0] = DNotify_Handler() 
 65          self.handler[0].add(self) 
 66          fcntl.fcntl(self.fd, fcntl.F_NOTIFY, self.flags) 
  71          print self.dirname, "changed!" 
   72   
 74      d = DNotify(".") 
 75      while 1: 
 76          signal.pause() 
  77   
 79       
 80       
 81       
 82       
 83      count = [0] 
 84      d1 = DNotify(".") 
 85      def fire1(count=count, d1=d1): 
 86          print "./ changed!", count[0] 
 87          count[0] += 1 
 88          if count[0] > 5: 
 89              d1.remove() 
 90              del(d1) 
  91       
 92       
 93      d1.callback = fire1 
 94      def fire2(): print "foo/ changed!" 
 95      d2 = DNotify("foo", fire2) 
 96      while 1: 
 97          signal.pause() 
 98           
 99       
100  if __name__ == '__main__': 
101      test_dnotify2() 
102