Tailer - GNU tail/head in Python
Tailer is a Python library that provides simple implementations of the GNU `tail` and `head` utilities, allowing you to read the last few lines of a file or follow a file for new content as it's written. The current version is 0.4.1, and the project has a low release cadence, indicating stability for its core functionality.
Common errors
-
TypeError: argument of type 'str' is not iterable
cause Attempting to pass a file path string directly to `tailer.tail`, `tailer.head`, or `tailer.follow` instead of an opened file object.fixOpen the file first and pass the file object: `with open('my_file.log', 'r') as f: tailer.tail(f, 10)`. -
FileNotFoundError: [Errno 2] No such file or directory: 'non_existent_file.log'
cause The file specified in the `open()` call does not exist at the provided path.fixVerify the file path is correct and the file exists before attempting to open it. Use `os.path.exists('your_file.log')` for robust error handling. -
Program appears to hang or loop indefinitely without output.
cause This typically occurs when using `tailer.follow()` on a file that is not actively being written to. The generator waits for new content and will not yield or terminate.fixEnsure the file being followed is actively receiving new data. For testing, manually append content to the file. In production, be aware of `follow`'s blocking nature and implement appropriate termination logic.
Warnings
- gotcha Tailer functions (tail, head, follow) expect an *open file object*, not a file path string. Passing a string will result in a TypeError or incorrect behavior.
- gotcha `tailer.follow()` is a blocking generator. It will continuously yield new lines as they are written to the file and will not terminate until the process is stopped or the generator is explicitly broken out of.
- deprecated The `tailer` library has not been updated since 2017 (version 0.4.1). While stable for its intended purpose, it may not leverage newer Python features, handle modern asynchronous patterns, or receive security updates.
Install
-
pip install tailer
Imports
- tail
import tailer tailer.tail(...)
- head
import tailer tailer.head(...)
- follow
import tailer tailer.follow(...)
Quickstart
import tailer
import os
# Create a dummy log file for demonstration
file_path = 'my_log_file.log'
with open(file_path, 'w') as f:
f.write('Line 1\n')
f.write('Line 2\n')
f.write('Line 3\n')
f.write('Line 4\n')
f.write('Line 5\n')
f.write('Line 6\n')
# Read the last 3 lines using tailer.tail
print(f"Reading last 3 lines of '{file_path}':")
with open(file_path, 'r') as f:
for line in tailer.tail(f, 3):
print(line.strip())
# Read the first 2 lines using tailer.head
print(f"\nReading first 2 lines of '{file_path}':")
with open(file_path, 'r') as f:
for line in tailer.head(f, 2):
print(line.strip())
# Cleanup the dummy file
os.remove(file_path)