tail

privex.helpers.common.tail(filename: str, nlines: int = 20, bsz: int = 4096) → List[str][source]

Pure python equivalent of the UNIX tail command. Simply pass a filename and the number of lines you want to load from the end of the file, and a List[str] of lines (in forward order) will be returned.

This function is simply a wrapper for the highly efficient io_tail(), designed for usage with a small (<10,000) amount of lines to be tailed. To allow for the lines to be returned in the correct order, it must load all nlines lines into memory before it can return the data.

If you need to tail a large amount of data, e.g. 10,000+ lines of a logfile, you should consider using the lower level function io_tail() - which acts as a generator, only loading a certain amount of bytes into memory per iteration.

Example file /tmp/testing:

this is an example 1
this is an example 2
this is an example 3
this is an example 4
this is an example 5
this is an example 6

Example usage:

>>> from privex.helpers import tail
>>> lines = tail('/tmp/testing', nlines=3)
>>> print("\n".join(lines))
this is an example 4
this is an example 5
this is an example 6
Parameters
  • filename (str) – Path to file to tail. Relative or absolute path. Absolute path is recommended for safety.

  • nlines (int) – Total number of lines to retrieve from the end of the file

  • bsz (int) – Block size (in bytes) to load with each iteration (default: 4096 bytes). DON’T CHANGE UNLESS YOU UNDERSTAND WHAT THIS MEANS.

Return List[str] lines

The last ‘nlines’ lines of the file ‘filename’ - in forward order.