Advertisement
Guest User

Python verify changes in a text file v2

a guest
Feb 17th, 2020
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.14 KB | None | 0 0
  1. import os, time, sys
  2.  
  3. # Segundos.
  4. update_interval = 1
  5. # Tiempo de modificacion antiguo.
  6. _after_timestamp = 0
  7. # Tiempo de modificacion nuevo.
  8. _before_timestamp = 0
  9. # Variable que indica volver a abrir el archivo para leearlo.
  10. _open_file_and_read = True
  11. # Argumento: El archivo a leer.
  12. the_file = sys.argv[1]
  13.  
  14. file_opened = None
  15.  
  16.  
  17. # Funcion simple que permite verificar el tiempo de modificacion de un archivo
  18. check_mod_timestamp = lambda file_: int(os.stat(file_).st_mtime)
  19.  
  20.  
  21. # verificar el tiempo de modificacion del archivo
  22. _before_timestamp = check_mod_timestamp(the_file)
  23.  
  24.  
  25.  
  26. # Primero leemos el archivo, despues esperamos 1 segundo, posteriormente verificamos que
  27. # el archivo no se ha modificado, si lo hizo entonces imprimimos la siguiente linea:
  28. # === {file} has been modified :: {time} ===
  29. # === file.txt has been modified :: Mon Feb 17 22:22:46 2020 ===
  30. #
  31. # Despues de hacer eso se muestra el texto del "nuevo" archivo.
  32. def start():
  33.     # las variables declaradas fuera de una funcion son globales (aunque no se modifican globalmente dentro de una funcion)
  34.     # pero al declarar una variable con "_" ( _variable ), es como si declararamos una variable "privada" en python.
  35.     # https://stackoverflow.com/questions/1641219/does-python-have-private-variables-in-classes
  36.     global _open_file_and_read, _before_timestamp, _after_timestamp
  37.     global file_opened
  38.    
  39.     while True:
  40.         if(_open_file_and_read):
  41.             _open_file_and_read = False
  42.             file_opened = open(the_file, 'r')
  43.            
  44.             for line in file_opened.readlines():
  45.                 print(line.rstrip() )
  46.        
  47.         time.sleep(update_interval)
  48.        
  49.         _after_timestamp = check_mod_timestamp(the_file)
  50.        
  51.         if( not (_after_timestamp == _before_timestamp) ):
  52.             _open_file_and_read = True
  53.             _before_timestamp = _after_timestamp
  54.             print(" === {file} has been modified :: {time} ===".format(file=the_file, time=time.ctime(_after_timestamp) ) )
  55.  
  56.  
  57. if(__name__ == '__main__'):
  58.     try:
  59.         start()
  60.     except(KeyboardInterrupt):
  61.         file_opened.close()
  62.         print('')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement