Esta vez voy a referirme a un modulo de Python muy pero muy interesante, se llama pyinotify. ¿Que hace? pues nada mas ni nada menos que mirar un directorio que especifiquemos e informarnos de cualquier cambio que suceda en el (los cambios que nosotros le indiquemos que informe claro), de esta manera podremos saber el nombre del archivo que fue eliminado, movido, pegado asi como tambien cambios de nombre, permisos, atributos etc.
Esto lo hace a travez de una utilidad del Kernel de Linux llamada “inotify” mirando inodos entonces Pyinotify es un puente entre el kernel y python. Como están pensando existen varias bibliotecas para diversos lenguajes, pero ninguna tan facil de usar como la implementación de Python (por lo menos mas facil que las de C y C++).
Les voy a dejar un ejemplo de mi aplicación ,despues del salto, (se trata de un proyecto que no esta terminado) tome el ejemplo de la pagina y lo modifique para lo que necesitaba:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pyinotify import WatchManager, Notifier,ThreadedNotifier, ProcessEvent,IN_CREATE,IN_DELETE, IN_MODIFY, IN_ATTRIB, IN_MOVED_FROM, IN_MOVED_TO, IN_MOVE_SELF
import os
import conectar
import archivos
import enviar_archivo
import desconexion
wm = WatchManager() # Watch Manager
mask = IN_CREATE | IN_DELETE | IN_MODIFY | IN_ATTRIB | IN_MOVED_FROM | IN_MOVED_TO | IN_MOVE_SELF # watched events
class PTmp(ProcessEvent):
def __init__(self):
self.nombre_de_archivo=''
self.nombre_de_ruta=''
self.accion=''
self.indicador_borrado=False
self.archivo_a_borrar = ''
self.nombre_antiguo=''
def process_IN_MOVED_TO(self, event):
try:
con_Cliente = conectar.crear_conexion()
conex_Cliente=con_Cliente.Get_socket_cliente(9999)
transferencia=True
except:
print 'Error de conexion con el servidor...creando log'
log = archivos.Escribir_archivo('log.rlp','config/')
transferencia=False
print 'Movido a: ' , event.pathname
if (self.archivo_a_borrar==event.path):
print 'Renombrar'
self.accion='renombrar'
if transferencia==True:
enviar_archivo.enviar(conex_Cliente,0, self.accion,event.path,event.name,self.nombre_antiguo)
else:
print nombre_archivo
print 'Operacion sin conexion'
else:
print 'Mover dentro'
self.indicador_borrado=True
def process_IN_MOVED_FROM(self, event):
print "Movido desde: ", event.pathname
self.nombre_antiguo=event.name
self.accion='eliminar'
try:
con_Cliente = conectar.crear_conexion()
conex_Cliente=con_Cliente.Get_socket_cliente(9999)
enviar_archivo.enviar(conex_Cliente,0, self.accion,event.path,event.name,0)
except:
print 'Error de conexion con el servidor...creando log'
log = archivos.Escribir_archivo('log.rlp','config/')
def process_IN_MODIFY(self, event):
print "Modificacion: ", event.pathname
def process_IN_ATTRIB(self, event):
print "Modify attribute: ", event.pathname
def process_IN_CREATE(self, event):
try:
con_Cliente = conectar.crear_conexion()
conex_Cliente=con_Cliente.Get_socket_cliente(9999)
transferencia=True
except:
print 'Error de conexion con el servidor...creando log'
log = archivos.Escribir_archivo('log.rlp','config/')
transferencia=False
print 'crear'
self.accion = 'crear'
if transferencia==True and os.path.isdir(str(event.pathname))==False and self.nombre_antiguo=='':
self.Archivo = archivos.Leer_archivo(event.name, event.path)
enviar_archivo.enviar(conex_Cliente,self.Archivo, self.accion,event.path,event.name,1)
elif transferencia==True and os.path.isdir(str(event.pathname))==True and self.nombre_antiguo=='':
self.accion='crear directorio'
enviar_archivo.enviar(conex_Cliente,0, self.accion,event.path,event.name,1)
else:
print event.name
self.nombre_antiguo=''
print 'Operacion sin conexion'
def process_IN_DELETE(self, event):
print archivos.Ruta_relativa(event.path,'/home/cleve/Descargas')
(filepath, filename) = os.path.split(str(event.pathname))
self.nombre_de_archivo=filename
self.nombre_de_ruta=filepath
self.accion='borrar'
print "Borrando:", self.nombre_de_archivo, ' en: ',self.nombre_de_ruta
def process_IN_MOVE_SELF(self, event):
print 'Entrando a borrado de archivo'
p = PTmp()
notifier = Notifier(wm, p)
wdd = wm.add_watch('/home/cleve/Descargas', mask, rec=True, auto_add=True)
notifier.loop()
Comentarios