tail -f en Python
Le but est réaliser une version minimaliste sans prétention de la commande unix tail avec l’option -f. Donc le but est de suivre le contenu d’un fichier comme une log.
J’ai commencé par créer une bibliothèque (libtail) qui porte la fonction tail.
#!/usr/bin/env python3
from time import sleep
def tail (filename, n=0, polling=0.01):
  num_lines = sum(1 for line in open(filename))
  f = open(filename,'r')
  cpt = 0
  while cpt < num_lines - n :
    cpt += 1
    next(f)
  try:
    while True:
      try:
        l = next(f)
        print(filename,":",l[:-1])
      except:
        sleep(polling)
  except:
    f.close()
Et un main.py qui l’appel…
#!/usr/bin/env python3
from libtail import tail
from sys import argv
if len(argv) != 2:
  print("""utilisation:
%s FICHIER"""%argv[0])
  exit(1)
tail(argv[1])